问题描述
为了使集成测试独立,我将删除所有旧数据,并在每次测试之前插入新的测试数据.除了简单地查询所有实体并一一删除它们,还有更好的方法吗?
To keep my integration tests independent I remove all old data and insert new test data before each test. Is there a better way of doing this than simply querying for all entities and deleting them one by one?
我考虑过编写一个存储过程,该过程运行从表名删除";对于要清除的每个表.这样做应该会更快一些,但最好不要执行SQL查询或通过NH调用SP.
I have considered writing a stored proc that runs "delete from tablename;" for each table that is to be cleared. That ought to quite a bit faster, but it would be nice to do it without doing SQL queries or calling SPs via NH.
我正在将香草NHibernate和Linq用于NHibernate.我相信Castle Active Record具有类似Foo.DeleteAll()的功能,但是我不想在该项目中使用Active Record.
I'm using vanilla NHibernate and Linq to NHibernate. I beleive Castle Active Record has something like Foo.DeleteAll(), but I don't want to use Active Record for this project.
有什么想法吗?
感谢/Erik
更新:
自从这个问题被回答后,NHibernate团队取得了进展.正如Ayende在此博客文章中所述的那样,您现在可以直接执行DML查询,而NHibernate不必获取任何实体.
Since this question was asked and answered, progress has been made by the NHibernate team. As Ayende explains in this blog post, you can now execute DML queries directly, without NHibernate having to fetch any entities.
要删除所有Foo对象,您可以这样操作:
To delete all Foo objects you could do like this:
using (ISession session = ...)
using (ITransaction transaction = session.BeginTransaction())
{
session.CreateQuery("delete Foo f").ExecuteUpdate();
transaction.Commit();
}
此查询将生成以下SQL:
This query would generate the following SQL:
delete from Foo
比先获取实体然后删除它们要快得多.不过请小心,因为此类查询不会影响1级缓存.
which aught to be significantly faster than fetching the entities first and then deleting them. Be careful though, since queries like these do not affect the level 1 cache.
推荐答案
在我的UnitTest的TearDown中,我主要是这样做的:
In the TearDown of my UnitTests, I mostly do this:
using( ISession s = ... )
{
s.Delete ("from Object o");
s.Flush();
}
这应删除所有实体.如果要删除一个特定实体的所有实例,可以执行以下操作:
This should delete all entities.If you want to delete all instances of one specific entity, you can do this:
using( ISession s = .... )
{
s.Delete ("from MyEntityName e");
s.Flush();
}
当然,此方法有一个缺点,那就是NHibernate将先获取实体,然后再删除它们.
Offcourse, there's a drawback with this method, and that is that NHibernate will first fetch the entities before deleting them.
这篇关于使用NHibernate删除表中所有行的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!