我试图将我的表与另一端的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");
});
我正在尝试使用他们here的解决方案,但是没有运气。
任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
但是现在我将使用不是所述表的主键的ForeignKey。
为此,您可以使用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