Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC NHibernate Model Binding

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?

like image 765
Ben Foster Avatar asked Jul 14 '10 15:07

Ben Foster


2 Answers

Using pared-down view models tailored specifically for your views is the recommended approach; you can simplify the mapping operations required by using AutoMapper.

like image 163
DanP Avatar answered Oct 24 '22 00:10

DanP


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.

like image 45
John Teague Avatar answered Oct 23 '22 23:10

John Teague