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

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

问题描述

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

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

基本原理:

HQL和NH标准是NHibernate特定的构造,因此它们是服务器端DAL实现的详细信息.我不希望他们泄漏"到客户端.因此,我们的客户端提供了LINQ表达式供服务器处理.到现在为止,选择请求和LINQ发送给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.

P.S.

我正在使用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天全站免登陆