【发布时间】:2014-07-25 16:47:50
【问题描述】:
我的解决方案中有 3 个项目,域、API 和 Web。最近我已将 Asp.net Identity 表单 1.0 更新为 2.0。在我的 Web 项目中一切正常,但是当我尝试在 Web API 项目中获取 Token 时出现此错误(在将 Identity 从 1.0 升级到 2.0 之前一切正常):
The entity type User is not part of the model for the current context
我的用户类如下所示:
public class User : IdentityUser
{
//more code here
}
这是我的数据库上下文类:
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");
}
}
在我的 Web API 项目中,我已将 IdentityUser 中的所有引用替换为 User,例如获取 Token 的方法如下:
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);
}
}
我该如何解决这个问题?
【问题讨论】:
-
我认为 IdentityDbContext 为给定的用户类型创建了一个 DbSet,所以我不确定这是否正确 - 但尝试使用
modelBuilder.Entity<User>()...而不是modelBuilder.Entity<IdentityUser>()... -
我都有,但我删除了modelBuilder.Entity
(),只留下了modelBuilder.Entity (),但没有帮助
标签: c# asp.net asp.net-web-api asp.net-identity asp.net-identity-2