Garth Marenghi Garth Marenghi - 13 days ago 7
C# Question

DropCreateDatabaseIfModelChanges when EF is another project

I have separated my solution in separate projects, a DAL project with entity framework and an ASP.NET MVC project.

I want to use

DropCreateDatabaseIfModelChanges
, but I don't know where to put it to make it work.

I've tried to put it in the web.config of the MVC project and the app.config of the DAL project (both by making use of the context element), I've tried putting it in the global.asax (
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<BreakAwayContext>());
), I've tried a custom initialization class, but none of these seem to work.

If possible, I don't want to make use of migrations. How can I make it work?

Answer

You could create a class to implement CreateDatabaseIfNotExists and call Database.SetInitializer function in Application_Start().

-DbInitializer

public class MyDbInitializer : CreateDatabaseIfNotExists<MyDbContext>
{
    protected override void Seed(MyDbContext context)
    {
        //Data initializing...
    }
}

-Application_Start

protected void Application_Start() 
{ 
   Database.SetInitializer(new MyDbInitializer());
}

The database will be create when running the application.

And if you would like to do a automatic migration of database, use MigrateDatabaseToLatestVersion class

public class Configuration :  DbMigrationsConfiguration<MyDbContext>
{
    public Configuration()
    {
        this.AutomaticMigrationsEnabled = true;            
    }

}

-Application_Start

Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext,Configuration>());

Howerver, I recomand that using migraion commands will be more flexible. See this walkthru: Overview of Entity Framework Code First Migrations with example, by Bhavik Patel.

Comments