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

标签 c# entity-framework entity-framework-4 code-first entity-framework-4.1

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

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/

相关文章:

c# - 在 Entity Framework 中跨多个表进行选择,从而产生通用的 IQueryable?

entity-framework - 如何将我自己的约定添加到 EF 4.3(使列大写)

entity-framework-4 - LINQ to Entities 不支持指定的类型成员。仅支持初始值设定项、实体成员和实体导航属性

c# - 将已编译的 Func 方法添加在一起的目的是什么?

c# - <T> 找不到通过 Activator 创建的对象类型

c# - 在 C# 中为可空结构的成员赋值

c# - 首先在 Entity Framework 代码中使用搜索字符串搜索 DateTime

c# - 为什么我可以抽象覆盖抽象方法?

c# - Entity Framework 中每种类型的表流利映射

c# - Linq 多重 where 查询