Aleksa Aleksa - 4 months ago 95
ASP.NET (C#) Question

Customizing Asp.Net Identity 3.0

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'.

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> {...}