The entity type 'IdentityUser' is part of

2020-07-26 02:28发布

问题:

I'm trying to migrate a .NET Core 1.1 MVC-application using EntityFrameworkCore (1.0.1) from SQLite ("Microsoft.EntityFrameworkCore.Sqlite": "1.0.1") to MySQL ("MySql.Data.EntityFrameworkCore": "7.0.6-IR31").

My context is extending IdentityDbContext, and when running Database.EnsureCreated(), using Sqlite, the AspNet-tables (RoleClaims, Roles, Users, etc) were automatically configured.

With the MySQL-connector, when i attempt to run either Update-Database or Database.EnsureCreated(), I get the error:

The entity type 'IdentityUser' is part of a hierarchy, but does not have a discriminator value configured.

Should I really configure this manually, and if so, how?

Context:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{

    //DbSets here..

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }

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

        builder.Entity<IdentityUser>()
            .HasDiscriminator<int>("Type")
            .HasValue<ApplicationUser>(1);
    }
}

ApplicationUser:

public class ApplicationUser : IdentityUser
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Firmname { get; set; }
    public string CVR { get; set; }
    public string ATT { get; set; }
    public string Telephone { get; set; }
    public string Address { get; set; }
}

回答1:

It seems that the MySQL Provider for EntityFramework Core doesn't automatically do registrations for derived classes (which other providers do implicitly), which is why you need to specify the discriminators in code.

However, since IdentityUser is not an abstract class, it can in theory be instantiated and assigned too and the MySQL Database Provider requires a registration for it too (even if in production there will never be an value with this discriminator).

So you have to register the base class too.

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

    builder.Entity<IdentityUser>()
        .HasDiscriminator<int>("Type")
        .HasValue<IdentityUser>(0)
        .HasValue<ApplicationUser>(1);
}