简体   繁体   English

回滚对Entity Framework .NET中的数据库所做的更改

[英]Rollback changes made to Database in Entity Framework .NET

I am writing unit test cases for testing a framework. 我正在编写用于测试框架的单元测试用例。 The unit test adds and modifies the data in an existing database. 单元测试添加并修​​改现有数据库中的数据。 I need to rollback all the changes done to database after a test finishes, ie delete the rows added and revert the rows modified. 我需要在测试完成后回滚对数据库所做的所有更改,即删除添加的行并还原修改的行。

I am using Entity Framework 6 for accessing the database. 我正在使用Entity Framework 6来访问数据库。 The underlying database is SQL Server. 底层数据库是SQL Server。 Is there any support provided by EF6 to achieve this? EF6是否有任何支持来实现这一目标?

Presently I am storing the changes in a list and I refer the this list for cleaning up the database. 目前我将更改存储在列表中,我将此列表用于清理数据库。 But using this approach leaves some residue randomly. 但是使用这种方法会随机留下一些残留物 I am not sure of the reason though, maybe some race condition or something. 我不确定原因,可能是一些竞争条件或其他原因。

Looking for some minimal and smart alternative for it. 寻找一些最小和聪明的替代品。 Thanks in advance :) 提前致谢 :)

you can wrap your test in a transaction and don't commit changes: 您可以将测试包装在事务中,而不是提交更改:

using (TransactionScope scope = new TransactionScope()) {
    //do your stuff
}

But for unit testing propouses you can use Effort - Entity Framework Unit Testing Tool which provide in-memory database operations. 但对于单元测试专家,您可以使用Effort - Entity Framework Unit Testing Tool来提供内存数据库操作。

EDITED to reply last comments 已编辑回复最新评论

You can use an overloaded TransactionScope contructor to control the IsolationLevel , so you can choose to read uncommited changes or not. 您可以使用重载的TransactionScope构造函数来控制IsolationLevel ,以便您可以选择是否读取未更改的更改。

If your proxy isn't inside the Transaction, please, check that the connection string is the same , so ado.net can identify the connection and enlist the connection in the same transaction. 如果您的代理不在交易中,请检查连接字符串是否相同 ,以便ado.net可以识别连接并在同一事务中登记连接。 If the connection string is not the same, you probably will need to activate the Distributed Transaction Coordinator. 如果连接字符串不相同,则可能需要激活分布式事务处理协调器。 Here you have an explanation how DTC scalation occurs: TransactionScope automatically escalating to MSDTC on some machines? 在这里你可以解释DTC scalation是如何发生的: TransactionScope会在某些机器上自动升级到MSDTC吗?

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

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