LocalDB database on the fly for entity infrastructure code

can I create an mdf file on the fly (at runtime) and use it with entity 6 infrastructure in the first approach to the code?

I need something like this:

if (mydb.mdf not exists) createmdf(); mycontext ctx = new mycontext(mydb.mdf connection string) ctx.CreateDatabase(); 

thanks

+7
c # entity-framework localdb
source share
1 answer

try it

 context.Database.CreateIfNotExists(); 

You can 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 and try to find the database. If the database does not exist, it will create it according to your chosen model.

Update:

Please see this answer too

+7
source share

All Articles