Best way to delete all rows in a table using NHibernate?

不想你离开。 提交于 2019-11-29 22:13:06

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();
}

Offcourse, there's a drawback with this method, and that is that NHibernate will first fetch the entities before deleting them.

I use Fluent Nhibernate attributes so I modify code a little in order not to hardcore table names

private static void CleanUpTable<T>(ISessionFactory sessionFactory)
{
    var metadata = sessionFactory.GetClassMetadata(typeof(T)) as NHibernate.Persister.Entity.AbstractEntityPersister;
    string table = metadata.TableName;

    using (ISession session = sessionFactory.OpenSession())
    {
        using (var transaction = session.BeginTransaction())
        {
            string deleteAll = string.Format("DELETE FROM \"{0}\"", table);
            session.CreateSQLQuery(deleteAll).ExecuteUpdate();

            transaction.Commit();
        }
    }
}

usage

CleanUpTable<Person>(sessionFactory);

With NHibernate 5.0 you can now simply do:

session.Query<Foo>().Delete();

Documentation:

    //
    // Summary:
    //     Delete all entities selected by the specified query. The delete operation is
    //     performed in the database without reading the entities out of it.
    //
    // Parameters:
    //   source:
    //     The query matching the entities to delete.
    //
    // Type parameters:
    //   TSource:
    //     The type of the elements of source.
    //
    // Returns:
    //     The number of deleted entities.
    public static int Delete<TSource>(this IQueryable<TSource> source);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!