为什么 EF Core 3.1 无法确定关系

Why can't EF Core 3.1 not able to determine the relationship

早些时候我有以下类关系

    [Table("User")]
    public class User
    {
        // Base properties
        [Key]
        public int UserId { get; set; }
        public string Name { get; set; }

        // Relationships
        public ICollection<UserRole> UserRoles { get; set; }
    }

    [Table("UserRole")]
    public class UserRole
    {
        // Base properties
        [Key]
        public int UserRoleId { get; set; }
        public string Name { get; set; }

        // Relationships
        public int UserId { get; set; }
        [ForeignKey("UserId")]
        public User User { get; set; }
    }

EF Core 能够按预期将其映射到 SQL,这给出了两个 tables

  1. 用户 - 用户 ID (PK)、名称
  2. UserRole - UserRoleId (PK)、名称、UserId (FK)

后来我想添加一种方法来验证记录,验证者来自用户 table 本身。以下是验证的实现方式:

    [Table("User")]
    public class User
    {
        // Base properties
        [Key]
        public int UserId { get; set; }
        public string Name { get; set; }

        // Relationships
        public ICollection<UserRole> UserRoles { get; set; }

        // Verification
        public int? VerifierId { get; set; }
        [ForeignKey("VerifierId")]
        public User Verifier { get; set; }
    }

    [Table("UserRole")]
    public class UserRole
    {
        // Base properties
        [Key]
        public int UserRoleId { get; set; }
        public string Name { get; set; }

        // Relationships
        public int UserId { get; set; }
        [ForeignKey("UserId")]
        public User User { get; set; }

        // Verification
        public int? VerifierId { get; set; }
        [ForeignKey("VerifierId")]
        public User Verifier { get; set; }
    }

上述设置在添加迁移时出现以下异常:Unable to determine the relationship represented by navigation property 'User.UserRoles' of type 'ICollection<UserRole>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

但是,在 UserRole table 中删除以下 属性 使得迁移成为可能:

ForeignKey("VerifierId")]
public User Verifier { get; set; }

但这不是我想要的。我也希望保留外键。如何使这成为可能?为什么一开始就不允许这样做?

这里的问题是EF不知道应该将哪个FK(UserIdVerifierId)映射到[=14=的UserRoles属性 ] class.

您需要定义应该使用哪个外键

[InverseProperty(nameof(UserRole.User))]
public ICollection<UserRole> UserRoles { get; set; }

在此处查看文档 https://docs.microsoft.com/en-us/ef/core/modeling/relationships