Die Datenbankaktualisierung der Entity Framework-Migration war erfolgreich, aber die Datenbankspalte wurde nicht hinzugefügt

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

Frage

Ich verwende Entity Framework in VS2012 mit SQL Server 2008 R2.Ich habe die Migration aktiviert und füge ein Zeichenfolgenfeld hinzu (z. B.DropboxUrl) zu einer meiner Datenbankklassen (z. B.Entwürfe).

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

Wenn ich in der Paket-Manager-Konsole PM> Update-Database ausführe, beschwert sich es, dass in der Datenbank bereits ein Objekt mit dem Namen "Unternehmen" vorhanden ist.„Unternehmen“ ist eine Tabelle, die derzeit in der vorhandenen Datenbank vorhanden ist, die ich aktualisieren möchte.

dh.

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.

Versuch 1: Nachdem ich nach diesem Fehler gesucht habe, bin ich auf diesen Workaround gestoßen:http://christesene.com/entity-framework-4-3-code-first-with-automatic-migrations/

Es wurde mir empfohlen, zuerst zu laufen

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.

Und die Up/Down-Methode entfernt:

dh.Ich konnte sehen, dass DropboxUrl ein Feld in der Up-Methode war, habe es aber wie vorgeschlagen entfernt.

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

Danach führe ich update-database erneut aus und es scheint erfolgreich zu sein.

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

Fehler 1: Meine Tabelle wurde nach dem Update nicht verändert (d. h.Die im Code vorhandene DropboxUrl-Spalte wurde nicht zur Datenbank hinzugefügt.

Problem 2: Und ich konnte die Datenbank auch nicht in den Ausgangszustand zurückversetzen:

dh.

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.

Versuch 2: Ich habe auch versucht, das Flag -IgnoreChanges zu verwenden, wenn ich „migration“ hinzufüge:Automatische Migrationen für ASP.NET SimpleMembershipProvider

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

PM> update-database -verbose

Wieder habe ich das Gleiche gesehen, wobei die Aktualisierung der Datenbank erfolgreich war, die Datenbankspalte „DropboxUrl“ jedoch nicht zur Tabelle „Designs“ hinzugefügt wurde.Wenn ich jedoch eine neue Datenbank erstelle, ist die DropboxUrl-Spalte wie erwartet vorhanden.

Frage: Wie könnte ich den Fehler umgehen, dass es in der Datenbank bereits ein Objekt mit dem Namen „Unternehmen“ gibt, während ich „Update-Datenbank“ durchführe, und meine Spalte trotzdem erfolgreich hinzufügen?Es scheint, als ob es ein einfaches Szenario sein sollte, das einfach funktioniert.

Danke.

War es hilfreich?

Lösung

Als Sie die Methoden „Up()“ und „Down()“ bei der Migration auskommentiert haben, haben Sie den Code zum Hinzufügen der Datenbankspalte entfernt.

Sie sollten Up() und Down() für Ihre Initiale wie folgt ändern:

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

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

Damit Entity Framework dies in Zukunft für Sie herausfinden kann, müssen Sie eine Erstmigration durchführen, um zu erkennen, dass eine vorhandene Tabelle vorhanden ist bevor Sie die Eigenschaft zum Code hinzufügen.z.B. Add-Migration -force -ignore.

Dann fügen Sie die Spalte hinzu und gehen Add-Migration AddedDropboxUrlColumn, und es werden die Methoden Up() und Down() generiert, wie ich es in einer neuen Migration beschrieben habe.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top