【问题标题】:EF Code First schema design - User and ContactEF Code First 架构设计 - 用户和联系人
【发布时间】:2012-10-05 03:59:00
【问题描述】:

我正在尝试提出一个管理 Person 及其好友的模型。

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

架构大致如下所示:

我不知道如何使用 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; }
}

有人可以帮我解决这个问题吗?

【问题讨论】:

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


    【解决方案1】:

    您需要在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 中的关联构建了有向图 => 如果一个人 A 与一个人 B 是朋友,则它被认为是不同的关系,那么如果一个人 B 是一个人 A 的朋友。这些关系之一将是在FriendWith 集合中,另一个将在FriendOf 集合中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-26
      相关资源
      最近更新 更多