Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 626
LoxLox Avatar asked Mar 13 '14 23:03

LoxLox


People also ask

How do I import data from a database into Entity Framework?

Select Data from the left menu and then ADO.NET Entity Data Model Select the connection to the database you created in the first section and click Next Click the checkbox next to Tables to import all tables and click Finish

How to create an Entity Framework data model in Visual Studio?

We will use the Entity Framework Tools for Visual Studio to help us generate some initial code to map to the database. These tools are just generating code that you could also type by hand if you prefer. Project -> Add New Item… Select Data from the left menu and then ADO.NET Entity Data Model

How to use code first classes to create entity diagrams?

Using code first classes to create entity diagrams Assuming your schema has been created from the Code First classes you can reverse the db into a an edmx to visualise the Model. Any classes generated from this obviously won't be related to your Code First classes though. code-firstentity-framework asked by Darren Lewis

Can code first create an empty database?

This scenario includes targeting a database that doesn’t exist and Code First will create, or an empty database that Code First will add new tables to. Code First allows you to define your model using C# or VB.Net classes.


1 Answers

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

like image 57
Wahid Bitar Avatar answered Sep 19 '22 20:09

Wahid Bitar