I have an existing table in my database and I want to create some additional tables using the Code First / Fluent API (no matter how you can classify it). Below is my DbContext :
public class MyContext : DbContext { public DbSet<Entity1> Entities1 { get; set; } public DbSet<Entity2> Entties2 { get; set; } public MyContext() : base(@"data source=....;") {} protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer(new MyContextInitializer()); modelBuilder.Conventions.Remove<IncludeMetadataConvention>(); modelBuilder.Configurations.Add(new Entity1Configuration()); modelBuilder.Configurations.Add(new Entity2Configuration()); } }
After addressing some issues here and some blog posts that I found as follows, it was suggested to create non-existent tables:
public class MyContextInitializer : CreateDatabaseIfNotExists<MyContext> { protected override void Seed(MyContext context) { context.Database.ExecuteSqlCommand(_mainTable); context.Database.ExecuteSqlCommand(_relationTable); base.Seed(context); } private readonly string _mainTable=@"create table ..."; private readonly string _relationTable=@"create table ..."; }
But the Seed method in MyContextIntializer not called because the database already exists. If I move the ExecuteSqlCommand statements to the OnModelCreating in MyContext , I get the following error:
The context cannot be used while the model is being created.
What are my other options besides running SQL directly in SQL Management Studio to create tables?
TheVillageIdiot
source share