EF 4 Code First: with existing tables

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?

+2
ef-code-first
source share
2 answers

Description

I did the same a few months ago.

You can match your model with an existing database. This was told by Scott Guthrie.

I recommend that you use Enity Framework Power Tools to create your models and context from an existing database.

Additional Information

Update

You must install an initializer for DbContext, if you do not, your new Initializer will not be used. Do the following when starting the application.

 Database.SetInitializer<MyContext>(new MyContextInitializer()); 
+1
source share

Are migrations included? If not, this is the likely reason. Fo you have a Migrations folder, is there a configuration file in this folder? What does the constructor look like? Here's how it should look:

  public Configuration() { AutomaticMigrationsEnabled = true; } 
0
source share

All Articles