首页 > 解决方案 > 如何在 EF6 中对不同实体使用同一张表

问题描述

我有具有导航属性的实体 DbDropPhoto

public class DbDropPhoto
{
    public virtual DbContour Contour { get; set; }
}

public class DbContour
{
    public virtual DbDropPhoto CurrentDropPhoto { get; set; }
}

使用 FluentAPI 像这样配置关系:

    modelBuilder.Entity<DbContour>()
        .HasRequired(s => s.CurrentDropPhoto)
        .WithOptional(s => s.Contour)
        .WillCascadeOnDelete();

现在我需要将相同的 DbContour 实体添加到另一个名为 DbThermalPhoto 的实体中。最好的方法是什么。我应该创建单独的表,例如 DbThermalPhotoContour,还是可以以某种方式重新使用现有表。我已经搜索过类似的问题,但它们的解决方案似乎非常复杂。

标签: c#entity-framework

解决方案


我设法像这样实现它:

        modelBuilder.Entity<DbDropPhoto>()
            .HasOptional(c => c.Contour)
            .WithMany()
            .HasForeignKey(s => s.ContourId);

        modelBuilder.Entity<DbThermalPhoto>()
            .HasOptional(c => c.Contour)
            .WithMany()
            .HasForeignKey(s => s.ContourId);

和实体:

[Table("DropPhotos")]
public class DbDropPhoto
{
    [Key] public Guid PhotoId { get; set; }

    public Guid? ContourId { get; set; }

    [ForeignKey("ContourId")]
    public virtual DbContour Contour { get; set; }
}

[Table("ThermalPhotos")]
public class DbThermalPhoto
{
    [Key] public Guid PhotoId { get; set; }

    public Guid? ContourId { get; set; }

    [ForeignKey("ContourId")]
    public virtual DbContour Contour { get; set; }
}

推荐阅读