拥有NHibernate的存储库以及像这样的LINQ查询
var q = from x in SomeIQueryable<SomeEntity> where x.A1 == a1 && x.B1 == b1 select x;
是否有解决方法如何获取此WHERE过滤器并将其应用于“一次性删除”,这似乎只能通过HQL实现:
var cmd = string.Format("delete from SomeEntity where x.A1 = '{0}' and x.B1 = {1}", a1, b1);
session.CreateQuery(cmd).ExecuteUpdate();
答案 0 :(得分:6)
NH LINQ提供程序和条件/查询转换API不支持条件删除/更新。除非您正在考虑扩展NHibernate,否则HQL或原始SQL是唯一的选择。
答案 1 :(得分:4)
现在可以使用Nhibernate 5.0:
session.Query<SomeIQueryable>()
.Where(x => x.A1 == a1 && x.B1 == b1)
.Delete();
文档:
//
// 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);
答案 2 :(得分:1)
目前,从NH 4.0.1开始,这是不可能的。然而,Jira有一个未解决的问题(NH-3659,https://nhibernate.jira.com/browse/NH-3659)。有一个基于http://weblogs.asp.net/ricardoperes/strongly-typed-delete-with-nhibernate描述的自定义拦截器和SQL替换的hackish解决方案,但我正在研究一个干净的解决方案,并最终将提交一个拉取请求。
答案 3 :(得分:0)
(from x in NHSession.Query<SomeEntity>()
where x.A1 == a1 && x.B1 == b1
select x).ForEach(y => { NHSession.Delete(y) });
NHSession.Flush();