La actualización de la base de datos de Entity Framework Migration se realizó correctamente pero no se agregó la columna de la base de datos

StackOverflow https://stackoverflow.com//questions/24007883

Pregunta

Estoy usando Entity Framework en VS2012 con SQL Server 2008 R2.Tengo la migración habilitada y estoy agregando un campo de cadena (es decir,DropboxUrl) a una de mis clases de base de datos (es decir.Diseños).

// 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);

En la consola de Manager de paquetes, cuando ejecuto PM> Update-Database, se queja de que ya hay un objeto llamado 'empresas' en la base de datos.'Empresas' es una tabla que existe actualmente en la base de datos existente que estoy intentando actualizar.

es decir.

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.

Intento 1: Después de buscar este error, encontré esta solución:http://christesene.com/entity-framework-4-3-code-first-with-automatic-migrations/

Me recomendó que ejecutara primero.

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.

Y eliminó el método Arriba/Abajo:

es decir.Pude ver que DropboxUrl era un campo en el método Up pero lo eliminé como se sugirió.

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);
*/
        }

Luego, ejecuto update-database nuevamente y parece tener éxito.

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

Número 1: Mi tabla no fue modificada después de la actualización (es decir.la columna DropboxUrl que está presente en el código no se agregó a la base de datos).

Número 2: Y tampoco pude hacer que la base de datos volviera a su estado inicial:

es decir.

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.

Intento 2: También intenté usar el indicador -IgnoreChanges cuando agrego migración:Migraciones automáticas para ASP.NET SimpleMembershipProvider

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

PM> update-database -verbose

Nuevamente, vi lo mismo, donde la actualización de la base de datos se realizó correctamente pero la columna de la base de datos DropboxUrl no se agregó a la tabla Diseños.Sin embargo, si creo una nueva base de datos, la columna DropboxUrl está presente como se esperaba.

Pregunta: ¿Cómo podría solucionar el error de que ya hay un objeto llamado 'Empresas' en la base de datos al actualizar la base de datos y aún así agregar mi columna correctamente?Parece que debería ser un escenario básico que simplemente funcione.

Gracias.

¿Fue útil?

Solución

Cuando comentaste los métodos Up() y Down() en la migración, eliminaste el código para agregar la columna de la base de datos.

Debes cambiar Up() y Down() de la siguiente manera para tu inicial:

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

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

Para que Entity Framework resuelva esto por usted en el futuro, debe realizar una migración inicial para que entienda que hay una tabla existente. antes de agregar la propiedad al código.p.ej. Add-Migration -force -ignore.

Luego agregas la columna y vas Add-Migration AddedDropboxUrlColumn, y generará los métodos Up() y Down() como lo describí en una nueva migración.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top