Adding Entity Framework core code first sublass with existing property name

37 Views Asked by At

What is best/a good practise in the following situation when using TPH inheritance in Entity Framework?:

I have

abstract class Base
{
    ...
}

class Sub1
{
    public int Amount {get;set;}
}

and a DbContext with:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Sub1>();
}

public DbSet<Base> Bases { get; set; }

Now I add

class Sub2
{
    public int Amount { get; set; }
}

and

modelBuilder.Entity<Sub2>();

Before adding Sub2, Sub1.Amount was mapped to a "Amount" column in the Bases table. After adding Sub2, Sub1.Amount is mapped to a "Sub1_Amount" column and Sub2.Amount is mapped to the "Amount" column. The table has data in it, so the new "Sub1_Amount" column are all nulls. When I try to run the system, I get

An exception occurred while reading a database value for property 'Sub1.Amount'. The expected type was 'System.Int32' but the actual value was null.

I understand why this is happening...but I thought Migrations would handle this.

Does anyone one know how to handle this? Thanks!

0

There are 0 best solutions below