问题
I have an existing table in my database and I want to create some additional tables using Code First/Fluent API (whatever way you may want to categorize it). Following 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 going through some questions here and some blog-posts I found following way suggested to create non-existing 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
is not called may be database already exists. If I move ExecuteSqlCommand
statements to OnModelCreating
statement in MyContext
I get following error:
The context cannot be used while the model is being created.
What are my other options than running SQL directly in SQL Management Studio to create tables?
回答1:
Description
I have done the same a few months ago.
You can map your Model to an existing Database. Scott Guthrie has blogged about it.
I encourage you to use the Enity Framework Power Tools to create your models and context from your existing Database.
More Information
- Using EF “Code First” with an Existing Database
- Entity Framework Power Tools CTP1
Update
You must set the initializer for the DbContext, if you don't do that your new Initializer will not used. Do the following on Application start.
Database.SetInitializer<MyContext>(new MyContextInitializer());
回答2:
Have you enabled migrations? If not, that is the likely reason. Fo you have a Migrations folder, does that folder have a Configuration file? What does the constructor look like? Here what it should look like:
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
来源:https://stackoverflow.com/questions/8908941/ef-4-code-first-with-existing-tables