How to map columns in Custom model to Identity model in ASP.NET Core Identity

asp.net asp.net-core c# entity-framework-core

Question

I am implementing ASP.NET Core Identity in an existing project with an existing Database.

I have specified the Entities to use for IdentityUser and IdentityRole like this:

public partial class MyContext : IdentityDbContext<MyUser, MyRole, int>

In Startup.cs:

services.AddIdentity<MyUser, MyRole>(options =>
        {
            options.User.RequireUniqueEmail = true;
        }).AddEntityFrameworkStores<MyContext>();

I was able to apply the migrations successfully to the database. But, on inspecting the AspNetRole table, I could see that EF created some extra columns.

enter image description here

How do I tell EF Core to use the existing colums (like RoleId for Id in the above image) instead of creating new ones?

Also, I noticed that EF Core changed MyRoles table name to AspNetRoles which was not the case with the MyUsers table. MyUsers table name remained the same even though extra columns were created as I mentioned above. Why is that?

PS: I am using DotNet Core 3.0 with EF Core 3.0.

1
0
10/25/2019 7:48:37 AM

Accepted Answer

  1. Add [Column()] annotations to change the default column name:

    public class MyRole: IdentityRole<int>
    {
        [Column("RoleId")]
        public override int Id { get; set; }
    
        [Column("RoleName")]
        public override string Name { get; set; }
    }
    
  2. To reuse the old table MyRoles, custom the OnModelCreating(builder) method:

    public class AppIdentityDbContext : IdentityDbContext<MyUser, MyRole, int>
    {
        ...
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<MyRole>(e =>{
                e.ToTable("MyRoles");
            });
        }
    }
    
1
10/25/2019 8:49:48 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow