【问题标题】:Error: DataContext has been changed, even though I am not changing anything in mvc.net code first.错误:DataContext 已更改,即使我没有先更改 mvc.net 代码中的任何内容。
【发布时间】:2016-08-21 06:40:24
【问题描述】:

我首先使用代码来使用 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。

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 我已经更新了迁移,但如果我不删除迁移文件夹,它就不起作用。当我删除迁移文件夹应用程序工作。
    • 你没有忘记更新数据库吧?此外,如果您查看数据库中的用户表,您是否看到存在这 2 个添加的字段?迁移文件夹通常不会引起任何问题......是否有新的错误出现?更新数据库时可能像“没有权限”?
    • 嗯,我想暂时没有问题,我会在需要的时候尝试更新一些字段,然后再试一次,非常感谢!
    • 如果有时间可以看看我的另一个问题吗? stackoverflow.com/questions/36881617/…很抱歉在这里问这个问题
    • 我尝试启用迁移和更新数据库,但它仍然给我同样的错误。我每次都必须删除迁移文件夹
    【解决方案2】:

    你说你删除了 Migrations 文件夹,你不能这样做。

    Migrations 与比较一起工作,它将更改与上次迁移进行比较,如果您没有上次迁移,则新的迁移将为空。

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

    1. 评论模型;
    2. 注释您添加到 ApplicationUser 的行;
    3. 注释您添加到寄存器或其他的新参数 页面;
    4. 添加新的迁移并更新数据库;
    5. 全部取消注释;
    6. 添加新的迁移和更新数据库。

    如果您需要启用迁移:Enable-Migrations

    添加新迁移:Add-Migration &lt;string&gt;

    更新数据库:Update-Database

    【讨论】:

      猜你喜欢
      • 2014-04-01
      • 2011-04-30
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 2013-02-28
      • 1970-01-01
      相关资源
      最近更新 更多