Linq to Nhibernate Bulk Update Query Equivalent?

Not sure if something is missing here. Basically, I'm looking for Linq for Nhibernate to execute the following SQL statement:

update SomeTable
set SomeInteger = (SomeInteger + 1)
where SomeInteger > @NotSoMagicNumber

Is there any way to do this?

Thank!

+3
source share
3 answers

Linq (not Linq to NHibernate, Linq in general) does not have a bulk update verb, such as SQL. If you need the efficiency of a massive update statement like yours, I would just stick with SQL.

+1
source

Like most (if not all) LINQ providers, LINQ to NHibernate comes in handy when reading data.

, NHibernate LINQ, . - :

//NHibernate session initialisation & finalisation skipped for brevity

var relevantObjects = from i in session.Linq<SomeObject>()
                      where i.SomeInteger > notSoMagicNumber
                      select i;

foreach (SomeObject item in relevantObjects)
{
    i.SomeInteger++;
    session.Update(item);
}

, , .

, NHibernate . IStatelessSession , .

, , session.Update .

+1

Late answer, but it now exists in Nhibernate 5.0.

    //
    // Summary:
    //     Update all entities selected by the specified query. The update operation is
    //     performed in the database without reading the entities out of it.
    //
    // Parameters:
    //   source:
    //     The query matching the entities to update.
    //
    //   expression:
    //     The update setters expressed as a member initialization of updated entities,
    //     e.g. x => new Dog { Name = x.Name, Age = x.Age + 5 }. Unset members are ignored
    //     and left untouched.
    //
    // Type parameters:
    //   TSource:
    //     The type of the elements of source.
    //
    // Returns:
    //     The number of updated entities.
    public static int Update<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, TSource>> expression);

In your case:

    session.Query<SomeObject>()
            .Update(i => new SomeObject { SomeInteger = i.SomeInteger + 1 });

Thanks to the NHibernate Team!

+1
source

Source: https://habr.com/ru/post/1729492/


All Articles