EF核心联接使用包括但外键不是另一个表上的主键 [英] EF Core Join using Include but ForeignKey is not Primary Key on the other table
问题描述
我试图将我的表与另一端的ForeignKey和PrimaryKey相关联。但是现在我将使用不是该表的主要键的ForeignKey。我使用的是 [InverseProperty] ,但我认为它存在一个错误,因为我已经看了几个小时,而且所有人都说了同样的话。
I am trying to relate my Tables with ForeignKey and PrimaryKey on the other end. But now i will be using a ForeignKey which is not the primary for the said table. I was using [InverseProperty] but i think there's a bug with it since i've been looking around for hours already and all of them says the same thing about it.
文档表:
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");
});
我正在尝试使用他们此处,但没有运气。
I am trying to use the solution they here, but no luck.
任何帮助将不胜感激。谢谢!
Any help would really be appreciated. Thanks!
推荐答案
但是现在我将使用ForeignKey,它不是所说的主键表。
But now i will be using a ForeignKey which is not the primary for the said table.
为此,您可以使用EF Core 备用键功能。但是首先请按照以下说明正确设置模型类:(正如您所说,用户
将有多个 Document
)
To do this you can use EF Core Alternate Keys feature. But first correct your model class set up as follows: (As you said a User
will have multiple 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
这篇关于EF核心联接使用包括但外键不是另一个表上的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!