C# 如何使用 Nhibernate 删除多个数据库实体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1869057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete multiple db entities with Nhibernate?
提问by Newbie
What is the best practice for this problem? Is there any batching features built-in?
这个问题的最佳实践是什么?是否有内置的批处理功能?
Sample code:
示例代码:
using (ITransaction transaction = _session.BeginTransaction())
{
_session.Delete("FROM myObject o WHERE o.Id = IN(1,2,...99999)");
transaction.Commit();
}
Thanks in advance.
提前致谢。
采纳答案by joshperry
HQL supports the IN clause, and if you use setParameterList you can even pass in a collection.
HQL 支持 IN 子句,如果你使用 setParameterList 你甚至可以传入一个集合。
var idList = new List<int>() { 5,3,6,7 };
_session.CreateQuery("DELETE MyDataClass o WHERE o.Id IN (:idList)")
.SetParameterList("idList", idList)
.ExecuteUpdate();
Be aware, like mentioned by ddango in a comment, that relationship cascades specified in your objects will not be executed since running an HQL query simply translates to a DB query and does not actually load any entity objects.
请注意,就像 ddango 在评论中提到的那样,在您的对象中指定的关系级联将不会执行,因为运行 HQL 查询只会转换为 DB 查询,实际上并不会加载任何实体对象。
回答by Dani
you can Use HQL to delete multiple objects
您可以使用 HQL 删除多个对象
Look for delete here - for session.delete example
在此处查找删除 - 对于 session.delete 示例
HQL DELETE example (you can use IN with HQL):
HQL DELETE 示例(您可以将 IN 与 HQL 一起使用):
ISession session = sessionFactory.OpenSession();
ITransaction tx = session.BeginTransaction();
String hqlDelete = "delete Customer c where c.name = :oldName";
// or String hqlDelete = "delete Customer where name = :oldName";
int deletedEntities = session.CreateQuery( hqlDelete )
.SetString( "oldName", oldName )
.ExecuteUpdate();
tx.Commit();
session.Close();
回答by Chris Kolenko
I had problems getting the answer to work and I found the following query worked 100%
我在获得答案时遇到问题,我发现以下查询 100% 有效
Session.CreateQuery("delete Customer c where c.id in (:deleteIds)")
.SetParameterList("deleteIds", deleteIds)
.ExecuteUpdate();
Customer is the class name not the table name. id is lowercase and in HQL it is the Primary Key not a property name in the class (Property names are supported)
客户是类名而不是表名。id 是小写的,在 HQL 中它是主键而不是类中的属性名称(支持属性名称)