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

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

问题描述

我已经设置了一个新的asp.net Web表单应用程序。我想使用我自己的实体框架数据模型使用提供的owin身份验证创建一个登录并注册功能。



我已经从默认和IdentityModels.cs中更改了我的连接字符串,但是当使用登录时,我收到上面的错误。



代码与默认值不变,当我将ApplicationDBContext更改回DefaultConnection时,它的工作原理如下。



我可以从我的数据库中访问数据,因为我使用一个linq查询来检查输入的电子邮件和密码。



错误在以下行中抛出登录用户控件:

  var result = signinManager.PasswordSignIn(Email.Text,Password.Text,RememberMe.Checked,shouldLockout:假); 

有没有什么我需要做的,使owin身份验证工作与提供的DefaultConnection以外的数据库?



代码段:



生成的注册:

  protected void CreateUser_Click(object sender,EventArgs e)
{
var manager = Context.GetOwinContext ).GetUserManager< ApplicationUserManager>();
var signInManager = Context.GetOwinContext()。Get< ApplicationSignInManager>();
var user = new ApplicationUser(){UserName = Email.Text,Email = Email.Text};
IdentityResult result = manager.Create(user,Password.Text);
if(result.Succeeded)
{
signInManager.SignIn(user,isPersistent:false,rememberBrowser:false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString [ReturnUrl],Response);
}
else
{
ErrorMessage.Text = result.Errors.FirstOrDefault();
}
}

生成的登录: / p>

  protected void LogIn(object sender,EventArgs e)
{
if(IsValid)
{
//验证用户密码
var manager = Context.GetOwinContext()。GetUserManager< ApplicationUserManager>();
var signinManager = Context.GetOwinContext()。GetUserManager< ApplicationSignInManager>();

var result = signinManager.PasswordSignIn(Email.Text,Password.Text,RememberMe.Checked,shouldLockout:false);

开关(结果)
{
case SignInStatus.Success:
IdentityHelper.RedirectToReturnUrl(Request.QueryString [ReturnUrl],Response);
break;
case SignInStatus.LockedOut:
Response.Redirect(/ Account / Lockout);
break;
case SignInStatus.RequiresVerification:
Response.Redirect(String.Format(/ Account / TwoFactorAuthenticationSignIn?ReturnUrl = {0}& RememberMe = {1},
Request.QueryString [ ReturnUrl],
RememberMe.Checked),
true);
break;
case SignInStatus.Failure:
default:
FailureText.Text =无效登录尝试;
ErrorMessage.Visible = true;
break;
}

Linq查询查找用户:

  var myUser = db.Dat_Account 
.FirstOrDefault(u => u.UserName == Email.Text
&& u.Password == Password.Text);

生成的ApplicationUser



public class ApplicationUser:IdentityUser
{
public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)
{
//请注意,authenticationType必须与一个在CookieAuthenticationOptions.AuthenticationType
var userIdentity = manager.CreateIdentity(this,DefaultAuthenticationTypes.ApplicationCookie)中定义;
//在此添加自定义用户声明
return userIdentity;
}

public Task< ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
{
return Task.FromResult(GenerateUserIdentity(manager));
}
}

我的用户表有更多的字段,电子邮件和密码。这是否可能导致问题?



上下文:

  public class ApplicationDbContext:IdentityDbContext< ApplicationUser> 
{
public ApplicationDbContext()
:base(MyDBEntities,throwIfV1Schema:false)
{
}

public static ApplicationDbContext Create ()
{
return new ApplicationDbContext();
}
}


解决方案

就像没有数据库初始化器一样,默认行为是CreateDatabaseIfNotExists。所以要么删除现有的数据库,让EF创建它与身份的东西,或者将初始化器切换到您的构造函数中的DropCreateDatabaseWhenModelChanges:

  static ApplicationDbContext(){
Database.SetInitializer(new DropCreateDatabaseWhenModelChanges< ApplicationDbContext>());
}

一旦你开始运行并拥有数据,你不想失去,您应该关闭初始化程序(Database.SetInitializer(new NullDatabaseInitializer());)或使用迁移。



http://www.codeguru.com/csharp/article.php /c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm


I have set up a new asp.net web forms application. I want to create a log on and register feature using the provided owin authentication using my own entity framework data model.

I have changed my connection string from the default and within IdentityModels.cs but when using the login I receive the error above.

The code is unchanged from the default and when I change the ApplicationDBContext back to the DefaultConnection it works as expected.

I am able to access data from my database as I have used a linq query to check the email and password entered.

The error is thrown on the following line within the login user control:

 var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

Is there something I need to do to make owin authentication work with a database other than the DefaultConnection supplied?

Code Snippets:

Generated Register:

protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
            var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text };
            IdentityResult result = manager.Create(user, Password.Text);
            if (result.Succeeded)
            {    
                signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else 
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }

Generated Login:

protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validate the user password
                var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

                var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

                switch (result)
                {
                    case SignInStatus.Success:
                        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                        break;
                    case SignInStatus.LockedOut:
                        Response.Redirect("/Account/Lockout");
                        break;
                    case SignInStatus.RequiresVerification:
                        Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}", 
                                                        Request.QueryString["ReturnUrl"],
                                                        RememberMe.Checked),
                                          true);
                        break;
                    case SignInStatus.Failure:
                    default:
                        FailureText.Text = "Invalid login attempt";
                        ErrorMessage.Visible = true;
                        break;
                }

Linq query to find user:

var myUser = db.Dat_Account
                    .FirstOrDefault(u => u.UserName == Email.Text
                    && u.Password == Password.Text);

Generated ApplicationUser

public class ApplicationUser : IdentityUser
    {
        public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        public Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            return Task.FromResult(GenerateUserIdentity(manager));
        }
    }

My user table has many more fields than just username, email and password. Is it possible that this causes an issue?

Context:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
        : base("MyDBEntities", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

解决方案

Looks like you don't have a database initializer so the default behavior would be CreateDatabaseIfNotExists. So either remove the existing database and let EF create it with the identity stuff, or switch the initializer to DropCreateDatabaseWhenModelChanges in your constructor:

static ApplicationDbContext() {
    Database.SetInitializer(new DropCreateDatabaseWhenModelChanges<ApplicationDbContext>());
}

Once you are up and running and have data you don't want to lose, you should switch the initializer off (Database.SetInitializer(new NullDatabaseInitializer());) or use migrations.

http://www.codeguru.com/csharp/article.php/c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm

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

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