简体   繁体   English

首先是实体框架代码的LocalDB数据库

[英]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? 是否可以在运行中创建一个mdf文件(在运行时)并在代码优先方法中将它与实体框架6一起使用?

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. 这将使用web.config文件中的连接字符串并尝试查找数据库。 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 请看这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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