Reputation: 55
I have problem related to Entity Framework 6, migrations and context.
I have created DbMigration like this:
public override void Up()
{
CreateTable(
"dbo.Settings",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
Value = c.String(),
})
.PrimaryKey(t => t.Id);
Sql("SET IDENTITY_INSERT[dbo].[Settings] ON");
Sql("INSERT[dbo].[Settings]([Id], [Name], [Value]) VALUES(1, N'Name1', N'Value1')");
Sql("INSERT[dbo].[Settings]([Id], [Name], [Value]) VALUES(2, N'Name2', N'Value2')");
Sql("SET IDENTITY_INSERT[dbo].[Settings] OFF");
}
In configuration I have
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(MyContext context)
{
}
and DbContext
public MyContext() :
base(connectionString)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration>());
}
Every time when I perform any operation on context, such as:
var ctx = container.Resolve<IMyContext>() as MyContext;
ctx?.Database.Initialize(false);
or I access it by a DbSet
:
DbSet<Settings> Set => this._Context.Set<Settings>();
var setting = this.Set.FirstOrDefault();
I get an exception:
System.Data.SqlClient.SqlException: 'There is already an object named 'Settings' in the database.'
After changing configuration to
AutomaticMigrationsEnabled = true;
the exception becomes:
System.Data.Entity.Migrations.Infrastructure.AutomaticMigrationsDisabledException: 'Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.'
I have tried other advice with adding empty migration: Initial, without any success.
Somehow, accessing context tries to re-create this table (and others). Did I miss something in the settings ? After several hours I'm stuck.
Thank you
Upvotes: 0
Views: 46