如何使用 Fluent API 设置可选一对一的原则


public class Sale
{
   public int SaleId { get; set; }
   public Comment Comment { get; set; }
}
public class Comment
{
   public int CommentId { get; set; }
   public int SaleId { get; set; }
   public Sale Sale { get; set; }
}
modelBuilder.Entity<Comment>()
   .HasRequired(s => s.Sale)
   .WithMany()
   .HasForeignKey(s => s.SaleId);

然而,它的方式是错误的...

public override void Up()
{
    AddColumn("public.tbl_sale", "Comment_CommentId", c => c.Long());
    AddForeignKey("public.tbl_sale", "Comment_CommentId", "public.tbl_comment", "CommentId");
}

如何解决?

在 EF 中对此类关系进行建模的标准方法是使用共享主键关联。

为此,请从Comment类中删除SaleId(请记住 - CommentId将是PK和FK)并使用以下配置:

modelBuilder.Entity<Comment>()
   .HasRequired(c => c.Sale)
   .WithOptional(s => s.Comment);

最新更新