I want to map a simplified read-only entity (e.g. for UI dropdowns, that need only id and name) to a table that already has full-feature entity mapped.
I have fairly typical mapping configurations using IEntityTypeConfiguration
classes that map entities through EntityTypeBuilder<MyFullClass>
and EntityTypeBuilder<MySimpleClass>
.
I have no control over database, it's a legacy project and I cannot add new SQL views just to solve this code issue.
public class MyFullClassConfiguration : IEntityTypeConfiguration<MyFullClass>
{
public void Configure(EntityTypeBuilder<MyFullClass> builder)
{
builder.ToTable("MyTable");
... all properties mapped
public class MySimpleClassConfiguration : IEntityTypeConfiguration<MySimpleClass>
{
public void Configure(EntityTypeBuilder<MySimpleClass> builder)
{
builder.ToTable("MyTable");
... minimum of required properties mapped
When I run the project, I get an error:
Cannot use table 'MyTable' for entity type 'MySimpleClass' since it is being used for entity type 'MyFullClass' and there is no relationship between their primary keys.
I tried to artificially link both entities, adding one-to-one relation:
b.HasOne<MyFullClass>().WithOne().HasForeignKey<MySimpleClass>(e => e.Id);
This time the project was started normally, I could read and update entities, but when saving a new MyFullClass
, EF threw:
The entity of type 'MyFullClass' is sharing the table 'MyTable' with entities of type 'MySimpleClass', but there is no entity of this type with the same key value that has been marked as 'Added'.
This seems so common scenario - to return simplified versions of complex entities for performance and bandwidth reasons, so I was surprised to discover that it's not supported in EF and that they will implement it only in v3, if I'm not mistaken: https://github.com/aspnet/EntityFrameworkCore/issues/15310
How do I solve this in .NET Core 2.2?