草庐IT

c# - EF 5 代码迁移错误 : "There is already an object named _____ in the database"

coder 2024-05-28 原文

在进行 EF5 代码迁移时遇到了一个反复出现的奇怪问题,现在让我无法工作。尝试运行 update-database 并收到此错误:

There is already an object named 'RequestStatus' in the database.

详细的日志转储:

PM> update-database -v
Using StartUp project 'LicensingWorkflow'.
Using NuGet project 'LicensingWorkflow'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'LicensingWorkflow.Models.LicenseWorkflowContext' (DataSource: (localdb)\v11.0, Provider: System.Data.SqlClient, Origin: Convention).
Applying code-based migrations: [201311111934210_AddRequestStatusToContext].
Applying code-based migration: 201311111934210_AddRequestStatusToContext.
CREATE TABLE [dbo].[RequestStatus] (
    [Id] [bigint] NOT NULL IDENTITY,
    [Status] [nvarchar](max),
    CONSTRAINT [PK_dbo.RequestStatus] PRIMARY KEY ([Id])
)
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'RequestStatus' in the database.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
ClientConnectionId:38d030fa-496e-4091-88eb-49093d76da14
There is already an object named 'RequestStatus' in the database.

我已经尝试了在 Google 上找到的一切。 我尝试过但没有提供任何结果的事情:

  • 尝试启动一个新数据库。
  • 删除 __MigrationHistory
  • This , this , 和 this .

最让人恼火的是我的同事在同一个代码库中,根本没有遇到这个问题。我正在使用 VS2012 和 EF5 的 LocalDb。

一些引用代码

数据库初始化器

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<LicenseWorkflowContext>());

数据库上下文

namespace LicensingWorkflow.Models {
    public class LicenseWorkflowContext : DbContext {

        public DbSet<License> Licenses { get; set; } 
        public DbSet<RequestHistory> RequestHistories { get; set; }
        public DbSet<RequestType> RequestTypes { get; set; }
        public DbSet<HistoryStatus> HistoryStatuses { get; set; }
        public DbSet<Request> Requests { get; set; }
        public DbSet<LicenseStatus> LicenseStatuses { get; set; }
        public DbSet<RequestEntryAnswerReference> RequestEntryAnswerReferences { get; set; }
        public DbSet<Comment> Comments { get; set; }
        public DbSet<SuretyBond> SuretyBonds { get; set; }
        public DbSet<RequestStatus> RequestStatuses { get; set; } 
    }
}

失败的 RequestStatus。

namespace LicensingWorkflow.Models {
    public class RequestStatus {
        public long Id { get; set; }
        public string Status { get; set; }
    }
}

它是请求模型的一部分

namespace LicensingWorkflow.Models {
    public class Request {
        public long Id { get; set; }
        public string RequesterId { get; set; }
        public string SupervisorId { get; set; }
        public DateTime RequestDate { get; set; }
        public long SurveyId { get; set; }
        public string WorkerId { get; set; }
        public long RequestTypeId { get; set; }
        public string State { get; set; }
        public List<Comment> Comments { get; set; }
        public RequestEntryAnswerReference ReqeustEntryAnswerReference { get; set; }
        public long? LicenseId { get; set; }
        public RequestStatus RequestStatus { get; set; }
    }
}

种子方法/Configuration.cs

public sealed class Configuration : DbMigrationsConfiguration<LicensingWorkflow.Models.LicenseWorkflowContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(LicensingWorkflow.Models.LicenseWorkflowContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );license branch renewal deficiency surrender
            //



            var status1 = new LicenseStatus { Id = 1, Status = "ok" };
            var status2 = new LicenseStatus { Id = 2, Status = "deficient" };
            var status3 = new LicenseStatus{Id = 3, Status = "inactive"};
            context.LicenseStatuses.AddOrUpdate(
                ls => ls.Id,
                status1,
                status2,
                status3
            );

            var license = new License {
                Id = 1,
                LicenseStatus = new LicenseStatus {Status = "ok"},
                LicenseNumber = 12345,
                OwnerId = "022567",
                ObtainedDate = new DateTime(2012, 10, 3),
                ExpirationDate = new DateTime(2013, 12, 12),
                State = "Minnesota",
                Type = "individual"
            };
            var license2 = new License {
                Id = 2,
                LicenseStatus = new LicenseStatus {Status = "deficient"},
                LicenseNumber = 12346,
                OwnerId = "022567",
                ObtainedDate = new DateTime(2012, 10, 3),
                ExpirationDate = new DateTime(2013, 12, 12),
                State = "Texas",
                Type = "individual"
            };

            var license3 = new License {
                Id = 3,
                LicenseStatus = new LicenseStatus { Status = "ok" },
                LicenseNumber = 12347,
                OwnerId = "025253",
                ObtainedDate = new DateTime(2012, 10, 3),
                ExpirationDate = new DateTime(2013, 12, 12),
                State = "Minnesota",
                Type = "individual"
            };
            var license4 = new License {
                Id = 4,
                LicenseStatus = new LicenseStatus { Status = "deficient" },
                LicenseNumber = 12348,
                OwnerId = "025253",
                ObtainedDate = new DateTime(2012, 10, 3),
                ExpirationDate = new DateTime(2013, 12, 12),
                State = "Texas",
                Type = "individual"
            };

            context.Licenses.AddOrUpdate(
                l => l.Id,
                license,
                license2
            );

            context.RequestTypes.AddOrUpdate(
                rt => rt.Id,
                new RequestType { Id = 1, Type = "license" },
                new RequestType { Id = 2, Type = "renewal" },
                new RequestType { Id = 3, Type = "deficiency" },
                new RequestType { Id = 4, Type = "surrender" },
                new RequestType { Id = 5, Type = "branch" },
                new RequestType { Id = 6, Type = "doNotRenew"}
            );

            var requestStatus1 = new RequestStatus() {
                Id = 1,
                Status = "submitted"
            };

            var requestStatus2 = new RequestStatus() {
                Id = 2,
                Status = "approved"
            };

            var requestStatus3 = new RequestStatus() {
                Id = 3,
                Status = "processing"
            };

            var requestStatus4 = new RequestStatus() {
                Id = 4,
                Status = "completed"
            };

            var requestStatus5 = new RequestStatus() {
                Id = 5,
                Status = "withdrawn"
            };

            var requestStatus6 = new RequestStatus() {
                Id = 6,
                Status = "denied"
            };

            context.RequestStatuses.AddOrUpdate(
                rs => rs.Id,
                requestStatus1,
                requestStatus2,
                requestStatus3,
                requestStatus4,
                requestStatus5,
                requestStatus6
            );

            var request1 = new Request {
                Id = 1,
                RequesterId = "123",
                RequestDate = DateTime.Now,
                RequestTypeId = 1,
                SupervisorId = "022567",
                State = "California",
                WorkerId = "",
                SurveyId = 62
            };

            var unassignedRequest1 = new Request{
                Id = 2,
                RequesterId = "123",
                RequestDate = DateTime.Now,
                RequestTypeId = 1,
                SupervisorId = "022567",
                State = "NewMexico",
                WorkerId = ""
            };

            var unassignedRequest2 = new Request {
                Id = 3,
                RequesterId = "123",
                RequestDate = DateTime.Now,
                RequestTypeId = 1,
                SupervisorId = "123",
                State = "Missouri",
                WorkerId = ""
            };

            var unassignedRequest3 = new Request {
                Id = 4,
                RequesterId = "123",
                RequestDate = DateTime.Now,
                RequestTypeId = 1,
                SupervisorId = "123",
                State = "Florida",
                WorkerId = ""
            };

            context.Requests.AddOrUpdate(
                r => r.Id,
                unassignedRequest1,
                unassignedRequest2,
                unassignedRequest3,
                request1
            );

            var requestEntryAnswerReference = new RequestEntryAnswerReference {
                Id = 1,
                RequestId = 1,
                ReferenceKey = "xxxxx-xxxxx-xxxxxx-xxxxx"
            };

            context.RequestEntryAnswerReferences.AddOrUpdate(
                r => r.Id,
                requestEntryAnswerReference
            );

            var comment1 = new Comment(){
                Id = 1,
                CommentText = "Test test test",
                CommenterId = "123",
                PostedDate = DateTime.Now,
                RequestId = 1
            };

            var comment2 = new Comment() {
                Id = 2,
                CommentText = "Test test test",
                CommenterId = "123",
                PostedDate = DateTime.Now,
                RequestId = 1
            };

            var comment3 = new Comment() {
                Id = 3,
                CommentText = "Test test test",
                CommenterId = "123",
                PostedDate = DateTime.Now,
                RequestId = 1
            };

            context.Comments.AddOrUpdate(
                r => r.Id,
                comment1,
                comment2,
                comment3
            );

            request1.Comments = new List<Comment> {
                comment1,
                comment2,
                comment3
            };

            context.Requests.AddOrUpdate(
                r => r.Id,
                request1
            );

            var hstatus1 = new HistoryStatus() { Id = 1, Status = "approved" };
            var hstatus2 = new HistoryStatus() { Id = 2, Status = "denied" };
            var hstatus3 = new HistoryStatus() { Id = 3, Status = "completed" };
            var hstatus4 = new HistoryStatus() { Id = 4, Status = "withdrawl" };
            var hstatus5 = new HistoryStatus() { Id = 5, Status = "assigned" };
            var hstatus6 = new HistoryStatus() { Id = 6, Status = "unassigned" };

            context.HistoryStatuses.AddOrUpdate(
                hs => hs.Id,
                hstatus1,
                hstatus2,
                hstatus3,
                hstatus4,
                hstatus5,
                hstatus6
            );
        }
    }
}

最佳答案

确保连接字符串的名称与您尝试更新的 DbContext 相同。换句话说,您正在尝试修改现有数据库。

关于c# - EF 5 代码迁移错误 : "There is already an object named _____ in the database",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19964679/

有关c# - EF 5 代码迁移错误 : "There is already an object named _____ in the database"的更多相关文章

  1. ruby-on-rails - Ruby on Rails 迁移,将表更改为 MyISAM - 2

    如何正确创建Rails迁移,以便将表更改为MySQL中的MyISAM?目前是InnoDB。运行原始执行语句会更改表,但它不会更新db/schema.rb,因此当在测试环境中重新创建表时,它会返回到InnoDB并且我的全文搜索失败。我如何着手更改/添加迁移,以便将现有表修改为MyISAM并更新schema.rb,以便我的数据库和相应的测试数据库得到相应更新? 最佳答案 我没有找到执行此操作的好方法。您可以像有人建议的那样更改您的schema.rb,然后运行:rakedb:schema:load,但是,这将覆盖您的数据。我的做法是(假设

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  5. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  6. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  7. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  8. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  9. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  10. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

随机推荐