在运行时创建数据库 [英] Creating a db in runtime

查看:118
本文介绍了在运行时创建数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到现在,我已经使用这个代码动态地创建了一个数据库:

Untill now I have used this code for creating a db dynamically:

var db = new MyEntities(db_name);
if (!db.DatabaseExists()) 
{
    db.CreateDatabase();

其中MyEntities扩展了ObjectContext类。

where MyEntities extends the ObjectContext class.

在我的新应用程序中,我有相同的代码,但现在MyEntities扩展了DbContext类,并且DatabaseExists()和CreateDatabase()不可用。

In my new application I have the same code, but now MyEntities extends the DbContext class and the DatabaseExists() and CreateDatabase() are not available.

如何创建一个db现在?

How can I create a db now?

推荐答案

所以下面的代码将执行一个不同的状态来创建数据库,我相信它会运行一个 DbContext 被击中。所以喜欢 using(var context = new DbContext())

So the below code will execute a different stategy for creating a database, I believe it will run when a DbContext gets hit. so like using (var context = new DbContext())

Database.SetInitializer(new DropCreateDatabaseAlways<DbContext>());
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContext>());
Database.SetInitializer(new CreateDatabaseIfNotExists<DbContext>());

这些都很自我解释。你甚至可以覆盖它们,以便您可以添加种子数据。

These are pretty self explanatory. You can even override them so that you can add Seed data.

将其放在您的 Global.asax

如你所见,这些是强类型的类。他们拿你继承的 DbContext 类。

As you can see, these are strongly typed classes. They take your inherited DbContext class.

所以例如:

public class BlogContext : DbContext {}

Database.SetInitializer(new DropCreateDatabaseAlways<BlogContext>());

上面的代码将删除并创建数据库,始终使用 BlogContext 作为参考。

That above code will drop and create the database always using the BlogContext as a reference.

这篇关于在运行时创建数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆