错误:DataContext已更改,即使我没有先更改mvc.net代码中的任何内容。

时间:2016-04-27 06:20:20

标签: asp.net-mvc entity-framework code-first ef-migrations

我首先使用代码来使用mvc.net开发Web应用程序。 我已经向IdentityUser添加了两个字段,如此

  public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
    public string ScreenName { get; set; }

    public string UserType { get; set; }
}

我在第一个控制器上使用这个字段

                UserId = User.Identity.GetUserId(),
                NewUserId = Genrate.GenrateUserId(),
                NewUserIdWithString = "Unspecified"  

除此之外,所有应用程序都运行良好,但我不知道在添加这些东西后,没有任何作用,它说,datacontext已被更改,可能是/是另一个问题/ s。

2 个答案:

答案 0 :(得分:0)

您通过添加以下两行来更改数据库模型:

public string ScreenName { get; set; }
public string UserType { get; set; }

数据库不再与您的代码匹配,您的应用程序崩溃。

然而,更新所述数据库以包含这两个新字段非常容易。 转到程序包管理器控制台(默认布局中VS的底部)并键入 add-migration控制台将提示您输入迁移的名称。填写姓名,然后输入下一个update-database 第一次执行此操作时,您可能需要先输入Enable-Migrations

然后数据库将更新到您的新架构(请注意,它不会删除任何现有数据并将默认值添加到不可为空的字段)

答案 1 :(得分:0)

您说您删除了迁移文件夹,但您无法执行此操作。

迁移适用于比较,它将更改与上次迁移进行比较,如果您没有上次迁移,则新迁移将为空。

为了解决这个问题,请执行以下操作:

  1. 评论模型;
  2. 注释您添加到ApplicationUser的行;
  3. 注释您添加到注册或其他参数的新参数 页;
  4. 添加新迁移并更新数据库;
  5. 取消全部注释;
  6. 添加新的迁移和更新数据库。
  7. 如果您需要启用迁移:Enable-Migrations

    添加新迁移:Add-Migration <string>

    更新数据库:Update-Database