英孚核心。两个实体(表)之间的多个 One-to-One-or-Zero 关系

EF Core. Multiple One-to-One-or-Zero relationships between two entities (tables)

我设计了三个具有导航属性的实体(代码优先方法,省略了不必要的属性):

图片(表示数据库中的图片信息):

public class Image
{
    public long Id { get; init; }

    public long? PlayerId { get; set; }
    public Player Player { get; set; }

    public long? PublicationId { get; set; }
    public Publication Publication { get; set; }
}

出版物(某些域实体):

public class Publication
{
    public long Id { get; init; }

    public long? ImageTitleId { get; set; }
    public Image ImageTitle { get; set; }

    public long? ImageBackgroundId { get; set; }
    public Image ImageBackground { get; set; }
}

播放器(某个域实体):

public class Player
{
    public long Id { get; init; }

    public long? ImageProfileId { get; set; }
    public Image ImageProfile { get; set; }

    public long? ImageLogoId { get; set; }
    public Image ImageLogo { get; set; }
}

业务规则是:

  1. 图像在所有情况下都是从属实体
  2. Publication/Player 是这些关系中的主要实体
  3. Publication/Player可否有相关图片(one-to-one-or-zero)

这里的困难是两个实体(因此数据库中的表)(标题图像、背景图像等)之间的多重关系。

EF 无法自动检测 principal/dependent 实体,在这种情况下我不知道如何配置 Fluent API。

我认为您错过了 Image 实体中的一些属性。 我将图像模型更改如下:

public class Image
{
    public long Id { get; init; }

    public long? ImageProfilePlayerId { get; set; }
    public Player ImageProfilePlayer { get; set; }

    public long? ImageLogoPlayerId { get; set; }
    public Player ImageLogoPlayer { get; set; }


    public long? ImageTitlePublicationId { get; set; }
    public Publication ImageTitlePublication { get; set; }

    public long? ImageBackgroundId { get; set; }
    public Publication ImageBackground { get; set; }
}

PaleyPublication如下(它们和你的一样):

 public class Publication
{
    public long Id { get; init; }

    public long? ImageTitleId { get; set; }
    public Image ImageTitle { get; set; }

    public long? ImageBackgroundId { get; set; }
    public Image ImageBackground { get; set; }
}

public class Player
{
    public long Id { get; init; }

    public long? ImageProfileId { get; set; }
    public Image ImageProfile { get; set; }

    public long? ImageLogoId { get; set; }
    public Image ImageLogo { get; set; }
}

并在 DbContext 中的 OnModelCreating 模型的配置下方使用:

   protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Image>(e => {
            e.HasOne(x => x.ImageProfilePlayer).WithOne(x => x.ImageProfile).HasForeignKey<Player>(x => x.ImageProfileId).IsRequired(false);
            e.HasOne(x => x.ImageLogoPlayer).WithOne(x => x.ImageLogo).HasForeignKey<Player>(x => x.ImageLogoId).IsRequired(false);
            e.HasOne(x => x.ImageTitlePublication).WithOne(x => x.ImageTitle).HasForeignKey<Publication>(x => x.ImageTitleId).IsRequired(false);
            e.HasOne(x => x.ImageBackground).WithOne(x => x.ImageBackground).HasForeignKey<Publication>(x => x.ImageBackgroundId).IsRequired(false);
        });

     
    }

结果是: