NHibernate更新参考 [英] NHibernate update reference

查看:84
本文介绍了NHibernate更新参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实体

我们有一个名为Product的实体,该实体是使用NHibernate加载的.

We have an entity called Product which is loaded using NHibernate.

产品具有NHibernate为我高兴地填充的类别.

Product has a category which NHibernate happily populates for me.

数据库

在数据库中,产品具有类别的外键.

In the database, Product has a foreign key for category.

场景

用户(通过Web界面)编辑此产品,然后选择其他类别(例如,我们选择蔬菜"代替鱼").

User edits this Product (via a web interface) and chooses a different category (say instead of "Fish" we select "Veg").

这可能是一个下拉列表,其中显示了每个类别.当他们选择其他类别时,我们会得到一个int密钥.

This is probably a dropdown list, with each category shown. When they choose a different category we get an int key.

问题

很显然,我们现在要保存对Product的更改,但实际上唯一的更改是保存一个新的int(例如2,而不是1).

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.

我们在产品"上没有"CategoryID"字段,我们只有类别"属性.

We don't have a "CategoryID" field on Product, we only have a Category property.

但是我们并不是真的想仅通过将类别分配给产品来检索类别(按ID).

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)向商品添加CategoryID属性

a) Add a CategoryID property to Product

b)创建一个新类别,为其分配相关ID,并将其附加到产品上(但肯定会导致错误或覆盖现有类别)

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)从系统中检索(查找)类别(按ID)并将其附加到产品上

c) Retrieve (lookup) the category from the system (by id) and attach that to the Product

d)完全做其他事情!

d) Do something else entirely!

推荐答案

已更新:Session.Load是

Updated: Session.Load is the correct answer

product.Category = session.Load<Category>(2);

session.Save(product);

这篇关于NHibernate更新参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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