trevorc
trevorc

Reputation: 3031

How would I add properties to my view model that are not part of my model using automapper?

I am not sure if this is possible but here is my situation.

Say I have a model like this:

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

My View model looks like this:

public class ProductModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string CustomViewProperty { get; set; }
}

I am using my ProductModel to post back to a form and I don't care or need the Custom View Property. This mapping works fine as automapper drops the unknown properties.

What I would like to do is map my custom properties in only one direction. i.e.

Mapper.CreateMap<Product, ProductModel>()
      .ForMember(dest => dest.CustomViewProperty //???This is where I am stuck

What ends up happening is when I call "ToModel", automapper dumps my unknown properties and nothing comes over the wire.

Like this.

var product = _productService.GetProduct();
var model = product.ToModel;
model.CustomViewProperty = "Hello World"; //This doesn't go over the wire
return View(model);

Is this possible? Thanks.

Upvotes: 0

Views: 168

Answers (1)

hazzik
hazzik

Reputation: 13344

You should ignore unmapped properties:

Mapper.CreateMap<Product, ProductModel>()
  .ForMember(dest => dest.CustomViewProperty, opt=>opt.Ignore());

or map them:

Mapper.CreateMap<Product, ProductModel>()
  .ForMember(dest => dest.CustomViewProperty, opt=>opt.MapFrom(product=>"Hello world"));

Upvotes: 1

Related Questions