With NHibernate I no longer expose foreign keys on my domain objects, so Product no longer has a property:
public int CategoryId {get;set;}
but instead has:
public Category Category {get;set;}
Unforunately this doesn't appear to work so well with the automatic model binding in ASP.NET MVC - if I want to simply bind a form collection directly to my domain object.
For example, I couldn't just have a selectlist of Category Id values in my view, accept a product object in my controller action, and expect MVC to convert this into a category object.
My solution so far has been to create view models that do have properties for the foreign key values - However, this normally leads to a fair bit of duplication in code and extra mapping logic in my controller.
Is there a better way?
Using pared-down view models tailored specifically for your views is the recommended approach; you can simplify the mapping operations required by using AutoMapper.
Also, remember that when using Nhibernate, you are dealing with proxy objects and it is best not to try and serialize them across application boundaries, like model binding, web services, or Remote calls.
If you need to turn CustomerID into Customer, you are going to have to create a Custom Model Binder that is data repository aware and can take customerID and get a Customer object. There are some cases where this is useful, but I would not recommend it for this scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With