0

I have to extend default implementation of Roles in Identity 3. So I wrote subclasses:

public class ApplicationRole:IdentityRole
{
    public string Description { get; set; }
    public DateTime CreationDate { get; set; }
}
public class ApplicationUserRole:IdentityUserRole<string>
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

Then, since I want Entity Framework 7 to store my data in the same default tables I wrote the following in OnModelCreating method of ApplicationDbContext:

builder.Model.RemoveEntityType(new Microsoft.Data.Entity.Metadata.EntityType(typeof(IdentityRole), builder.Model));
builder.Model.RemoveEntityType(new Microsoft.Data.Entity.Metadata.EntityType(typeof(IdentityUserRole<string>),builder.Model));

builder.Entity<ApplicationRole>().ToTable("AspNetRoles");              
builder.Entity<ApplicationUserRole>().HasKey(r => new { UserId = r.UserId, RoleId = r.RoleId });
builder.Entity<ApplicationUserRole>().ToTable("AspNetUserRoles");

Also I defined properties in ApplicationDbContext:

public DbSet<ApplicationUserRole> MyUserRoles { get; set; }
public DbSet<ApplicationRole> MyRoles { get; set; }

(I tried to override default UserRoles and Roles with new, but EF migration throw AmbiguousMatchException) Now I suppose I have to register my custom implementation in app configuration, but I have no idea how. I whote in Startup.cs:

services.AddIdentity<ApplicationUser, ApplicationRole>(/*options*/)

and changed the superclass for ApplicationDbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser,ApplicationRole,string>

What else should I do? Or maybe I must address the task completely different?

Slip
  • 593
  • 1
  • 7
  • 21
  • Do you really need to do `RemoveEntityType` and add `MyUserRoles` and `MyUserRoles` to your context if you are already inheriting from `IdentityDbContext<...>`? – DavidG Nov 18 '15 at 10:25
  • Yes. Otherwise EF's migration tool cannot bind my entities to the tables throwing "Cannot use table 'AspNetUserRoles' in schema '' for entity 'ApplicationUserRole' since it is being used for another entity." – Slip Nov 18 '15 at 11:15
  • 1
    Wait for a week, they're going to change all structures again, it will be Identity v.5 and will let you configure your authentication creating only 20 classes and overriding 80 methods... (ah, and don't forget interfaces, it has more than a thousand). And the best, this time it will be well documented. – Vi100 Nov 18 '15 at 11:52

1 Answers1

1

Looking at the source for IdentityDbContext and it seems you cannot use your own IdentityUserRole class in Identity v3. In fact, there is an open issue to add this back in.

DavidG
  • 113,891
  • 12
  • 217
  • 223
  • I've not had to extend those models in all of my projects, but I think it's a useful thing to have in for sure. – DavidG Nov 18 '15 at 11:42