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

How to set the principle for optional one-to-one using 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 中对这种关系建模的标准方法是使用 Shared Primary Key Association

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

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