EF-CTP4和单元测试问题(每次测试前重新启动数据库) [英] Problem with EF - CTP4 and Unittesting ( Re-Init databasebefore each test )

查看:77
本文介绍了EF-CTP4和单元测试问题(每次测试前重新启动数据库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 

在每个Unittest之前我想要重新创建数据库(已将初始化程序设置为"AlwaysRecreate" ;)像这样:

before each Unittest i want to recreate the database ( have set the initializer to "AlwaysRecreate" ) like this:


    [TestInitialize()]
    public void TestPreRun()
    {<br/>
       Model.Database.DeleteIfExists();
      Model.Database.CreateIfNotExists();
      Model.Database.Initialize();
      Model.Database.EnsureInitialized();
      Model = new MyDbContext();
    }

推荐答案

da.ri,

da.ri,

如果要在每次测试之前重新创建数据库(顺便说一句,可能会很慢)并且您有AlwaysRecreate初始化程序,那么您需要做的就是在每次测试之前调用context.Database.Initialize() 。试验&NBSP;这将执行
数据库删除和创建,如果您从初始化程序类派生并提供和实现种子,则将调用Seed方法。 请注意,Initialize()和EnsureInitialized()之间的区别在于Initialize()
总是运行初始化程序,即使它之前已经运行过,而EnsureInitialized只运行初始化程序,因为尚未为数据库运行它在当前的应用域中。

If you want to recreate the database before every test (which, by the way, will likely be quite slow) and you have the AlwaysRecreate initializer, then all you need to do is call context.Database.Initialize() before each test.  This will do the database deletion and creation, and will call the Seed method if you have derived from the initializer class and provided and implementation of Seed.  Note that the difference between Initialize() and EnsureInitialized() is that Initialize() always runs your initializer, even if it has been run before, whereas EnsureInitialized only runs the initializer is it has not yet been run for the database in the current app domain.

话虽如此,您看到的例外可能与以上任何内容无关。 如消息所示,此异常通常是因为您在保存后在上下文中存在冲突的主键。 如果您发布代码,您有
将对象放入上下文并保存它们,那么可能更容易找出您获得此异常的原因。

That being said, the exception you are seeing is probably not related to any of the above.  As the message says, this exception usually happens because you have conflicting primary keys in your context after saving.  If you post the code you have that puts objects into the context and saves them, then it might be easier to figure out why you are getting this exception.

谢谢,

Arthur

Thanks,
Arthur


这篇关于EF-CTP4和单元测试问题(每次测试前重新启动数据库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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