如何使用标准删除 NHibernate 对象? [英] How can one delete NHibernate objects using a criteria?

查看:22
本文介绍了如何使用标准删除 NHibernate 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这一定是一个简单的问题.给定一个条件,如何删除满足条件的实体?

This must be a simple question. Given a criteria, how one deletes the entities satisfying the criteria?

理由:

HQL 和 NH 标准是 NHibernate 特定的构造,因此它们是服务器端 DAL 实现细节.我不希望它们泄漏"到客户端.因此,我们的客户端提供了 LINQ 表达式供服务器处理.到目前为止,选择请求和 LINQ to NHibernate 处理它们的请求都很好.

HQL and NH criteria are NHibernate specific constructs and as such they are server side DAL implementation details. I do not want them to "leak" to the client side. So, our client side provides LINQ expressions for the server to process. Up until now the requests where select requests and LINQ to NHibernate dealed with them just fine.

但是,现在需要实现批量删除操作.像往常一样,客户端提供一个 LINQ 表达式,服务器将删除满足该表达式的实体.不幸的是,LINQ to NHibernate 在这里没有帮助.它最多可以将给定的 LINQ 表达式转换为 NHibernate 标准.

However, there is a need to implement batch delete operation now. As usual, the client side provides a LINQ expression and the server is to delete entities satisfying the expression. Unfortunately, LINQ to NHibernate is of no help here. The most it can do is translate the given LINQ expression to NHibernate criteria.

无论如何,这就是故事.我想强调的是,客户端根本不知道 NHibernate,我喜欢它保持这种状态.

Anyway, this is the story. I wish to stress that the client side is unaware of NHibernate at all and I like it to stay this way.

附言

我使用的是 NH 2.1

I am using NH 2.1

推荐答案

您可以使用标准来选择元素的 ID,将它们连接到一个字符串中,然后使用 HQL 删除它们?

You may use the criteria to select the IDs of your elements, join them in a string and use HQL to delete them?

类似于:

public void Delete(ICriteria criteria, string keyName, string tableName)
{
    criteria.setProjection(Projections.Attribute(keyName));
    IList<int> itemIds = criteria.List<int>();

    string collection = string.Join(",", Array.ConvertAll<int, string>(itemIds, Convert.ToString));

    Session.HQL(string.Format("delete from {0} where {1} in ({2})", tableName, keyName, collection);
}

此代码未经测试或编译(特别是我不确定 HQL 部分),但我认为您明白了:由于投影,我们不会获取整个对象,而只会获取索引.

This code was not tested or compiled (in particular I'm not sure of the HQL section), but I think that you got the idea: we don't fetch the whole objects thanks to the projection, but only the indices.

这篇关于如何使用标准删除 NHibernate 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆