简体   繁体   中英

LocalDB database on fly for entity framework code first

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM