I'm new to NHibernate but have a better understanding of EF4.
I have a basic "Edit Item" page, and on submit I want to update my Item object with values from the form. FWIW, I'm using a FormView and leveraging the new WebForms Model Binding features where practical.
My "Item" object has a property:
public virtual Category Category { get; set; }
which corresponds to a FK relationship in the database (column "CategoryId" pointing to table "Category".)
So my form has a "Category" dropdown. This dropdown has been loaded with a list of all the Category objects.
On submit, all I want to do is assign the selected value in the Category dropdown to the Category property of my Item object. Pretty straight forward, right? :)
However I ran into difficulty:
I can easily get the dropdown.SelectedValue, but I can't assign this to my Item object. In EF4, my Item object would use a Foreign Key Association and would thererfore have both
CategoryandCategoryIdproperties, which would automatically be kept in sync. When I tried something similar in NHibernate I got a Invalid Index for this SqlParameterCollection error due to the attempted multiple use of a single column.I an easily get the dropdown.SelectedItem, but this is of type ListItem, which cannot be cast to
Category.I tried making use of the dropdown.DataSource property (maybe accessing the "SelectedIndex-th" item), but when stepping through the code, this DataSource value was null.
My best (awful) solution so far is as follows:
var dropdown = (DropDownList)MyFormView.FindControl("dropdown");
var id = dropdown.SelectedValue;
var category = new MyRepository().GetCategoryById(id);
item.Category = category;
So I'm making an extra repository call, and getting the entire Category object again, when all I really want to do is:
item.CategoryId = id;
How should I be doing this?