实体类型IdentityUser不是当前上下文的模型的一部分

我看到了与这个问题相同的问题,但那里提出的情景似乎并不适用所以我认为我有一个不同的问题。 事实上,我在SO上看到几个相似的问题,每个问题都有不同的原因和解决方案,所以我认为这个错误必须从高水平引起。 那说……

我有一个EF代码优先数据库模型,我正在尝试使用IdentityUser扩展我的MVC 5站点的标准注册。

我有我的扩展UserModel

 namespace MyMvcSite.Models { public class UserModel :IdentityUser { public string BillingId { get; set; } public virtual ICollection Databases { get; set; } } 

我的背景:

 using MyMvcSite.Models; namespace MyMvcSite.Web { public class AuthContext : IdentityDbContext { public AuthContext() : base("AuthContext") { } } } 

现在,当我执行代码注册用户时:

 public async Task RegisterUser(UserModel user) { user.Email = user.UserName; var result = await _userManager.CreateAsync(user); return result; } 

我得到错误: The entity type IdentityUser is not part of the model for the current context. 我无法弄清楚这个错误意味着什么,因为它看起来 – 对我来说 – 就像我有一切正确。 任何人都可以告诉可能出错的地方???

我知道我的connectionString AuthContext是正确的,因为我以前使用过它。

当您使用具有ASP.NET标识的自定义用户类时,必须确保在实例化时向UserManagerUserStore显式指定自定义用户类类型

 private UserManager _userManager; public AccountController() { AuthContext _ctx = new AuthContext(); UserStore userStore = new UserStore(_ctx); _userManager = new UserManager(userStore); } 

或以较短的forms(如您的回复评论):

 private UserManager _userManager; public AccountController() { AuthContext _ctx = new AuthContext(); _userManager = new UserManager(new UserStore(_ctx)); } 

如果要在使用自定义类时允许类型默认为IdentityUser ,您将遇到报告的错误。

我遇到了同样的问题,我记得在MVC4中使用SimpleMembership时遇到了类似的问题。

我正在进行数据库优先开发,所以我有一个EDMX文件。 事实certificate,ASP.NET Identity不喜欢生成.edmx模型文件时创建的连接字符串。 如果你正在使用。 EDM连接字符串:base(“EDMConnString”)你很可能会遇到这个问题。

我通过创建一个标准连接字符串来解决这个问题,该字符串指向ASP.NET标识表所在的数据库(在我的情况下是同一个数据库),使用该连接字符串:base,并且它有效。

像这样的东西

  

当我向我的项目介绍DI时,我遇到了这个错误。 使用AutoFac和Identity我必须添加以下内容: builder.RegisterType().As().InstancePerLifetimeScope();

如果没有这个,当AutoFac创建我的UserStore实例时,它使用默认的UserStore() ctor创建一个新的IdentityDbContext ,而不是我的ApplicationDbContext

使用此行,使用ApplicationDbContext调用UserStore(DbContext context) ctor。