Where should SetInitializer be placed in Entity Framework CTP4?

.net asp.net-mvc-2 c# entity-framework

Question

I'm trying to use the CTP4 preview to add Entity Framework, code first, to an MVC application that has been running with test data.

Right now I'm receiving the following error:

Since the database's creation, the model that supports the "SchedulerContext" context has changed. Call Database or manually delete/update the database. SetInitializer using an instance of IDatabaseInitializer. For instance, the RecreateDatabaseIfModelChanges strategy will automatically delete, rebuild, and, if desired, seed the database with fresh information.

Since I already have a database, I have no desire to create another. So I tried include the following in the constructor for the SchedulerContext:

Database.SetInitializer<SchedulerContext>(new CreateDatabaseOnlyIfNotExists<SchedulerContext>());

It had no impact at all; the next time it ran, I had the identical issue. The first, I believe, LINQ statement that contacts the database seems to be where the fault manifests itself.

Is this phrase indeed the solution to this issue, or where should I place it?

1
6
4/10/2013 9:06:49 PM

Accepted Answer

Update

I just ignored the fact that you currently have a database and wish to build a new one; in that case, adding this to your SchedulerContext class would be the appropriate solution.

protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {
    modelBuilder.IncludeMetadataInDatabase = false;
}

old response

Typically, you place it in the Global. asax

protected void Application_Start() {
    Database.SetInitializer<SchedulerContext>(new CreateDatabaseOnlyIfNotExists<SchedulerContext>());
}

Remember that it won't be initialized until the data context is used for the first time.

Update

public class DataContextInitializer : CreateDatabaseOnlyIfNotExists<SchedulerContext> {
    protected override void Seed(SchedulerContext context) {
    }
}

The SetInitializer is then modified as before.

System.Data.Entity.Infrastructure.Database.SetInitializer<SchedulerContext>(new  DataContextInitializer());
9
9/9/2010 5:04:38 PM

Popular Answer

By the way, using this method to set the initializer in Global is correct as of CTP5. asax

protected void Application_Start() { System.Data.Entity.Database.DbDatabase.SetInitializer<NerdDinners>(new System.Data.Entity.Database.DropCreateDatabaseIfModelChanges<NerdDinners>()); }



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow