在运行时创建数据库

编程入门 行业动态 更新时间:2024-10-26 06:29:31
本文介绍了在运行时创建数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

在运行时创建数据库

本文发布于:2023-11-30 21:37:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651545.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!