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
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
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
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With