gpt4 book ai didi

c# - Entity Framework 的双重自引用属性

转载 作者:太空狗 更新时间:2023-10-29 23:10:46 25 4
gpt4 key购买 nike

这段代码代表了我的小规模问题:

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

public virtual Person Parent { get; set; }
public virtual ICollection<Person> Friends { get; set; }
}

当我在 Entity Framework (4.1) 场景中使用此类时,系统会生成一个唯一的关系,认为 Parent 和 Friends 是同一关系的两个面。

我怎么知道在语义上分离属性,并在 SQL Server 中生成两个不同的关系(因为我们可以看到 Friends 与 Parents 完全不同 :-))。

我试过使用流畅的界面,但我想我不知道正确的调用。

感谢大家。

安德烈比奥利

最佳答案

您可以在 Fluent API 中使用它:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasMany(p => p.Friends)
.WithOptional()
.Map(conf => conf.MapKey("FriendID"));

modelBuilder.Entity<Person>()
.HasOptional(p => p.Parent)
.WithMany()
.Map(conf => conf.MapKey("ParentID"));
}

我在这里假设关系是可选的。 People 表现在有两个外键 FriendIDParentID。像这样的东西应该可以工作:

using (var context = new MyContext())
{
Person person = new Person() { Name = "Spock", Friends = new List<Person>()};
Person parent = new Person() { Name = "Sarek" };
Person friend1 = new Person() { Name = "Kirk" };
Person friend2 = new Person() { Name = "McCoy" };

person.Parent = parent;
person.Friends.Add(friend1);
person.Friends.Add(friend2);

context.People.Add(person);

context.SaveChanges();

// Load with eager loading in this example
var personReloaded = context.People
.Where(p => p.Name == "Spock")
.Include(p => p.Parent)
.Include(p => p.Friends)
.First();
}

关于c# - Entity Framework 的双重自引用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5513755/

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