gpt4 book ai didi

c# - Entity Framework 与相同实体类型但具有不同关系类型的多对多关系

转载 作者:行者123 更新时间:2023-11-30 20:50:13 24 4
gpt4 key购买 nike

使用 Entity Framework 6,我有一个 Person 类...

public class Person
{
public int ID { get; set; }
public string Name { get; set; }

public virtual ICollection<Relationship> Relationships { get; set; }
}

和一个关系类

public class Relationship
{
public int ID { get; set; }
public RelationshipType DependencyType { get; set; }

[ForeignKey("Person")]
public int PersonID { get; set; }
public virtual Person Person { get; set; }

public virtual ICollection<Person> RelatedPersons { get; set; }

}

我想要它代表的是,例如,我可能将 sibling 作为一种关系类型,将 UnclesAndAunts 作为另一种关系类型,并保持这些类型的关系,而无需知道 parent 是谁,因为他们可能不在数据库中.

使用 Code First,这会生成一个表模式......

CREATE TABLE [dbo].[Person](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[Relationship_ID] [int] NULL)

CREATE TABLE [dbo].[Relationship](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RelationshipType] [int] NOT NULL,
[PersonID] [int] NOT NULL,
[Person_ID] [int] NULL)

PersonID is the main Person of this relationship.
Person_ID is the Person to whom the main person is related to.
I would see the Relationship table containing repeated PersonID data.

问题在于,由于 Person 表中的 Relationship_ID,这表示 Person 表将具有重复数据,而我希望 Relationship 表具有重复数据,例如

Relationship...

ID RelationshipType PersonID Person_ID
---------------------------------------------
1 Sibling 1 2
2 Sibling 1 3
3 UnclesAndAunts 1 4

谁能告诉我应该如何用模型类表示它,我假设我需要包含一些属性或其他属性。

谢谢

最佳答案

Relationship_ID 来自 Relationship.RelatedPersons 集合。我认为这里有一个 collection 是不正确的,它应该是一个 reference RelatedPerson (单数)因为一个 Relationship 实体描述了恰好两个 人之间的关系,而不是一个人与其他人的集合之间的关系。所以,我建议像这样更改模型:

public class Person
{
public int ID { get; set; }
public string Name { get; set; }

[InverseProperty("Person")]
public virtual ICollection<Relationship> Relationships { get; set; }
}

public class Relationship
{
public int ID { get; set; }
public RelationshipType DependencyType { get; set; }

[ForeignKey("Person")]
public int PersonID { get; set; }
public virtual Person Person { get; set; }

[ForeignKey("RelatedPerson")]
public int RelatedPersonID { get; set; }
public virtual Person RelatedPerson { get; set; }
}

[InverseProperty] 属性在这里很重要,它告诉 EF Relationship.PersonPerson.Relationships 的反向导航属性。如果没有该属性,您将在 Relationship 表中获得 三个 外键,这些外键引用 Person 表。

您可能还需要为其中一个关系禁用级联删除,以避免有关从 PersonRelationship 的禁止多个级联删除路径的异常。可以使用 Fluent API 来完成:

modelBuilder.Entity<Relationship>()
.HasRequired(r => r.RelatedPerson)
.WithMany()
.HasForeignKey(r => r.RelatedPersonID)
.WillCascadeOnDelete(false);

一旦你有了它,你就可以添加第二个与 Fluent API 的关系,这将允许你从模型中删除所有属性,因为它们是多余的:

modelBuilder.Entity<Relationship>()
.HasRequired(r => r.Person)
.WithMany(p => p.Relationships)
.HasForeignKey(r => r.PersonID);

关于c# - Entity Framework 与相同实体类型但具有不同关系类型的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22712199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com