Asp.net mvc 3 如何使用automapper向视图模型中添加不属于模型的属性?

Asp.net mvc 3 如何使用automapper向视图模型中添加不属于模型的属性?,asp.net-mvc-3,automapper,Asp.net Mvc 3,Automapper,我不确定这是否可行,但我的情况是这样的 假设我有一个这样的模型: public class Product { public int Id { get; set; } public string Name { get; set; } } public class ProductModel { public int Id { get; set; } public string Name { get; set; } public string CustomV

我不确定这是否可行,但我的情况是这样的

假设我有一个这样的模型:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class ProductModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string CustomViewProperty { get; set; }
}
我的视图模型如下所示:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class ProductModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string CustomViewProperty { get; set; }
}
我正在使用ProductModel发回表单,我不关心或不需要自定义视图属性。当automapper删除未知属性时,此映射工作正常

我想做的是只在一个方向上映射我的自定义属性。i、 e

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

这可能吗?谢谢。

您应该忽略未映射的属性:

Mapper.CreateMap<Product, ProductModel>()
  .ForMember(dest => dest.CustomViewProperty, opt=>opt.Ignore());
Mapper.CreateMap()
.FormMember(dest=>dest.CustomViewProperty,opt=>opt.Ignore());
或者绘制它们的地图:

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

我已经尝试了这两种方法,automapper删除了我的自定义属性。我相信“忽略”就是这样做的。这是正确的。吉米强迫我重新检查我的ToModel扩展,这就是问题所在。Ignore起作用。ToModel属性具体做什么?这是一种扩展方法,我将实体映射到模型。它应该是product.ToModel();