I have two webapps. Both refer to the same database, with the need to organize migrations from both the App. Both have MigrateDatabaseToLatestVersion configured. When you start with the empty database of the first application, a schema is created, the corresponding entry is added to the __MigrationHistory table, and everything is ok. But when launching the second second application, the migration should make changes to the existing database tables, but the application crashes with an error - "... This table already exists." Moreover, this happens both for tables that have been changed and for tables that have remained unchanged. How to solve this problem?

sample code of the second application:

Global.asax Database.SetInitializer(new SyncContextInitializer()); using (var context = new SyncDataContext()) { context.Database.Initialize(force: true); } public class SyncContextInitializer : MigrateDatabaseToLatestVersion<SyncDataContext, SyncConfiguration> { } public class SyncDataContext : DataContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new IdentityUserLoginMap()); ....... base.OnModelCreating(modelBuilder); } } public sealed class SyncConfiguration : DbMigrationsConfiguration<SyncDataContext> { private readonly bool _pendingMigrations; public SyncConfiguration() { AutomaticMigrationDataLossAllowed = true; AutomaticMigrationsEnabled = true; var migrator = new DbMigrator(this); _pendingMigrations = migrator.GetDatabaseMigrations().Any(); } ...... ..... } 
  • You are from two applications that may be different, want to make migrations to one database? - Denis Bubnov
  • Yes, 2 applications with a common database - 3axap

1 answer 1

The problem is that you create the same table in two different migrations. It will not work.

If two applications use the same table, they must use the same database context.

Take out the entities displayed on the database, the context of the database and the migration of the database to a separate library, and connect it to both applications. Then everything will work the way you want.


Alternatively, do not use shared tables for the two applications.