linqからnhibernateバルクアップデートクエリに相当しますか?
-
22-09-2019 - |
質問
ここで何かが足りないかどうかはわかりません。基本的に、私は次のSQLステートメントを行うために、linqからnhibernateを探しています。
update SomeTable
set SomeInteger = (SomeInteger + 1)
where SomeInteger > @NotSoMagicNumber
それをする方法はありますか?
ありがとう!
解決
linq(linqからnhibernate、linq全般)には、SQLのようなバルクアップデート動詞はありません。あなたのようなバルクアップデートステートメントの効率が必要な場合は、SQLに固執するだけです。
他のヒント
遅い回答ですが、現在は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);
あなたの場合:
session.Query<SomeObject>()
.Update(i => new SomeObject { SomeInteger = i.SomeInteger + 1 });
Nhibernateチームに感謝します!
ほとんどの(すべてではないにしても)LINQプロバイダーと同様に、LINQからNhibernateからNhibernateは、データを読むのにのみ役立ちます。
Linqの助けを借りてNhibernateでやりたいことを達成するには、関連するすべてのオブジェクトを取得し、それぞれを更新する必要があります。何かのようなもの:
//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
またはセッションをフラッシュします。
所属していません StackOverflow