简体   繁体   中英

NHibernate efficient Delete using LINQ Where condition

Having a repository for NHibernate with LINQ queries like this

var q = from x in SomeIQueryable<SomeEntity> where x.A1 == a1 && x.B1 == b1 select x;

Is there a solution how to get this WHERE filter and apply it for "one-shot-delete" which seems to be only possible through HQL:

var cmd = string.Format("delete from SomeEntity where x.A1 = '{0}' and x.B1 = {1}", a1, b1);
session.CreateQuery(cmd).ExecuteUpdate();

It is now possible with Nhibernate 5.0:

session.Query<SomeIQueryable>()
            .Where(x => x.A1 == a1 && x.B1 == b1)
            .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);

NH LINQ provider and the criteria/queryover API do not support conditional deletes/updates. HQL or raw SQL are the only options unless you are looking into extending NHibernate.

Currently, as of NH 4.0.1, it is not possible. There is, however, an open issue at Jira (NH-3659, https://nhibernate.jira.com/browse/NH-3659 ). There is an hackish solution based on a custom interceptor and SQL replacement described at http://weblogs.asp.net/ricardoperes/strongly-typed-delete-with-nhibernate , but I am working on a clean solution and will eventually submit a pull request.

(from x in NHSession.Query<SomeEntity>()
                  where x.A1 == a1 && x.B1 == b1 
                  select x).ForEach(y => { NHSession.Delete(y) });
        NHSession.Flush();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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