Entity Framework Code First Many to Many Setup For Existing Tables

Remove your Essence2EssenceSet model class. If junction table contains only keys of related entities participating in many-to-many relations it is not needed to map it as entity. Also make sure that your fluent mapping of many-to-many relations specifies schema for table: mb.Entity<Essence>() .HasMany(e => e.EssenceSets) .WithMany(set => set.Essences) .Map(mc => { mc.ToTable(“Essence2EssenceSet”, “Com”); mc.MapLeftKey(“EssenceID”); mc.MapRightKey(“EssenceSetID”); … Read more

Change foreign key constraint naming convention

You can implement a custom sql generator class derived from SqlServerMigrationSqlGenerator from System.Data.Entity.SqlServer namespace: public class CustomSqlGenerator : SqlServerMigrationSqlGenerator { protected override void Generate(AddForeignKeyOperation addForeignKeyOperation) { addForeignKeyOperation.Name = getFkName(addForeignKeyOperation.PrincipalTable, addForeignKeyOperation.DependentTable, addForeignKeyOperation.DependentColumns.ToArray()); base.Generate(addForeignKeyOperation); } protected override void Generate(DropForeignKeyOperation dropForeignKeyOperation) { dropForeignKeyOperation.Name = getFkName(dropForeignKeyOperation.PrincipalTable, dropForeignKeyOperation.DependentTable, dropForeignKeyOperation.DependentColumns.ToArray()); base.Generate(dropForeignKeyOperation); } private static string getFkName(string primaryKeyTable, string foreignKeyTable, params string[] … Read more

How do I remove underscore of foreign key fields in code first by convention

I finally found an answer for this, by writing a custom convention. This convention works in EF 6.0 RC1 (code from last week), so I think it’s likely to continue to work after EF 6.0 is released. With this approach, the standard EF conventions identify the independent associations (IAs), and then create the EdmProperty for … Read more

How do I use Entity Framework in Code First Drop-Create mode?

Use DropCreateDatabaseAlways initializer for your database. It will always recreate database during first usage of context in app domain: Database.SetInitializer(new DropCreateDatabaseAlways<YourContextName>()); Actually if you want to seed your database, then create your own initializer, which will be inherited from DropCreateDatabaseAlways: public class MyInitializer : DropCreateDatabaseAlways<YourContextName> { protected override void Seed(MagnateContext context) { // seed database … Read more

Entity Framework Database.SetInitializer simply not working

The database will only be created when you actually use the context. If you have overridden the Seed method in your initializer as follows: protected override void Seed(MyContext context){…} The Seed code will only run when you use an instance of MyContext. That is why it works when you use var ctx = new MyContext(); … Read more