cho*_*bo2 11 c# asp.net-mvc automapper
我有类似的东西
public class ProductViewModel
{
  public int SelectedProductId { get; set; }
  public string ProductName {get; set;}
  public int Qty {get; set;}
   public List<SelectListItem> Products { get; set}; 
}
Run Code Online (Sandbox Code Playgroud)
我有这样的域名
public class Product
{
  public int ProductId {get; set;}
  public string ProductName {get; set;}
  public int Qty {get; set;}
}
public class Store
{
  public Product() {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
现在我需要进行映射.
//在我的控制器里
var result = Mapper.Map<ProductViewModel, Store>(Product);
Run Code Online (Sandbox Code Playgroud)
这不会绑定任何东西,因为它无法弄清楚如何将ProductId放入其中
Store.Product.ProductId;
Run Code Online (Sandbox Code Playgroud)
我的地图是这样的
Mapper.CreateMap<ProductViewModel, Store>().ForMember(dest => dest.Product.ProductId, opt => opt.MapFrom(src => src.SelectedProductId));
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
表达式'dest =>转换(dest.Product.SelectedProductId'必须解析为顶级成员.参数名称:lambdaExpression
我不确定该怎么做.
duy*_*ker 25
要映射嵌套结构,只需在MapFrom参数中创建一个新对象.
例
制图:
Mapper.CreateMap<Source, Destination>()
      .ForMember(d => d.MyNestedType, o => o.MapFrom(t => new NestedType { Id = t.Id }));
Mapper.AssertConfigurationIsValid();
Run Code Online (Sandbox Code Playgroud)
测试代码:
var source = new Source { Id = 5 };
var destination = Mapper.Map<Source, Destination>(source);
Run Code Online (Sandbox Code Playgroud)
类别:
public class Source
{
    public int Id { get; set; }
}
public class Destination
{
    public NestedType MyNestedType { get; set; }
}
public class NestedType
{
    public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
        您得到的错误是因为您无法在对象图中声明超过一层的映射声明。
因为您只发布了一个属性,所以我很难为您提供使这项工作有效的代码。一种选择是将视图模型属性更改为 MyTestTestId,约定将自动采用。