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

时间:2016-01-21 20:55:31

标签: c# asp.net entity-framework asp.net-identity owin

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

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

代码与默认代码保持不变,当我将ApplicationDBContext更改回DefaultConnection时,它按预期工作。

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

登录用户控件中的以下行引发错误:

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

我是否需要做一些事情来使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();
            }
        }

生成登录:

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查询以查找用户:

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)
        {
            // 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));
        }
    }

我的用户表包含的字段多于用户名,电子邮件和密码。这可能导致问题吗?

上下文:

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

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

1 个答案:

答案 0 :(得分:0)

看起来您没有数据库初始化程序,因此默认行为是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