Link to NHibernate

The objects

We have an object called Product that loads using NHibernate.

The product has a category that NHibernate happily fills for me.

Database

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

Scenario

The user edits this product (via the web interface) and selects a different category (instead of "Fish" we select "Veg").

This is probably a drop-down list showing each category. When they select another category, we get an int key.

Problem

Obviously, now we want to save the changes to Product, but in fact the only change is to save the new int (say 2 instead of 1).

So, we retrieve the existing Product, and now the problem arises.

We do not have the "CategoryID" field in Product, we only have the Category property.

But we really do not want to retrieve a category (by id) just to assign it to the Product.

So, I think I want to know if we should ...

a) Add the CategoryID property to Product

b) Create a new category, assign an appropriate identifier to it and attach it to the Product (but it will probably cause errors or overwrite the existing category)

c) Get (find) a category from the system (by id) and attach it to the product

d) Do something else!

+2
source share
3 answers

Updated: Session.Load is the correct answer

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

It looks like you can use the Session.Load (id) functionality.

Session.Load is a special method that returns a proxy with an identifier until you request another property to which it is loaded. It throws an error if there is no element matching the ID. Try something like:

 product.Category = Session.Load<Category>(2); //2 being the new category ID Session.SaveOrUpdate(product); 

I just checked a little and didn't seem to drop the entire category.

+4
source

Use NH EnumStringType<T> to match your category as an enumeration with the corresponding database value (which can be a string or a number). You will find many examples of use if you have Google.

NTN!

0
source

Source: https://habr.com/ru/post/1299691/


All Articles