【问题标题】:How to recreate my EF CodeFirst Table?如何创建我的 EF 代码优先表?
【发布时间】:2013-01-14 13:59:00
【问题描述】:

我创建了一个 Code First 类

在Sql中自动创建了一个数据库。

我删除了表格:(

我已启用迁移:

AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
Database.SetInitializer(new DropCreateDatabaseAlways<SurveyContext>());

还有

update-database -force

Cannot find the object "dbo.CustomerResponses" because it does not exist or you do not have permissions.

请帮忙。

【问题讨论】:

  • 你的上下文是什么样的?
  • 你试过用谷歌搜索"Cannot find the object because it does not exist or you do not have permissions"吗?

标签: entity-framework code-first


【解决方案1】:

在系统表中有一个名为

的表
__MigrationHistory

...我删除了它。

在包管理器控制台中运行命令“update-database” 问题已解决!

更多信息:

http://blog.oneunicorn.com/2012/02/27/code-first-migrations-making-__migrationhistory-not-a-system-table/

【讨论】:

  • 似乎只有在您的项目No migrations configuration type was found in the assembly '{project_name}'. 中定义了迁移信息时才有效。但值得一试。
  • 手头主题的便捷链接 - msdn.microsoft.com/en-us/data/jj591621.aspx
  • 此解决方案的缺点是您会丢失迁移历史记录。
  • 我试过了,但它不会更新,因为其他表已经存在
【解决方案2】:

Daf De Giraf 有一个更好的答案 here,它不会抹去你的迁移历史。

如果您以正确的方式使用 命令Add-Migration "Name_Of_Migration" 然后你可以做 跟随以获得干净的开始(重置,丢失数据, 课程):

  1. Update-database -TargetMigration:0
    通常,由于执行了 down 方法,您的数据库现在是空的。

  2. Update-database 这会将您的数据库重新创建到您当前的迁移中

【讨论】:

    【解决方案3】:

    我过去曾收到过该错误消息....

    检查您在连接字符串中指定的数据库是否已创建。如果不是,请创建它然后执行代码。

    【讨论】:

      【解决方案4】:

      显然可能有更好的方法来做到这一点,但由于这是令人惊讶的顶级 Google 帐户,我认为在阅读这些答案后提及我的想法会很好:

      这是我面临的问题: 我首先更改了由 EF6 代码生成的 FK,然后遇到了错误:

      Unable to determine the relationship represented by navigation property 'Account.SalaryIncomes' of type 'ICollection<Person>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
      

      为了解决这个错误,我尝试了许多定义映射的方法,但是我最终删除了我的 Person 表,并且在完全删除关系以尝试从头开始之后,错误得到了解决。然而,在更新数据库时,它抱怨“人”不存在——这导致我来到这里。

      查看这些答案后,我决定我懒得重新加载数据,并认为迁移生成了 C# UP() 和 Down() 方法 - 我想,也许我可以参考另一个迁移... 在将 up 和 down 代码提取到该迁移中的公共方法中,并从新迁移中引用这些方法之后 - 更新有效,然后创建了 person。为了安全起见 - 我将新调用包装在 try catch... 我的新 UP 方法看起来像这样吗:

      protected override void Up(MigrationBuilder migrationBuilder)
          {
              try
              {
                  new AddPeople().CreatePersonTable(migrationBuilder);
              }
              catch { }
      
              // Origional generated migration code
          }
      

      这个答案伴随着我没有测试过下次是否会覆盖此迁移(丢失代码)的 caviat - 但是,如果迁移按顺序运行,那么您实际上可以运行一次,并且然后删除它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-15
        • 2012-08-05
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 2011-12-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多