views:

180

answers:

2

Say I have a class, e.g.:

public class Person
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual int SpouseId { get; set; }
    public virtual Person Spouse { get; set; }
}

I have included the SpouseId because that is the out-of-the-box way to model bind using (Try)UpdateModel (based on ScottGu's sample MVC 2.0 code here). In my NHibernate mapping I have set SpouseId to insert=false and update=false, and my mapping works just fine.

I to have a "create person" form in ASP.NET MVC (2), which then uses SpouseId to select the spouse:

<%
using (Html.BeginForm()) 
{
%>
    <%= Html.LabelFor(m => m.Name) %>
    <%= Html.TextBoxFor(m => m.Name) %>
    <%= Html.ValidationMessageFor(m => m.Name) %>

    <%= Html.LabelFor(m => m.SpouseId) %>
    <%= Html.EditorFor(m => m.SpouseId, "PersonPicker") %>
    <%= Html.ValidationMessageFor(m => m.SpouseId) %>
<%
}
%>

Where I have an EditorTemplate for "PersonPicker" that just displays a dropdown based on a list of person's in ViewData.

When I then do TryUpdateModel() it works fine, I get my values populated like expected, i.e. SpouseId gets set but not Spouse. and the problem with this is of course that NHibernate uses Person.Spouse.

I would definitely prefer to skip the SpouseId entirely since it is cluttering my model and it is only there because of this issue.

I could of course do person.Spouse = myService.Find<Person>(person.SpouseId); in code but that has a very, very nasty smell to it.

What is the best way to do this? Preferably dropping the SpouseId property entirely.

(I might add that I am using VS2008 and .NET 3.5)

A: 

Here is what I have done so far it works, but I don't think it is perfect and for that reason I have my doubts as to wether it is the best/right way to do it.

I wen't the Way of The ModelBinder and created a ModelBinder like the following:

public class MyModelBinder : DefaultModelBinder
{
    public MyModelBinder(IService service)
    {
        this.Service = service; 
    }

    private IService Service
    {
        get;
        set;
    }

    protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
    {
        var modelType = bindingContext.ModelType;

        if (/* determine if modelType is a type for association */)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var id = (int?)value.ConvertTo(typeof(int));
            var result = id.HasValue ? this.Service.Find(modelType, id.Value) : null;

            if (result != null)
            {
                return result;
            }
        }

        return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
    }
}

Apart from the logic to determine if the type is "included" it seems fine with me.

The tedious part comes from registering the binders in Global.asax (using StructureMap for IoC):

ModelBinders.Binders[typeof(Person)] = ObjectFactory.GetInstance<MyModelBinder>();

This I would have to do for all types. It works and it is better than my previous solution, but could it be better?

veggerby
A: 

Okay what I really, really ended up doing was to use AutoMapper and a ViewModel:

public class PersonViewModel 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int SpouseId { get; set; }    
}

And to populate view model:

// set once for app Mapper.CreateMap<Person, PersonViewModel>();
var personViewModel = Mapper.Map<Person, PersonViewModel>(person);

To re-populate domain:

// set once for app 
// Mapper.CreateMap<PersonViewModel, Person>()
//    .ForMember(x => x.Id, o => o.Ignore())
//    .ForMember(x => x.Spouse, o => o.MapFrom(x => PersonService.Find(x.SpouseId)));
var viewModel = new PersonViewModel();
if (TryUpdateModel(viewModel)) 
{
    var person = PersonService.Find(viewModel.Id);
    Mapper.Map(personViewModel, person);
}

Only thing I'm not fond of is the "back-mapping" of Spouse, since is requires a PersonService (eg. via DI/IoC) - however apart from that it works.

For this simple sample AutoMapper is probably overkill, and if we don't use AutoMapper for the "save back to domain model", we won't have the PersonService dependency in the mapping configuration (however in the Action method and that might "violate" DRY).

veggerby