Automatic migration for ASP.NET SimpleMembershipProvider

So, I tried using automatic migrations with my new MVC 4 Project, but somehow does not work. I am following this blog step by step.

I added changes to the UserProfile account model ( NotaryCode field):

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

Then I wrote enable-migrations on the package manager console and a configuration class appeared (inherited from DbMigrationsConfiguration<Web.Models.UsersContext> ), then I populate the class as:

 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" }); } 

And then I tried running update-database -verbose , but that would not work. I mean, this is the result:

The database already has an object named "UserProfile".

 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.** 

I know that the object exists. I mean, I'm trying to use automatic migrations to, exactly, modify and run without manually re-creating the database. But for some reason this does not work.

I am looking at the MSDN documentation and have discovered a property:

 AutomaticMigrationDataLossAllowed = true; 

But setting it to true does not change anything. I guess I missed something, but for some reason did not find it. Any idea?

+43
entity-framework-5 asp.net-mvc-4 code-first-migrations ef-migrations
Nov 05 '12 at 18:36
source share
3 answers

update-database -verbose does not work because your model was changed after your data table already exists.

First, make sure there are no changes to the UserProfile class. Then run:

Add-Migration InitialMigrations -IgnoreChanges

This should generate an empty InitialMigration file. Now add any desired changes to the UserProfile class. After adding the changes, run the update command again:

update-database -verbose

Now, automatic migration will be applied, and the table will be modified with your changes.

+127
Nov 09 '12 at 8:56
source share

It looks like it happened here that you turned on migrations and then started the application. By launching the application before using the UpdateDatabase command, EntityFramework created and populated the database, but since the database did not exist when the migration was enabled, it did not create the InitialCreate migration. Migrations still believe that you have an empty database and you want to create all the objects in your model.

What you can try is to either re-enable migrations that will generate an InitialCreate migration that reflects the current state of the database. In this case, I would save the changes you made to the seed method than running the "Enable-Migrations -Force", this should recreate the migration and generate the IntialCreate migration. Then you can refill your seed method and run the UpdateDatabase command.

+6
Nov 07 '12 at 19:38
source share

I had the same and sorted differently. Went to my local db, deleted UserProfile and other tables with foreign key constraints webpages_Membership, webpages_OAuthMembership, webpages_Roles, webpages_UsersInRoles. All this will be recreated when running update-database -verbose.

0
Sep 20 '15 at 10:54
source share



All Articles