Create模式中使用Entity

Create模式中使用Entity

本文介绍了如何在Code First Drop-Create模式中使用Entity Framework?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework v4。我已按照。我目前处于开发模式(未发布到任何更高的环境),并希望在每个新部署中重新创建表,因为模型仍然高度易失,并且我不在乎保留数据。但是,这不会发生。表不会创建/修改,也不会发生在DB上。如果我通过使用包管理器命令移动到迁移模型:enable-migrations,add-migration(初始),这可以使用和使用我的迁移。但是,由于我不想进行粒度迁移,只需要我的初始创建脚本,因此我不得不删除迁移文件夹,重新启动命令(enable-migrations,add-migration)并手动删除数据库我修改任何东西。

I'm using Entity Framework v4. I have followed the instructions in the Nerd Dinner tutorial. I'm currently in development mode (not released to any higher environments) and would like for tables to be recreated on each new deployment, since the models are still highly volatile and I don't care to retain data. However, this does not occur. Tables are not created/modified, or anything happening to the DB. If I move to a migrations model by using the Package Manager commands: enable-migrations, add-migration (initial), this works and uses my migrations. However, since I don't yet want to have granular migrations and only want my initial create script, I am forced to delete the migrations folder, redo the commands (enable-migrations, add-migration) and delete the database manually, every time I change anything.

我如何首先发现代码的丢弃/创建行为?

How do I get the drop/create behavior of code first to occur?

推荐答案

使用您的数据库的初始化程序。在应用程序域的上下文首次使用期间,它将始终重新创建数据库:

Use DropCreateDatabaseAlways initializer for your database. It will always recreate database during first usage of context in app domain:

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

实际上,如果要种数据库,请创建自己的初始化程序,它将继承自 DropCreateDatabaseAlways

Actually if you want to seed your database, then create your own initializer, which will be inherited from DropCreateDatabaseAlways:

public class MyInitializer : DropCreateDatabaseAlways<YourContextName>
{
     protected override void Seed(MagnateContext context)
     {
         // seed database here
     }
}

在首次使用上下文之前设置它

And set it before first usage of context

Database.SetInitializer(new MyInitializer());

这篇关于如何在Code First Drop-Create模式中使用Entity Framework?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 22:31