仅通过主键删除 NHibernate 中的实体 [英] Remove entity in NHibernate only by primary key

查看:60
本文介绍了仅通过主键删除 NHibernate 中的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个仅使用主键删除实体的存储库方法,主要是因为从 web 应用程序中,我通常只在从网页调用删除请求"时知道主键.

I'm trying to implement a repository method for removing entities using only primary key, mainly because from a webapp I usually only are aware of the primary key when invoking a "delete request" from a web page.

由于 ORM,今天的选择是从数据库中获取实体,然后将其删除,这给了我额外的往返.

Because of the ORM, the option today is to get the entity from the database, and then deleting it, which gives me an extra roundtrip.

我可以使用 HQL 删除,但是由于我想为所有实体创建一个通用的删除方法,除非我使用反射来找出哪个字段是主键(可行,但感觉不到正确).

I could use HQL delete, but since I want to create a generic delete method for all entities, that won't fly unless I use reflection to find out which field that is the primary key (doable, but doesn't feel correct).

或者是 NHibernate 需要实体来正确处理级联?

Or is it in the nature of NHibernate to need the entity in order to correctly handle cascades?

我尝试了这种方法,假设它不会加载实体,除非明确需要,但是还没有时间对其进行测试.也许有人可以解释一下将如何​​处理?

I tried this approach, with the assumption that it would not load the entity unless explicitly necessary, however haven't had time to test it yet. Maybe someone can shed some light on how this will be handled?

var entity = session.Load<T>( primaryKey );
session.Delete( entity );

现在已经对其进行了测试,它似乎在删除之前仍然对实体进行了完整选择.

Have now tested it and it seems that it still does a full select on the entity before deletion.

推荐答案

Load 可能会返回一个代理对象,但不能保证.您的映射可能包含级联删除,这将强制 NHibernate 从数据库加载对象,以确定如何删除对象及其图形.

Load may return a proxy object but it isn't guaranteed. Your mapping may contain cascade deletes that will force NHibernate to load the object from the database in order to determine how to delete the object and its graph.

我会像您一样使用 Load 来实现.对于某些对象,NHibernate 可能不需要先进行选择.在这种情况下,这是[通常]您为使用 o/r 映射器支付的微不足道的代价.

I would implement this using Load as you are doing. For some objects NHibernate may not need to do a select first. In cases where it does, that's the [usually] trivial price you pay for using an o/r mapper.

这篇关于仅通过主键删除 NHibernate 中的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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