解决方案-实体类型ApplicationUser不是当前上下文模型的一部分 [英] Solution - The entity type ApplicationUser is not part of the model for the current context

查看:336
本文介绍了解决方案-实体类型ApplicationUser不是当前上下文模型的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将这个问题作为文档发布,因为花了很多时间才找到这个简单的问题.我正在使用VS15生成的原始MVC项目,并尝试对其进行修改.

I am posting this question as documentation because it took me many hours to find this simple issue. I am taking the original MVC project generated by VS15 and attempting to modify it.

错误:[InvalidOperationException:实体类型ApplicationUser不是当前上下文模型的一部分.]

Error: [InvalidOperationException: The entity type ApplicationUser is not part of the model for the current context.]

推荐答案

由于各种原因,您可能会收到此错误.这不是保证的修复程序,但希望它将为某个人节省一些时间.通常会出现此错误,因为您的应用程序使用的是默认DbContext,而不是您打算使用的默认DbContext.

You may get this error for a variety of reasons. This is not a guaranteed fix but hopefully it will save some time for someone out there. This error shows up usually because your application is using a default DbContext and not the one you're intending to use.

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() : base("DefaultConnection") {}
}

项目将生成此自定义DbContext.您应该使用该类确保项目的Web.config中的"DefaultConnection"是连接字符串或连接名称.

The project generates this custom DbContext. You should make sure the "DefaultConnection" is either the connection string or the name of the connection in your Web.config of your project using this class.

这是我的连接字符串.请注意,该名称与上面的DbContext中的名称相同:

This is my connection string. Note that the name is the same as the one in the DbContext above:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-AspnetIdentitySample-10_8_3;Integrated Security=True" providerName="System.Data.SqlClient" />

确定连接字符串已设置好之后,我们需要检查NinjectWebCommon中的绑定.

Once you made sure your connection string is set up, we need to check the bindings in NinjectWebCommon.

kernel.Bind<ApplicationDbContext>().ToSelf();
kernel.Bind<IUserStore<ApplicationUser>>().To<UserStore<ApplicationUser>>().WithConstructorArgument("context", kernel.Get<ApplicationDbContext>());
kernel.Bind<UserManager<ApplicationUser>>().ToSelf();

这是我在应用程序中发现错误的地方.第一行不是必需的,但这是一个好主意.第二行是最重要的.

This is where I found the error in my application. The first line is not required but is a good idea. The second line is the most important.

UserStore有2个构造函数.第一个是空的.第二个参数有1个参数DbContext上下文. Ninject的构造函数参数区分大小写,并且必须命名为"context",Ninject才能正确选择此构造函数.

UserStore has 2 constructors. The first is empty. The second has 1 parameter, DbContext context. Ninject's constructor arguments are case-sensitive and must be named "context" for Ninject to properly select this constructor.

这篇关于解决方案-实体类型ApplicationUser不是当前上下文模型的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆