实体框架迁移更新数据库成功,但未添加数据库列

坦率

我在带有SQL Server 2008 R2的VS2012中使用实体框架。我已启用迁移,并且正在向我的数据库类之一(即设计)中添加一个字符串字段(即DropboxUrl)。

// Design.cs

public class Design
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }

        [StringLength(Constants.DESIGN_NAME_MAX_LENGTH)]
        public string Name { get; set; }

        [StringLength(Constants.DESIGN_DESC_MAX_LENGTH)]
        public string Description { get; set; }

        public ItemDate Dates { get; set; }

        public string DropboxUrl { get; set; } // Added this line
    }

// SedaContext.cs:

public class SedaContext : DbContext
    {
        public DbSet<Company> Companies { get; set; }

        public DbSet<Design> Designs { get; set; }
}


// Global.aspx
protected void Application_Start()
        {

            // Application initialize
            // https://stackoverflow.com/questions/3600175/the-model-backing-the-database-context-has-changed-since-the-database-was-crea

            Database.SetInitializer<SedaContext>(null);

在Package Manager控制台中,当我运行PM> update-database时,它抱怨数据库中已经存在一个名为“ Companies”的对象。“公司”是我要更新的现有数据库中当前存在的表。

即。

PM> update-database -verbose
Using StartUp project 'UI'.
Using NuGet project 'UI'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'SedaDev' (DataSource: ., Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Applying automatic migration: 201405311730564_AutomaticMigration.
CREATE TABLE [dbo].[Companies] (
    [Id] [uniqueidentifier] NOT NULL DEFAULT newsequentialid(),
    [Name] [nvarchar](max),
    [Description] [nvarchar](max),
    [Owner_UserId] [int],
    CONSTRAINT [PK_dbo.Companies] PRIMARY KEY ([Id])
)
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Companies' in the database.
...
   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.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:fa9e9e62-aba0-435f-9309-e9fc8fbe19d5

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

尝试1:搜寻此错误后,我遇到了以下解决方法:http : //christesene.com/entity-framework-4-3-code-first-with-automatic-migrations/

建议我先跑

PM> Add-migration initial

Scaffolding migration 'initial'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration initial' again.

并删除了Up / Down方法:

即。我可以看到DropboxUrl是Up方法中的一个字段,但是我按照建议将其删除。

public override void Up()
        {
/*
    CreateTable(
                "dbo.Companies",
                c => new
                    {
                        Id = c.Guid(nullable: false, identity: true),
                        Name = c.String(),
                        Description = c.String(),
                        Owner_UserId = c.Int(),
                    })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.UserProfiles", t => t.Owner_UserId)
                .Index(t => t.Owner_UserId);
...
  CreateTable(                "dbo.Designs",
                c => new
                    {
                        Id = c.Guid(nullable: false, identity: true),
                        Name = c.String(maxLength: 100),
                        Description = c.String(maxLength: 1000),
                        Dates_Create = c.DateTime(nullable: false),
                        Dates_LastUpdate = c.DateTime(nullable: false),
                        DropboxUrl = c.String(),
                        Project_Id = c.Guid(),
                    })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.Projects", t => t.Project_Id)
                .Index(t => t.Project_Id);
*/
        }

之后,我再次运行update-database,它似乎成功。

PM> update-database -verbose
Using StartUp project 'UI'.
Using NuGet project 'UI'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'SedaDev' (DataSource: phobos.spxis.com, Provider: System.Data.SqlClient, Origin: Configuration).
Applying explicit migrations: [201406020449030_initial].
Applying explicit migration: 201406020449030_initial.
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])

VALUES (N'201406020449030_initial', N'Delecs.Seda.DataAccess.Migrations.Configuration',  0x1F8B0800000000000400ED1DCB72DCB8F19EAAFCC3D49C92544523D9F166
...
7B7C117028FAD9D8632C54E5F87C13A0D36590D83B7A73FA9F8AD368F7FFE3F0347EA807B340100 , N'6.0.2-21211')
Running Seed method

问题1:更新后我的表未更改(即,代码中存在的DropboxUrl列未添加到数据库中)。

问题2:而且我也无法使数据库恢复到初始状态:

即。

PM> update-database -TargetMigration $InitialDatabase
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Reverting migrations: [201406020449030_initial].
Reverting automatic migration: 201406020449030_initial.
Automatic migration was not applied because it would result in data loss.
PM> update-database -TargetMigration $InitialDatabase -force
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Reverting migrations: [201406020449030_initial].
Reverting automatic migration: 201406020449030_initial.
System.Data.SqlClient.SqlException (0x80131904): Could not drop object 'dbo.UserProfiles' because it is referenced by a FOREIGN KEY constraint.

尝试2:添加迁移时,我还尝试使用-IgnoreChanges标志:ASP.NET SimpleMembershipProvider的自动迁移

PM> Add-migration initial -IgnoreChanges
Re-scaffolding migration 'initial'.

PM> update-database -verbose

同样,我看到了同样的事情,更新数据库成功了,但是数据库列DropboxUrl没有添加到Designs表中。但是,如果我创建一个新数据库,则DropboxUrl列将按预期方式显示。

问题:在更新数据库时,如何解决数据库错误中已经存在名为“ Companies”的对象,并且仍然成功添加我的列的问题?看来这应该是可行的基本方案。

谢谢。

里斯·斯蒂芬斯(Rhys Stephens)

当注释掉迁移的Up()和Down()方法时,您删除了添加数据库列的代码。

您应该按以下方式更改Up()和Down():

public override void Up() {
   AddColumn("Companies", "DropboxUrl", x => x.String());
}

public override void Down() {
    DropColumn("Companies", "DropboxUrl");
}

为了使Entity Framework将来能够为您解决此问题,您需要进行一次初始迁移,以使其了解在将属性添加到代码之前已经存在一个表例如Add-Migration -force -ignore.

然后,添加列go Add-Migration AddedDropboxUrlColumn,它将生成Up()和Down()方法,如我在新迁移中所述。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

实体框架迁移更新数据库成功,但未添加数据库列

来自分类Dev

使用实体框架代码优先迁移添加数据库触发器

来自分类常见问题

实体框架核心更新-特定于数据库的迁移

来自分类Dev

实体框架-“从数据库更新”未添加表

来自分类Dev

实体框架无法更新数据库

来自分类Dev

实体框架数据库更新

来自分类Dev

Automapper,实体框架更新数据库

来自分类Dev

实体框架更新数据库

来自分类Dev

添加数组数据库列

来自分类Dev

使用实体框架核心更新数据库中的列

来自分类Dev

在实体框架迁移期间读取数据库(选择查询)

来自分类Dev

MySql数据库中的实体框架代码优先迁移

来自分类Dev

使用实体框架7添加新迁移时,表未添加到数据库

来自分类Dev

使用实体框架7添加新迁移时,表未添加到数据库

来自分类Dev

更新/添加数据到Google Spreadsheet数据库

来自分类Dev

身份实体框架库-更新数据库[MySQL]

来自分类Dev

如何更新实体框架7迁移和数据库-代码优先

来自分类Dev

如何在服务器生产中更新迁移数据库实体框架

来自分类Dev

如何使用没有迁移历史记录的实体框架更新数据库

来自分类Dev

实体框架-添加现有数据库

来自分类Dev

实体框架数据库优先不添加表

来自分类Dev

在并发数据库更新时锁定实体框架代码

来自分类Dev

更新数据库条目MVC实体框架

来自分类Dev

实体框架数据库更新优先多重性冲突

来自分类Dev

如何使用实体框架从DataGrid更新数据库

来自分类Dev

尝试先使用实体框架代码更新数据库

来自分类Dev

实体框架核心,更新数据库不考虑属性

来自分类Dev

使用DTO实体框架,如何更新数据库?

来自分类Dev

实体框架不会更新Amazon RDS SQL数据库

Related 相关文章

热门标签

归档