How do I upgrade the existing entities from EF 6.1 to EF Core 7 without breaking/changing the inheritance strategy or behavior?

77 views Asked by At

I have an existing ASP.NET MVC web application build on the .NET Framework that uses Entity Framework 6.1 with a code-first approach and SQL Server.

The entities shown below use table-per-type and table-per-hierarchy inheritance strategy and this works without any issues in Entity Framework 6.1.

public abstract class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public abstract void MakeSound();
}

public abstract class Mammal : Animal
{
    public string FurColor { get; set; }

    public abstract void GiveBirth();
}

public class Dog : Mammal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof! Woof!");
    }

    public override void GiveBirth()
    {
        Console.WriteLine("Dog gives birth to puppies.");
    }
}

public class Cat : Mammal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow! Meow!");
    }

    public override void GiveBirth()
    {
        Console.WriteLine("Cat gives birth to kittens.");
    }
}

Here is the Fluent API configuration

modelBuilder.Entity<Animal>().ToTable("Animal");

modelBuilder.Entity<Mammal>().ToTable("Mammal")
                .HasDiscriminator<string>("Discriminator")
                .HasValue<Dog>("Dog")
                .HasValue<Cat>("Cat");

modelBuilder.Entity<Dog>().ToTable("Mammal");
            modelBuilder.Entity<Cat>().ToTable("Mammal");

With the above configuration, Entity Framework 6.1 has created two tables Animal and Mammal with a discriminator in the Mammal table.

Issue

However, when I try to recreate the same with EF Core 7, it fails with this error:

System.InvalidOperationException: 'The corresponding CLR type for entity type 'Animal' cannot be instantiated, but the entity type was mapped to 'Animal' using the 'TPC' mapping strategy. Only instantiable types should be mapped.

I know table-per-concrete-type was introduced in EF Core 7.0. But, do they still support the same implementation as they did with Entity Framework 6.1?

What I have tried: after a bit of research in Microsoft's documentation on EF Core inheritance. I tried the below configurations, but they did not work.

  1. Configured the Animal entity to use modelBuilder.Entity<Animal>().ToTable("Animal").UseTpcMappingStrategy();
  2. Configured the Mammal entity to use HasDiscriminator<string>("MammalType")

Question

How do I port/migrate the above entities from EF 6.1 to EF Core 7 without breaking/changing the inheritance strategy or behaviour?

0

There are 0 answers