Same property name in several child entities with Entity Framework Core 2.0

.net-core-2.0 c# entity-framework entity-framework-core

Question

I'm currently using the simple model below. It's pretty straightforward: we have resources and they can be Room, EmptyOffice (...) or Service.

Room and EmptyOffice can have a capacity, but NOT Service.

public abstract class Resource : Entity
{
    public string Name { get; set; }
}

public class Room : Resource
{
    public int Capacity { get; set; }
}

public class EmptyOffice : Resource
{
    public int Capacity { get; set; }
}

public class Service : Resource
{ }

To get the data from my SQL view, I use the mappings:

builder.Entity<Resource>(m =>
{
    m.ToTable("resource", "facility");
    m.HasKey(x => x.Id);
    m.Property(x => x.Id)
        .HasColumnName("ResourceId");
    m.Property(x => x.Type)
        .HasColumnName("ResourceTypeId");

    m.HasDiscriminator(x => x.Type)
        .HasValue<Room>(ResourceType.Room)
        .HasValue<EmptyOffice>(ResourceType.EmptyOffice)
        .HasValue<Service>(ResourceType.Service);
});

builder.Entity<Room>();
builder.Entity<EmptyOffice>();
builder.Entity<Service>();

When I run my code, EF Core throws the following exception:

System.Data.SqlClient.SqlException: 'Invalid column name 'Room_Capacity'.'

If I rename the Capacity property to Room_Capacity, it works but it's horrible.

How can I force EF Core 2.0 to target the capacity property for each of my child entities?

Thank you Sebastien

1
2
9/6/2017 11:44:16 AM

Accepted Answer

You can't do that as the only inheritance pattern available in EF Core is table per class hierarchy. If you go with interfaces instead of base classes, you can, but each entity will be mapped to a different table. Mark any property you want to exclude with [NotMapped], or, using the code, with Ignore.

1
9/6/2017 10:11:42 AM

Popular Answer

This worked for me:

builder.Entity<Room>().Property(a => a.Capacity).HasColumnName("Capacity");

builder.Entity<EmptyRoom>().Property(a => a.Capacity).HasColumnName("Capacity");


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