Where should SetInitializer be placed in Entity Framework CTP4?

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

Question

I am attempting to add Entity Framework, code first, to an MVC application that's been running with test data, using the CTP4 preview.

I am currently getting this error:

The model backing the 'SchedulerContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

I do not want to generate a database at all, as I already have a database. So I tried adding the following to the SchedulerContext constructor:

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

which had no effect at all -- I got the same error the next time it ran. The error seems to occur when it is executing a LINQ statement that accesses the database -- the first, I think.

Where should I put this statement, or is this statement the answer to this problem at all?

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

Accepted Answer

Update

I simply glossed over the fact you already have a database and don't want to create another one...in that case the answer is to put this in your SchedulerContext class

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

Old answer

You usually put it in the Global.asax

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

Note that it will only be initialized on first use of the data context.

Update

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

Then you modify the SetInitializer like so.

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

Popular Answer

Btw, as of CTP5, this is the proper way of setting the initializer in Global.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