Using custom user instead of ASP.NET IdentityUser

2020-07-24 05:35发布

问题:

I'm new on ASP.NET Identity and trying to customize the identity which is provided while creating new MVC project.

ASP.NET Identity automatically creates few tables for handle authentication and authorization itself.

My main goal is just create Users table but others. I've tried following code to prevent creating these tables:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Ignore<IdentityUserRole>();
        modelBuilder.Ignore<IdentityUserClaim>();
        modelBuilder.Ignore<IdentityRole>();
    }

When I want to create a user, following error returning:

The navigation property 'Roles' is not a declared property on type 'ApplicationUser'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.

I found that built-in Identity user has following structure:

IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string>

What I need is creating a custom IdentityUser which not contains role, claim, etc. I just want the table 'Users' when I run the project.

Any possibility to create my own IdentityUser or customize built-in one? Or any suggestion to create just 'Users' table and work with it?

Many thanks in advice.

回答1:

This is what I did in order to get a solution:

  • I removed the base.OnModelCreating
  • Then I added the ignore in this order.

    //base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<IdentityUser>().ToTable("User");
    modelBuilder.Entity<IdentityUser>().ToTable("User").Ignore(p => p.Roles);
    modelBuilder.Ignore<IdentityUserRole>();
    modelBuilder.Ignore<IdentityUserLogin>();
    modelBuilder.Ignore<IdentityUserClaim>();
    modelBuilder.Ignore<IdentityRole>();
    

Doing this I got a final error that it said: Could not drop object 'dbo.Role' because it is referenced by a FOREIGN KEY constraint.

For that I changed the migration moving the DropTable("dbo.Role"). I know this is hack, but I did not find out how EF migrations move the droptables sentences to the right order.

Richard