自创建数据库以来,支持'SisContext'上下文的模型已更改。考虑使用Code First Migrations来更新数据库

时间:2013-06-13 15:22:52

标签: asp.net-mvc asp.net-mvc-4 membership-provider ef-migrations

当我尝试使用数据库(SIS)中提供的详细信息登录时,出现此错误。

The model backing the 'SisContext' context has changed since the database was created. Consider using Code First Migrations to update the database. Thing is Database(SIS) was manually added using add existing item and not generated automatically.

我的SisContext看起来像这样

public class SisContext : DbContext
    {
        //protected override void OnModelCreating(DbModelBuilder modelBuilder)
        //{
        //    modelBuilder.Conventions.Remove<System.Data.Entity.Infrastructure.IncludeMetadataConvention>();
        //}
        public DbSet<User> Users { get; set; }
        public DbSet<AspNetUser> AspNetUsers { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<BusinessUnit> BusinessUnits { get; set; }
        public DbSet<LicenseHolder> LicenseHolders { get; set; }
        public DbSet<License> Licenses { get; set; }

        public SisContext():base("SIS")
        {
            if (HttpContext.Current == null)
            {
                Database.SetInitializer<SisContext>(null);
            }
        }
    }

我有另一个名为DataContextInitializer的类,看起来像这样

public class DataContextInitializer:DropCreateDatabaseAlways<SisContext>
    {
        protected override void Seed(SisContext context)
        {
        WebSecurity.Register("Demo", "123456", "demo@demo.com", true, "Demo", "Demo");
        Roles.CreateRole("Admin");
        Roles.AddUserToRole("Demo", "Admin");
        }
    }

在我的AccountController中,Login方法如下;

 public class AccountController : Controller
    {

        //
        // GET: /Account/
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(LoginModel model)
        {
            if(Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                return RedirectToAction("Index", "Home");
            }
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

        public ActionResult Index()
        {
            return View();
        }

    }
上述ValidateUser操作中使用的

Login方法位于继承自CodeFirstMembershipProvider

的类MembershipProvider类中
 public override bool ValidateUser(string username, string password)
        {
            if (string.IsNullOrEmpty(username))
            {
                return false;
            }
            if (string.IsNullOrEmpty(password))
            {
                return false;
            }
            using (SisContext Context = new SisContext())
            {
                AspNetUser User = null;
                User = Context.AspNetUsers.FirstOrDefault(Usr => Usr.Username == username);//error mentioned above is shown here
                if (User == null)
                {
                    return false;
                }
                if (!User.IsApproved)
                {
                    return false;
                }
                if (User.IsLockedOut)
                {
                    return false;
                }
                String HashedPassword = User.Password;
                Boolean VerificationSucceeded = (HashedPassword != null && Crypto.VerifyHashedPassword(HashedPassword, password));
                if (VerificationSucceeded)
                {
                    User.PasswordFailuresSinceLastSuccess = 0;
                    User.LastLoginDate = DateTime.UtcNow;
                    User.LastActivityDate = DateTime.UtcNow;
                }
                else
                {
                    int Failures = User.PasswordFailuresSinceLastSuccess;
                    if (Failures < MaxInvalidPasswordAttempts)
                    {
                        User.PasswordFailuresSinceLastSuccess += 1;
                        User.LastPasswordFailureDate = DateTime.UtcNow;
                    }
                    else if (Failures >= MaxInvalidPasswordAttempts)
                    {
                        User.LastPasswordFailureDate = DateTime.UtcNow;
                        User.LastLockoutDate = DateTime.UtcNow;
                        User.IsLockedOut = true;
                    }
                }
                Context.SaveChanges();
                if (VerificationSucceeded)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

在我的网页配置中,我添加了我的custommembershipProvider

 <membership defaultProvider="CodeFirstMembershipProvider">
      <providers>
        <clear />
        <add name="CodeFirstMembershipProvider" type="Sorama.CustomAuthentication.CodeFirstMembershipProvider" connectionStringName="SisContext" />
      </providers>
    </membership>
    <roleManager enabled="true" defaultProvider="CodeFirstRoleProvider">
      <providers>
        <clear />
        <add name="CodeFirstRoleProvider" type="Sorama.CustomAuthentication.CodeFirstRoleProvider" connectionStringName="SisContext" />
      </providers>
    </roleManager>

    <!--<httpModules>
      <add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
      <add name="DomainServiceModule" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </httpModules>-->
    <httpRuntime maxRequestLength="2147483647" executionTimeout="180" />
    <httpModules>
      <add name="DomainServiceModule" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </httpModules>
  </system.web>
  <connectionStrings>
    <add name="SISContext" connectionString="Data Source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\SIS.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>

1 个答案:

答案 0 :(得分:0)

您是否尝试过此链接.... http://msdn.microsoft.com/en-us/data/jj591621。我正在使用MVC3和EF6.0.0.1 我遇到了同样的问题,但是通过启用代码优先迁移,错误消失了。