Reputation: 688
I want Update database by code first migration .for example I have 3 entity in contex and 1 table in database and there is a problem when I run program and get this error:There is already table.
Migration Configuration
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
// AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
}
}
IdentityModel
public ApplicationDbContext() : base("DefaultConnection" )
{
Database.SetInitializer<ApplicationDbContext>(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Migrations.Configuration>());
}
any help ?
Upvotes: 0
Views: 6042
Reputation: 12314
That's a common problem with migrations. When you add a new migration it compares the current code model to the prior code model stored in the prior migration. If this is the first migration it will thus generate code for everything, so sometimes the code will try to add objects that already exist.
To get past this, you can comment out the code in the Up() method of the migration for the items that already exist and then apply the migration (update-database). Now it will correctly generate just the changes moving forward.
To prevent this, you should always generate an initial snapshot of your database without generating any changes:
add-migration MyStartingPoint -IgnoreChanges // ignorechanges flag tells EF to just take snapshot with no code in Up()
Here is a document on how migrations operate "under the hood".
Upvotes: 1
Reputation: 665
Have you tried to use the Add-Migration "migration_name"
before calling update database? Or maybe try to use Update-Database -Force
.
Otherwise, I have found some steps that maybe could be useful:
enable-migrations
command from the Package Manager Console.add-migration
command to create an initial migration.update-database
command to apply the initial migration to your database. This doesn't make any changes to existing objects (because the Up() method contains no code), but it marks the existing database as having been migrated to the initial state.add-migration
command to create a new migration. The code in the Up() method of the new migration will contain only the changes to your object model.update-database
command to apply the changes to your database.Upvotes: 3