Home > Mobile >  Migrating EF6 to EF Core setting unable to specify the identity user table
Migrating EF6 to EF Core setting unable to specify the identity user table

Time:07-30

Question:

How do we migrate our EF6 code first application to EF Core and specify an existing table for the identity user?

Background:

We are migrating an ASP.NET MVC application that used EF6 to .NET6 and EF Core. The original project was developed with a code first database and used a public class ApplicationUser : IdentityUser override for authentication.

Problem:

When we need to query the ApplicationUser or pull the related data in a query the application throws an error because it is expecting to find the table name AspNetUsers, but the table is actually named ApplicationUsers. I have been unable to successfully set the table name for the ApplicationUser.

Failed attempts:

This does nothing

[Table( "ApplicationUsers" )]
public class ApplicationUser : IdentityUser

This does nothing, as it seems to be overridden by the defaults in the base implementation

protected override void OnModelCreating( ModelBuilder modelBuilder )
{
    modelBuilder.Entity<ApplicationUser>( b => 
    {
        b.ToTable("ApplicationUsers");
    } );
    ...
    base.OnModelCreating( modelBuilder );
}

This errors on startup with the following error A key cannot be configured on 'ApplicationUser' because it is a derived type.

protected override void OnModelCreating( ModelBuilder modelBuilder )
{
    modelBuilder.Entity<IdentityUser>( b => 
    {
        b.ToTable("ApplicationUsers");
    } );
    ...
    base.OnModelCreating( modelBuilder );
}

CodePudding user response:

First off, take a look here and be sure to replace all mentions of IdentityUser to ApplicationUser ( so that no one is registering the base IdentityUser as a dbContext set under the hood ) and also run the base model creation before your "extra editions" iinstead of the other way around, by first running

base.OnModelCreating( modelBuilder );

and then addiing your own changes on the model buiilder, that will override the previous ones instead

  • Related