【问题标题】:How to define two FK in the same table?如何在同一张表中定义两个FK?
【发布时间】:2018-10-23 10:14:54
【问题描述】:

我有一个名为User 的表,它继承了IdentityUser 的属性,在该表中我添加了对需要存储所有用户友谊的UserFriendship 表的引用:

public class User : IdentityUser
{
    public string FirstName { get; set; } 
    public DateTime BirthDate { get; set; }

    public virtual ICollection<UserFriendship> UserFriendship { get; set; }
}

本质上UserFriendship包含两个用户,他们是有共同友谊的人,这是模型定义:

public class UserFriendship
{
    public int Id { get; set; }

    [Key, ForeignKey("UserA")]
    public string UserAId { get; set; }
    public User UserA { get; set; }

    [Key, ForeignKey("UserB")]
    public string UserBId { get; set; }
    public User UserB { get; set; }

    [Required]
    public DateTime DateTime { get; set; }
}

我定义了UserAUserB,它们是User 中的两个FK,它们包含在AspNetUsers 表中。

现在在FluentAPI 中我声明了以下内容:

builder.Entity<UserFriendship>(entity =>
{
    entity.HasKey(f => f.Id);

    entity.HasOne(u => u.UserA)
          .WithMany(n => n.UserFriendships)
          .HasForeignKey(u => u.UserAId)
          .IsRequired();

    entity.HasOne(u => u.UserB)
          .WithMany(n => n.UserFriendships)
          .HasForeignKey(u => u.UserBId)
          .IsRequired();
 });

当我执行这个命令时:

add-migration InitialMigration -context MyAppContext

我会得到:

无法在“User.UserFriendships”和“UserFriendship.UserB”之间创建关系,因为“User.UserFriendships”和“UserFriendship.UserA”之间已经存在关系。导航属性只能参与单个关系。

我不是EnityFramework 的专家,但基于那个错误我认为我不能在同一个表中定义两个FK

如有错误请见谅,谢谢。

【问题讨论】:

    标签: asp.net entity-framework asp.net-core


    【解决方案1】:

    您可以在表中定义多个 FK。 这里的问题是您两次指向一个导航属性 - UserFriendships。解决方案是创建两个导航属性。

    导航属性用于浏览实体的指定外键(您具有一对多关系)的相关数据。

    试试这个:

    public class User
    {
        public string FirstName { get; set; }
        public DateTime BirthDate { get; set; }
    
        public ICollection<UserFriendship> UserAFriendships { get; set; }
        public ICollection<UserFriendship> UserBFriendships { get; set; }
    }
    
    public class UserFriendship
    {
        public int Id { get; set; }
    
        public string UserAId { get; set; }
        public User UserA { get; set; }
    
        public string UserBId { get; set; }
        public User UserB { get; set; }
        public DateTime DateTime { get; set; }
     }
    

    并通过fluent api定义关系如下:

    modelBuilder.Entity<UserFriendship>(entity =>
    {
         entity.HasKey(f => f.Id);
    
         entity.HasOne(u => u.UserA)
             .WithMany(n => n.UserAFriendships)
             .HasForeignKey(u => u.UserAId)
             .IsRequired();
    
         entity.HasOne(u => u.UserB)
              .WithMany(n => n.UserBFriendships)
              .HasForeignKey(u => u.UserBId)
              .IsRequired();
    });
    

    更重要的是 - 如果您使用 Fluent API,则无需指定属性 Key, ForeignKey

    【讨论】:

    • 感谢这个工作,你认为我的实现是正确的还是有另一种简单的方法来实现这个?
    猜你喜欢
    • 1970-01-01
    • 2011-11-24
    • 2013-03-15
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多