【问题标题】:EF Core - Many to many relationship on a classEF Core - 类上的多对多关系
【发布时间】:2017-03-12 08:48:15
【问题描述】:

用户-朋友关系

我找到答案了

Entity Framework Core: many-to-many relationship with same entity 并尝试这样。

实体:

public class User
{
    public int UserId { get; set; }

    public virtual ICollection<Friend> Friends { get; set; }
}

public class Friend
{
    public int MainUserId { get; set; }

    public User ManUser { get; set; }

    public int FriendUserId { get; set; }

    public User FriendUser { get; set; }
}

流畅的 API:

modelBuilder.Entity<Friend>()
    .HasKey(f => new { f.MainUserId, f.FriendUserId });

modelBuilder.Entity<Friend>()
    .HasOne(f => f.ManUser)
    .WithMany(mu => mu.Friends)
    .HasForeignKey(f => f.MainUserId);

modelBuilder.Entity<Friend>()
    .HasOne(f => f.FriendUser)
    .WithMany(mu => mu.Friends)
    .HasForeignKey(f => f.FriendUserId);

当我添加迁移时,错误消息是

无法在“User.Friends”和“Friend.FriendUser”之间创建关系,因为“User.Friends”和“Friend.ManUser”之间已经存在关系。 导航属性只能参与单个关系。

我该怎么办?或者我应该创建一个实体 FriendEntity:User?

【问题讨论】:

    标签: c# many-to-many entity-framework-core


    【解决方案1】:

    问题是你不能有一个集合来支持一对多关联。 Friend 有两个外键,在它们引用的实体中都需要一个 inverse end。所以添加另一个集合作为 MainUser 的反向结束:

    public class User
    {
        public int UserId { get; set; }
        public virtual ICollection<Friend> MainUserFriends { get; set; }
        public virtual ICollection<Friend> Friends { get; set; }
    }
    

    还有映射:

    modelBuilder.Entity<Friend>()
        .HasKey(f => new { f.MainUserId, f.FriendUserId });
    
    modelBuilder.Entity<Friend>()
        .HasOne(f => f.MainUser)
        .WithMany(mu => mu.MainUserFriends)
        .HasForeignKey(f => f.MainUserId).OnDelete(DeleteBehavior.Restrict);
    
    modelBuilder.Entity<Friend>()
        .HasOne(f => f.FriendUser)
        .WithMany(mu => mu.Friends)
        .HasForeignKey(f => f.FriendUserId);
    

    一个(或两个)关系应该没有级联删除以防止多个级联路径。

    【讨论】:

      【解决方案2】:

      第二个集合不是强制性的。你只需要像这样将 de .WithMany() 留空:

      modelBuilder.Entity<Friend>()
          .HasOne(f => f.MainUser)
          .WithMany()
          .HasForeignKey(f => f.MainUserId);
      
      modelBuilder.Entity<Friend>()
          .HasOne(f => f.FriendUser)
          .WithMany()
          .HasForeignKey(f => f.FriendUserId);
      

      看看这个:https://github.com/aspnet/EntityFramework/issues/6052

      【讨论】:

      • 谢谢,离开 WithMany 似乎已经为我解决了这个问题。
      • 尝试这让我在数据库中多了一个不必要的外键关系(我有三个,而不是两个。其中一个是多余的,但只是命名不同)。为了解决这个问题,我在 WithMany() 调用中重新添加了一个参数,如下所示: modelBuilder.Entity() .HasOne(f => f.FriendUser) .WithMany(mu => mu.MainUserFriends) .HasForeignKey (f => f.FriendUserId);
      猜你喜欢
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 2021-10-21
      • 2019-01-19
      • 2017-10-26
      • 1970-01-01
      相关资源
      最近更新 更多