Nhibernate GetById 返回 ObjectNotFoundException insetad of null
我正在使用流畅的 Nhibernate。此代码根据 ID 从数据库加载类型 T 的实例。
public T GetById(IdT id, bool shouldLock)
{
T entity;
if (shouldLock)
{
entity = (T) NHibernateSession.Load(persitentType, id, LockMode.Upgrade);
}
else
{
entity = (T) NHibernateSession.Load(persitentType, id);
}
return entity;
}
但我有一个大问题。当我调用它的属性时,我得到 ObjectNotFoundException
而不是 null
。
如何使该实体可为空并且不返回异常?
I am using fluent Nhibernate. This code Loads an instance of type T from the DB based on its ID.
public T GetById(IdT id, bool shouldLock)
{
T entity;
if (shouldLock)
{
entity = (T) NHibernateSession.Load(persitentType, id, LockMode.Upgrade);
}
else
{
entity = (T) NHibernateSession.Load(persitentType, id);
}
return entity;
}
But I have big problem. When I call property on it I get ObjectNotFoundException
instead of null
.
How can I make that entity be nullable and not return the Exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用 Get 而不是 Load。 Get 将返回 null,而不是异常。
I would use Get instead of Load. Get will return null, instead of an exception.
我认为您误解了
Load
的作用。这会通过 ID 为您创建一个 NHibernate 代理对象,而无需实际查询数据库。当您调用属性时,它将查询数据库,如果您提供了错误的 ID,则没有底层对象,因此会出现异常。
您将使用此功能的正常情况是,您有一个 State 对象,并且用户在下拉列表中选择了 PA。因为您已经拥有密钥 PA,所以不必在数据库中查询 State 对象,您可以调用 Load,然后将该状态对象传递到另一个对象中,以获得对象 X 与状态 PA 的正确关系。
您想要用于一般获取对象或在键不存在时获取 null 的方法只是
Session.Get(object ID)
I think you're mistaken in what
Load
does. This create an NHibernate proxy object for you by ID without actually querying the database.When you invoke a property it will query the database, if you supplied a bad id there is no underlying object hence the exception.
The normal situtations you will use this is for is say you have a State object and the user selected PA in a drop down. Instead of having to query the database for the State object since you already have the key PA you can call
Load
and then pass that state object into a different object to have the correct relationship of Object X to State PA.The method you want to be using for general get object or get null if key does not exist is just
Session.Get<T>(object ID)
Load
永远不会返回 null。它总是返回一个实体或抛出异常。如果您想要这种行为,请使用Get
。有关此的更多信息获取和加载之间的区别Load
will never return null. It will always return an entity or throw an exception. If you want that behaviour useGet
. More info on this Difference between Get and Load