LocalDB database on fly for entity framework code first

LoxLox picture LoxLox · Mar 14, 2014 · Viewed 9.6k times · Source

is possible to create an mdf file on fly (at runtime) and use it with entity framework 6 in a code first approach?

I need something like this:

if (mydb.mdf not exists)
    createmdf();

mycontext ctx = new mycontext(mydb.mdf connection string)
ctx.CreateDatabase();

Thank you

Answer

Wahid Bitar picture Wahid Bitar · Mar 14, 2014

Try this

context.Database.CreateIfNotExists();

You could do something like this in your context constructor

public YourDBContext(): base("YourDBConnectionString") 
{
    Database.SetInitializer<YourDBContext>(new CreateDatabaseIfNotExists<YourDBContext>());
    //Database.SetInitializer<YourDBContext>(new DropCreateDatabaseIfModelChanges<YourDBContext>());
}

This will use your connection string in the web.config file and try to find the database. If the database doesn't exist then it will create it according to the model that you defined.

Update :

Please look at this answer too