Automatyczne migracje dla ASP.NET SimpleMembershipProvider

Więc próbowałem użyć automatycznych migracji z moim nowym projektem MVC 4, ale jakoś to nie działa. I śledziłem ten wpis na blogu krok po kroku.

Dodałem zmiany do modelu konta UserProfile (pole NotaryCode):

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int NotaryCode { get; set; }
}

Potem napisałem na konsoli Menedżera pakietów enable-migrations i pojawiła się Klasa konfiguracyjna (dziedziczy z DbMigrationsConfiguration<Web.Models.UsersContext>) Następnie wypełniłem klasę jako:

public Configuration()
{
    AutomaticMigrationsEnabled = true;
}

protected override void Seed(Atomic.Vesper.Cloud.Web.Models.UsersContext context)
{
    WebSecurity.InitializeDatabaseConnection(
            "DefaultConnection",
            "UserProfile",
            "UserId",
            "UserName", autoCreateTables: true);

    if (!Roles.RoleExists("Atomic"))
        Roles.CreateRole("Atomic");

    if (!Roles.RoleExists("Protocolista"))
        Roles.CreateRole("Protocolista");

    if (!Roles.RoleExists("Cliente"))
        Roles.CreateRole("Cliente");

    string adminUser = "randolf";

    if (!WebSecurity.UserExists(adminUser))
        WebSecurity.CreateUserAndAccount(
            adminUser,
            "12345",
            new { NotaryCode = -1 });

    if (!Roles.GetRolesForUser(adminUser).Contains("Atomic"))
        Roles.AddUsersToRoles(new[] { adminUser }, new[] { "Atomic" });
}

A potem próbowałem uciec update-database -verbose ale to nie działa. To jest wyjście:

Istnieje już obiekt o nazwie 'UserProfile' w bazie danych.

PM> update-database -verbose
Using StartUp project 'Web'.
Using NuGet project 'Web'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'VesperCloud' (DataSource: .\SQLSERVER, Provider: System.Data.SqlClient, Origin: Configuration).
No pending code-based migrations.
Applying automatic migration: 201211051825098_AutomaticMigration.
CREATE TABLE [dbo].[UserProfile] (
    [UserId] [int] NOT NULL IDENTITY,
    [UserName] [nvarchar](max),
    [NotaryCode] [int] NOT NULL,
    CONSTRAINT [PK_dbo.UserProfile] PRIMARY KEY ([UserId])
)
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'UserProfile' 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.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
   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:a7da0ddb-bccf-490f-bc1e-ecd2eb4eab04
**There is already an object named 'UserProfile' in the database.**
Wiem, że obiekt istnieje. Staram się używać automatycznych migracji, aby precyzyjnie modyfikować i uruchamiać bez ręcznego odtwarzania DB. Ale jakoś to nie działa.

Przejrzałem dokumentację MSDN i znalazłem właściwość:

AutomaticMigrationDataLossAllowed = true;
Ale ustawienie na true niczego nie zmienia. Chyba czegoś mi brakuje, ale jakoś nie znajduję czego. Jakiś pomysł?
Author: Pete, 2012-11-05

3 answers

update-database -verbose nie działa, ponieważ model został zmieniony po tym, jak Tabela danych już istniała.

Najpierw upewnij się, że nie ma żadnych zmian w klasie UserProfile. Następnie uruchom:

Add-Migration InitialMigrations -IgnoreChanges

Powinno to wygenerować pusty plik "InitialMigration". Teraz dodaj wszelkie pożądane zmiany do klasy UserProfile. Po dodaniu zmian uruchom ponownie polecenie update:

update-database -verbose

Teraz zostanie zastosowana automatyczna migracja i tabela zostanie zmieniona Twoim zmiany.

 127
Author: Haminh Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-14 18:08:46

Wygląda na to, że włączyłeś Migracje, a następnie uruchomiłeś aplikację. Uruchamiając aplikację przed użyciem polecenia UpdateDatabase, EntityFramework utworzyłby i wypełnił bazę danych, ale od momentu włączenia migracji baza danych nie istniała, nie utworzyła migracji inicjalnej. Migracje nadal myślą, że masz pustą bazę danych i chcą utworzyć wszystkie obiekty w modelu

Możesz spróbować albo ponownie włącz migracje, które wygenerują migrację inicjalną, która odzwierciedla bieżący stan bazy danych. W tym przypadku chciałbym zapisać zmiany wprowadzone do metody seed niż uruchomić "Enable-Migrations-Force", to powinno odtworzyć migrację i wygenerować migrację IntialCreate. Następnie możesz ponownie zaludnić swoją metodę zalążkową i uruchomić polecenie UpdateDatabase.

 6
Author: lukew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-07 19:38:46

Miałem to samo i posortowane w inny sposób. Udał się do mojego lokalnego db usunięte UserProfile i inne tabele z ograniczeniami klucza obcego webpages_Membership, webpages_OAuthMembership, webpages_Roles, webpages_usersinroles tabele. Wszystko to zostanie odtworzone po uruchomieniu update-database-verbose.

 0
Author: Chamilgreat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-20 10:54:39