1

我正在尝试将我的表与另一端的 ForeignKey 和 PrimaryKey 相关联。但现在我将使用一个 ForeignKey,它不是所述表的主键。我正在使用[InverseProperty]但我认为它有一个错误,因为我已经环顾了好几个小时,而且他们都说了同样的话。

文件表:

public class Document
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DocumentId { get; set; }
    public int ProjectId { get; set; }
    public int DepartmentId { get; set; }
    public int AuthorId { get; set; }

    [NotMapped]
    public virtual User Author { get; set; }
}

用户

public class User
{
    [Key]
    public int UserId { get; set; }
    public int AuthUserId { get; set; }
    public string DisplayName { get; set; }

    [NotMapped]
    [ForeignKey("AuthorId")]
    public virtual Document Document { get; set; }
}

语境:

modelBuilder.Entity<User>(entity =>
        {
            entity.HasOne(u => u.Document)
            .WithMany("AuthorId");
        });

我正在尝试使用他们在这里的解决方案,但没有运气。

任何帮助将不胜感激。谢谢!

4

1 回答 1

2

但现在我将使用一个 ForeignKey,它不是所述表的主键。

为此,您可以使用 EF Core备用键功能。但首先更正您的模型类设置如下:(如您所说 aUser将有多个Document

public class Document
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DocumentId { get; set; }
    public int ProjectId { get; set; }
    public int DepartmentId { get; set; }
    public int AuthorId { get; set; }

    public User Author { get; set; }
}

public class User
{
    [Key]
    public int UserId { get; set; }
    public int AuthUserId { get; set; }
    public string DisplayName { get; set; }


    public ICollection<Document> Documents { get; set; }
}

然后在Fluent API配置中如下:

modelBuilder.Entity<Document>()
        .HasOne(p => p.Author)
        .WithMany(b => b.Documents)
        .HasForeignKey(p => p.AuthorId)
        .HasPrincipalKey(b => b.AuthUserId); // <-- here you are specifying `AuthUserId` as `PrincipalKey` in the relation which is not primary key
于 2019-02-21T04:38:49.303 回答