我想删除表A中表B中不存在的所有行。 为了做到这一点,我使用session.Delete(查询)如下:
Session.Delete<A>("FROM A WHERE id NOT IN (SELECT vpg_id FROM B)");
我收到以下错误:
NHibernate.QueryException: could not resolve property: vpg_id of: A [FROM A WHERE Id NOT IN (SELECT vpgid FROM B)]
我还尝试使用HQL进行如下操作:
Session.CreateQuery("DELETE A WHERE id NOT IN (SELECT vpg_id FROM B)").ExecuteUpdate();
并获得此例外:
NHibernate.QueryException: No data type for node: IdentNode vpg_id [DELETE A WHERE id NOT IN (SELECT vpg_id FROM B)]
答案 0 :(得分:1)
您应该尝试对类进行别名(来自NHibernate参考:http://nhibernate.info/doc/nhibernate-reference/queryhql.html#queryhql-subqueries)
from A as aClass
where aClass.id not in (
select bClass.vpg_id from B as bClass
)
或尝试存在
from A as aClass
where not exists (
select bClass.vpg_id from B as bClass where aClass.id = bClass.vpg_id
)
答案 1 :(得分:0)
我设法只使用带有SQL native的CreateSQLQuery来实现:
const string deleteSql = @"DELETE FROM CheckpointStorageObject WHERE NOT EXISTS (Select 1 from CheckpointToProtectionGroup WHERE CheckpointToProtectionGroup.checkpoint_id = CheckpointStorageObject.id)";
Session.CreateSQLQuery(deleteSql).ExecuteUpdate();
我无法使用CreateQuery,因为CheckpointToProtectionGroup表是一个关联表,它有2个引用2个不同的表。因此,NHibernate无法解析CheckpointToProtectionGroup.checkpoint_id属性(即使我使用了别名),因为checkpoint_id列仅存在于数据库中,但在CheckpointToProtectionGroup类中不存在。
如果在包含在CreateSQLQuery之前调用的其他HQL的事务中使用CreateSQLQuery并且可能影响您的本机SQl - 您应该在调用CreateSQLQuery之前调用session.flush()。