8

How do I map a property from an object to another object with a different property name?

I have a Product class that looks like this:

public class Product : IEntity
{
     public int Id { get; set; }
     public string Name { get; set; }
}

And the view model looks like:

public class ProductSpecificationAddViewModel
{
     public int ProductId { get; set; }
     public string ProductName { get; set; }
}

I need to do the following mapping:

Product.Id => ProductSpecificationAddViewModel.ProductId
Product.Name =>ProductSpecificationAddViewModel.ProductName

Here is my action method:

public ActionResult Add(int id)
{
     Product product = productService.GetById(id);

     // Mapping
     //ProductSpecificationAddViewModel viewModel = new ProductSpecificationAddViewModel();
     //viewModel.InjectFrom(product);

     return View(viewModel);
}

How would I do this?

Omu
  • 69,856
  • 92
  • 277
  • 407
Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234

2 Answers2

8

If you are using ValueInjecter then you would write a ConventionInjection. See the second sample here

    public class PropToTypeProp : ConventionInjection
    {
        protected override bool Match(ConventionInfo c)
        {
            return c.TargetProp.Name == c.Source.Type.Name + c.TargetProp.Name;
        }
    }

this injection will do from all properties of TSource.* to TTarget.TSource+*, so you do:

vm.InjectFrom<PropToTypeProp>(product);
Omu
  • 69,856
  • 92
  • 277
  • 407
Chandermani
  • 42,589
  • 12
  • 85
  • 88
3

You can do this easily with AutoMapper. By default is uses convention (i.e. Id maps to Id and Name to Name), but you can also define custom mappings.

Mapper.CreateMap<Product, ProductSpecificationAddViewModel>()
    .ForMember(destination => destination.ProductName,
               options => options.MapFrom(
                    source => source.Name));

Your contoller mapping code will be then this simple :

Mapper.Map(product, viewModel);
rouen
  • 5,003
  • 2
  • 25
  • 48
  • I know it's easy with AutoMapper but I can't use it on the web hosting servers because of the trust level, so I need to settle for ValueInjecter. – Brendan Vogt Nov 09 '11 at 05:09
  • just curious here. what trust levels are required for Automapper on the server. Both are dlls right? – user20358 Nov 30 '12 at 10:59
  • 1
    medium trust hosting service have problems with automapper because Reflection.Emit doesn't work in medium trust – Not Important Jul 12 '13 at 23:28