Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 565
kastanf Avatar asked Aug 11 '11 19:08

kastanf


3 Answers

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);
like image 129
Sÿl Avatar answered Oct 19 '22 01:10

Sÿl


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.

like image 28
Dmitry S. Avatar answered Oct 19 '22 02:10

Dmitry S.


(from x in NHSession.Query<SomeEntity>()
                  where x.A1 == a1 && x.B1 == b1 
                  select x).ForEach(y => { NHSession.Delete(y) });
        NHSession.Flush();
like image 33
Paul Aicher Avatar answered Oct 19 '22 01:10

Paul Aicher