我正在尝试将我的表与另一端的外键和主键相关联。但现在我将使用外键,它不是所述表的主键。我正在使用[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");
});
我正在尝试使用他们的解决方案 here ,但运气不佳。
任何帮助将不胜感激。谢谢!
最佳答案
But now i will be using a ForeignKey which is not the primary for the said table.
为此,您可以使用 EF Core Alternate Keys特征。但首先要更正您的模型类设置,如下所示:(正如您所说,User
将有多个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
关于asp.net-core - 使用 Include 进行 EF Core 联接,但外键不是另一个表上的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54799285/