EF Code First架构设计 - 用户和联系人

时间:2012-10-05 03:59:01

标签: c# entity-framework ef-code-first poco entity-framework-5

我正在努力想出一个管理Person及其朋友的模型。

  • 一个人有0对多的朋友
  • 朋友也是一个人 - 虽然
  • 不一样
  • 朋友可以属于一个或多个群组

粗略地说,架构看起来像这样:

enter image description here

我无法弄清楚如何使用EF Code First实现相同目的。这是我到目前为止,但这不会创建所需的架构

public class Person 
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Person> Friends { get; set; } // is this right?
}

public class Friend {
    public long Id { get; set; }
    public long PersonId { get; set; }  // Person whose Friend this guy is
    public virtual ICollection<Group> Groups { get; set; } 

    // other fields 
}

public class Group{
    public long Id { get; set; }
    public string Name { get; set; }
}

有人可以帮我弄清楚这个烂摊子吗?

1 个答案:

答案 0 :(得分:3)

您需要在Person上自我引用多对多关系,因为您当前的模型允许每个人拥有许多朋友,但同时每个人只能与另一个人成为朋友。

试试这个:

public class Person 
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Person> FriendWith { get; set; } 
    public virtual ICollection<Person> FriendOf { get; set; } 
}

您可以添加此Fluent-API映射:

modelBuilder.Entity<Person>()
            .HasMany(p => p.FriendWith)
            .WithMany(p => p.FriendOf)
            .Map(m => {
                 m.MapLeftKey("PersonId");
                 m.MapRightKey("FriendId");
                 m.ToTable("PersonFriends");
            });

看起来很奇怪,但EF构建定向图中的关联=&gt;如果一个人A是一个人B的朋友,那么它被认为是不同的关系,那么如果一个人B是一个人A的朋友,其中一个关系将在FriendWith集合中,另一个将在{{1}收集。