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

entity-framework-6

Question

I've got a database structure where I've got an Equipment table with the columns Equipment_Id, Field_1, and Field_2. I've got an Equipment_Locale table with the fields Equipment_Id and Desc. The Ids are the same in both tables, and there is a one-to-one relationship between these tables.

I've got the following entity:

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

I've got the following 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!
    }
}

I need to map the description in there, though, which comes from the EQUIPMENT_LOCALE table's DESC column.

This answer gives me a pretty clear idea on how I could use this if I was defining the mapping in ModelBuilder. However, we've been using files with EntityTypeConfigurations on this project and just having the model builder add those configurations, and I'm not sure how to set up a two table mapping in one of those. How can I accomplish this?

1
2
5/23/2017 11:45:30 AM

Accepted Answer

It turns out that the answer I linked which did it in ModelBuilder was really, really close to what I needed to simply put in my EntityTypeConfiguration file. I'd just never used Map() in EntityTypeConfiguration before so I was a bit clueless.

The following seems to work for me:

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");
        });
    }
}
4
2/26/2015 9:10:19 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow