I have 3 projects in my solution, Domain, API and Web. Recently I've updated Asp.net Identity form 1.0 to 2.0. And everything works fine in my Web project but when I try to get Token in Web API project I get this error (an before upgrading Identity from 1.0 to 2.0 everything worked):
The entity type User is not part of the model for the current context
My User class looks like this:
public class User : IdentityUser
{
//more code here
}
Here is My Database context class:
public class DatabaseContext : IdentityDbContext<User>
{
public DatabaseContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Configuration.LazyLoadingEnabled = true;
}
//more code here
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>()
.ToTable("AspNetUsers");
modelBuilder.Entity<User>()
.ToTable("AspNetUsers");
}
}
In my Web API project I've replaced all references from IdentityUser to User, for example method for getting Token looks like:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (UserManager<User> userManager = _userManagerFactory())
{
var user = userManager.Find(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}
How can I fix this ?
I've fixed it,
So the problem was with updating Asp.net Identity from 1.0 to 2.0 as ASP.net Web API handles things bit differently for 2.0 so what I did was:
To my DatabaseContext class I've added method:
public static DatabaseContext Create() { return new DatabaseContext(); }
And to my User class:
public async Task GenerateUserIdentityAsync(UserManager manager, string authenticationType) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); // Add custom user claims here return userIdentity; }