Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to delete all rows in a table using NHibernate?
    primarykey
    data
    text
    <p>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?</p> <p>I have considered writing a stored proc that runs "delete from <em>tablename</em>;" 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.</p> <p>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.</p> <p>Any ideas?</p> <p>Thanks /Erik</p> <p><strong>UPDATE:</strong></p> <p>Since this question was asked and answered, progress has been made by the NHibernate team. As Ayende explains in <a href="http://ayende.com/Blog/archive/2009/05/28/nhibernate-ndash-executable-dml.aspx" rel="noreferrer">this blog post</a>, you can now execute DML queries directly, without NHibernate having to fetch any entities.</p> <p>To delete all Foo objects you could do like this:</p> <pre><code>using (ISession session = ...) using (ITransaction transaction = session.BeginTransaction()) { session.CreateQuery("delete Foo f").ExecuteUpdate(); transaction.Commit(); } </code></pre> <p>This query would generate the following SQL:</p> <pre><code>delete from Foo </code></pre> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload