NHibernate 中的静态查找
我想在 NHibernate 中使用一些预定义的查找,而不需要对数据库进行往返。
基本上我想要这样的代码:
public class Countries
{
static Countries() {
Australia = new Country
{
Id = 14,
Description = "Australia"
}
}
public static Country Austrlia { get; protected set }
}
然后编写以下代码片段:
address.Country = Countries.Australia;// Snippet1
if (address.Country == Countries.Australia) { // Snippet2
// Do something
}
所以我会重写 Equals、GetHashCode 甚至重载运算符 == 和 != 用于 Country 类查找。
仅当具有给定 ID 的国家/地区尚未加载到内存中时,Snippet1 才起作用。 否则,它会抛出 NonUniqueObjectException ,表示具有给定 Id 的对象已在内存中。
为了解决这个问题,我必须驱逐加载的国家/地区,然后分配查找值。 这感觉不对,我不确定再次执行国家/地区查找查询时会发生什么。
那么问题是:如何在NHibernate中维护静态查找类?
谢谢, 德米特里。
I want to use some of predefined lookups without roundrips to Database in NHibernate.
Basically I would like to have code like this:
public class Countries
{
static Countries() {
Australia = new Country
{
Id = 14,
Description = "Australia"
}
}
public static Country Austrlia { get; protected set }
}
Then write this code snippets:
address.Country = Countries.Australia;// Snippet1
if (address.Country == Countries.Australia) { // Snippet2
// Do something
}
So I do override Equals, GetHashCode and even overload operators == and != for Country class lookup.
The Snippet1 works ONLY if the Country with given Id has not been loaded into memory.
Otherwise it throws NonUniqueObjectException saying the object with given Id is already in memory.
To workaraound this I have to evict the loaded country and then assign the lookup value.
This feels wrong and I'm not sure what will happen when the query for Country lookup will be executed again.
So the question is: How to maintain static lookup classes in NHibernate?
Thanks,
Dmitriy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NHibernate 似乎无法处理逻辑上相同(但实例不同)的 2 个对象。
因此,与其将“静态查找”与数据库查找混合在一起,不如只使用其中之一。
就我而言 - 存储在数据库中的查找。 但为了避免仅仅为了获取对象而往返数据库,只需要使用 Load 而不是 Get:
It seems NHibernate cannot handle 2 objects logically the same (but different instances).
So instead of mixing "static lookup" with Database lookups it is better to only use one of them.
In my case - lookups stored in the database. BUT to avoid roundtrip to the database just for the sake of obtaining the object it is only needed to use Load instead of Get:
看看我们所说的枚举类..
基本上是享元模式。
您可以使用
IUserType
实现将它们保留为值或显示名称。我们和他们一起做疯狂的事情。 比如为 DBA 人员提供自动生成的带有外键的查找表,同时将所有值保留在代码中。
Check out what we call Enumeration classes..
It's basically the flyweight pattern.
You can persist them, using an
IUserType
implementation, as the value or the display name.We do crazy stuff with them. Like provide auto-genned lookup tables with foreign keys for DBA folks while keeping all the values in code.