繁体   English   中英

NHibernate 高效删除使用 LINQ where 条件

[英]NHibernate efficient Delete using LINQ Where condition

拥有 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();

现在可以使用 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);

NH LINQ 提供程序和 API 的条件/查询不支持条件删除/更新。 HQL 或原始 SQL 是唯一的选择,除非您正在考虑扩展 NHibernate。

目前,从 NH 4.0.1 开始,这是不可能的。 但是,Jira 存在一个未解决的问题(NH-3659、 https://nhibernate.jira.com/browse/NH-3659 )。 有一个基于自定义拦截器和 SQL 替换的黑客解决方案,在http://weblogs.asp.net/ricardoperes/strongly-typed-delete-with-nhibernate中描述,但我正在研究一个干净的解决方案,最终将提交一个拉取请求。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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