如何将两个表映射到 EntityTypeConfiguration 中的一个实体?

How can I map two tables to one entity in an EntityTypeConfiguration?

我有一个数据库结构,其中有一个设备 table,其列为 Equipment_IdField_1Field_2。我有一个 Equipment_Locale table 字段 Equipment_IdDesc。两个table的Id是一样的,table之间是一对一的关系。

我有以下实体:

public class Equipment
{
    public long Id { get; set; }
    public string Description { get; set; }
    public long Field1 { get; set; }
    public long Field2 { get; set; }
}

我有以下 EntityTypeConfiguration:

public class EquipmentMapping : EntityTypeConfiguration<Equipment>
{
    public EquipmentMapping()
    {
        ToTable("EQUIPMENT");
        HasKey(e => e.Id);
        Property(e => e.Id).HasColumnName("EQUIPMENT_ID");
        Property(e => e.Field1).HasColumnName("FIELD_1");
        Property(e => e.Field2).HasColumnName("FIELD_2");
        // TODO: Okay, now I need to get the description in here!
    }
}

不过,我需要在其中映射描述,它来自 EQUIPMENT_LOCALE table 的 DESC 列。

This answer 让我清楚地知道如果我在 ModelBuilder 中定义映射,我可以如何使用它。但是,我们一直在这个项目中使用带有 EntityTypeConfigurations 的文件,只是让模型构建器添加这些配置,我不确定如何在其中一个中设置两个 table 映射。我怎样才能做到这一点?

您需要在您的父级中使用导航 属性:

public virtual Equipment_Locale Equipment_Locale { get; set; } 

然后你可以像这样添加到设备配置映射:

        HasRequired(p => p.Equipment_Locale )
            .WithMany()
            .HasForeignKey(p => p.Equipment_LocaleId )
            .WillCascadeOnDelete(false);

关系映射见此处:https://msdn.microsoft.com/en-us/data/jj591620.aspx

事实证明,我在 ModelBuilder 中链接的答案非常非常接近我需要简单地放入 EntityTypeConfiguration 文件中的答案。我以前从未在 EntityTypeConfiguration 中使用过 Map() 所以我有点无能为力。

以下似乎对我有用:

public class EquipmentMapping : EntityTypeConfiguration<Equipment>
{
    public EquipmentMapping()
    {
        HasKey(e => e.Id);
        Property(e => e.Id).HasColumnName("EQUIPMENT_ID");
        Property(e => e.Field1).HasColumnName("FIELD_1");
        Property(e => e.Field2).HasColumnName("FIELD_2");
        Property(e => e.Description).HasColumnName("DESC");

        Map(m =>
        {
            m.Properties(e => new
            {
                e.Id,
                e.Field1,
                e.Field2
            });
            m.ToTable("EQUIPMENT");
        });

        Map(m =>
        {
            m.Properties(e => new
            {
                e.Id,
                e.Description
            });
            m.ToTable("EQUIPMENT_LOCALE");
        });
    }
}