NHibernate更新参考
实体
我们有一个名为 Product 的实体,它是使用 NHibernate 加载的。
产品有一个 NHibernate 很乐意为我填充的类别。
数据库
在数据库中,Product 有一个类别的外键。
场景
用户编辑此产品(通过网络界面)并选择不同的类别(假设我们选择“蔬菜”而不是“鱼”)。
这可能是一个下拉列表,显示了每个类别。当他们选择不同的类别时,我们会得到一个 int 键。
问题
显然,我们现在想要保存对 Product 的更改,但实际上唯一的更改是保存一个新的 int (比如 2,而不是 1)。
所以我们检索现有的产品,现在问题来了。
我们的产品上没有“CategoryID”字段,我们只有一个类别属性。
但我们并不是真的想检索类别(通过 id)只是为了将其分配给产品。
所以我想我想知道的是我们应该...
a)向产品添加一个 CategoryID 属性
b)创建一个新类别,为其分配相关 id 并将其附加到产品(但这肯定会导致错误,或者覆盖现有类别)
c) 从系统中检索(查找)类别(通过 ID)并将其附加到产品
d) 完全做其他事情!
Entities
We have an entity called Product which is loaded using NHibernate.
Product has a category which NHibernate happily populates for me.
Database
In the database, Product has a foreign key for category.
Scenario
User edits this Product (via a web interface) and chooses a different category (say instead of "Fish" we select "Veg").
This is probably a dropdown list, with each category shown. When they choose a different category we get an int key.
Problem
Obviously we now want to save the changes to Product but in effect the only change is to save a new int (say 2, instead of 1).
So we retrieve the existing Product, and now comes the problem.
We don't have a "CategoryID" field on Product, we only have a Category property.
But we don't really want to retrieve the category (by id) just to assign it to the Product.
So I guess what I want to know is should we...
a) Add a CategoryID property to Product
b) Create a new category, assign it the relevant id and attach that to Product (but surely that will cause errors, or overwrite the existing category)
c) Retrieve (lookup) the category from the system (by id) and attach that to the Product
d) Do something else entirely!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您似乎可以使用 Session.Load(id) 功能。
Session.Load 是一种特殊方法,它返回带有 ID 的代理,直到您请求另一个属性(此时它会加载)。如果没有与 ID 匹配的项目,则会抛出错误。尝试这样的事情:
我只是做了一些测试,它似乎并没有拉回整个类别。
It looks like you might be able to using the Session.Load(id) functionality.
Session.Load is a special method that returns a proxy with the ID until you request another property at which point it loads. It throws an error if there is no item matching the ID. Try something like:
I just did a little testing and it did not seem to pull back the entire Category.
更新:Session.Load 是正确答案
Updated: Session.Load is the correct answer
使用 NH 的
EnumStringType
将您的类别作为枚举映射到相应的数据库值(可以是字符串或数字)。如果你用谷歌搜索,你会发现很多使用示例。哈!
Use NH's
EnumStringType<T>
to map your Category as an enum to the respective database value (which can be a string or a number). You'll find quite a few usage examples, if you google for it.HTH!