ASP.NET MVC - Partially updating model from view

前端 未结 6 721
独厮守ぢ
独厮守ぢ 2021-01-31 20:17

I just wondered how people were approaching this situation. It\'s something that seems like a weak point in my usage of MVC with ORMs (NHibernate in this case)...

Say y

6条回答
  •  野的像风
    2021-01-31 20:57

    This sounds like the perfect scenario for automapper. You create a view model class which contains a subset of the fields or your real model, and you let AutoMapper take care extraccting values from the domain model object into your view model object. What issues are you having with this approach?

    Consider this example:

    Here is your domain model and your view model

    public class Person
    {
        public string FirstName
        { get; set; }
    
        public string LastName
        { get; set; }
    
        public string HomeNumber
        { get; set; }
    
        public string Address1
        { get; set; }
    
        public string Address2
        { get; set; }
    }
    
    public class PersonViewModel
    {
        public string FirstName
        { get; set; }
    
        public string LastName
        { get; set; }
    
        public string HomeNumber
        { get; set; }
    }
    

    Here is your mapping, you have to create a mapping in both directions from dm->vm and vm->dm.

    From what I've seen when using Automapper is that if you map from object A to B and B has a property which A doesn't have, it will be reset. So when I create the map I direct it to ignore those missing properties. I'm not a Automapper expert so I may be using it wrong.

    Mapping

    Mapper.CreateMap();
    // Automapper will reset values in dest which don't exist in source, so be sure to ignore them!
    Mapper.CreateMap()
        .ForMember(dest => dest.HomeNumber, opt => opt.Ignore());
    

    Finally usage:

    Person p = new Person()
    {
        FirstName = "First",
        LastName = "Last",
        Address1 = "add 1",
        Address2 = "add 2"
    };
    
    PersonViewModel pvm = Mapper.Map(p);
    // Map to a new person
    Person p2 = Mapper.Map(pvm);
    
    // Map to the existing person just to update it
    Person p3 = new Person()
    {
        HomeNumber = "numberHere"
    };
    
    // This will update p3
    Mapper.Map(pvm, p3);
    

    Because of the exclusion, this is obviously less than ideal, but much better than manually doing the whole thing.

提交回复
热议问题