Customizing Asp.Net Identity 3.0

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

Question

I want to customize Asp.Net Identity 3 classes.

Here is what I did:

public class MyDbContext : IdentityDbContext<User>

and

public class User : IdentityUser<int>

I also extended IdentityUserClaim<int>, IdentityRole<int>, IdentityUserLogin<int> and IdentityUserRole<int> but I get the following error:

The type 'User' cannot be used as type parameter 'TUser' in the generic type or method' IdentityDbContext<TUser>'.There is no implicit reference conversion from 'User' to 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser'.

Accepted Answer

I don't know how you made your class to inherit IdentityUser<int> as generic version of `IdentityUser' has more type parameters. Check here: https://msdn.microsoft.com/en-us/library/dn613256%28v=vs.108%29.aspx

So, you will need:

public class User : IdentityUser<int, UserLogin, UserRole, UserClaim>

and:

public class UserRole : IdentityUserRole<int> { }
public class UserClaim : IdentityUserClaim<int> { }
public class UserLogin : IdentityUserLogin<int> { }

Edit: For Identity 3.0 things are a bit different, but problem is similar. According to: https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNet.Identity.EntityFramework/IdentityDbContext.cs

IdentityDbContext<TUser> is like this:

public class IdentityDbContext<TUser> : IdentityDbContext<TUser, IdentityRole, string> where TUser : IdentityUser
{ }

Important part is where TUser : IdentityUser Definition of IdenityUser is:

public class IdentityUser : IdentityUser<string>
{ ... }

And your User class inherits IdentityUser<int> so it doesn't have implicit conversion to 'IdentityUser' because int/string difference.

Solution would be to inherit from IdentityDbContext<TUser, TRole, TKey> where TUser would be your User class, TRole would be new Role class that iherits IdentityRole<int> and TKey is int:

public class MyDbContext : IdentityDbContext<User, Role, int> {...}
public class User : IdentityUser<int> {...}
public class Role : IdentityRole<int> {...}

Popular Answer

This should be enough:

public class ApplicationUser : IdentityUser<int>
{

}

public class ApplicationRole : IdentityRole<int>
{

}

public class MyDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
{

}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why