使用参数自动映射器映射视图模型子项



我是使用自动映射器的新手,我遇到了一个问题

我有一个这样的模型。

public class StepUp {
public string Example {get;set;}
public string Example2 {get;set;}
public decimal? auxValue { get;set; }
}

但是我有两个视图模型作为目的地

public class NuevoStepUpViewModel()
{
public bool TieneAuxiliar { get; set; }
public string Example { get;set; }
public CargaDatosElectricos CargaDatosElectricos { get; set; }
}
public class CargaDatosElectricos {
public CargaDatosElectricos(bool tieneAuxiliar)
{
TieneAuxiliar = tieneAuxiliar;
}
public readonly bool TieneAuxiliar;
public string Example2 { get; set; }
}

我认为有些是这样的:

CreateMap<StepUp,NuevoStepUpViewModel()
.ForMember(x => x.TieneAuxiliar, x => x.MapFrom(c => c.auxValue.HasValue))
.ForMember(x => x.Example, x => x.MapFrom(c => c.Example))
.ForMember(x => x.CargaDatosElectricos.Example2, x => x.MapFrom(c => c.Example2))
.BeforeMap((x,y) => {
x.CargaDatosElectricos = new CargaDatosElectricos(c.auxValue.HasValue);
});

但我得到了

表达式 'x => x.CargaDatosElectricos.Example2' 必须解析为 顶级成员,而不是任何子对象的属性

我应该如何创建映射器配置来执行这种类型的映射?

您的代码上有一些错误。您可以使用AfterMap范围(而不是BeforeMap(更好地配置映射以提供复杂的配置。(我不确定,但我认为(AutoMapper不会实例化类型为类的属性。因此,您必须在目标类(VIewModel(的结构上执行此操作,或者在AfterMap上执行此操作。

TieneAuxiliar属性将不允许您在readonly时设置值,因此,您将无法配置到此属性的映射。我把它改成公共经典属性。

请参阅此处的工作示例:

https://dotnetfiddle.net/HSyUVv

using System;
using AutoMapper;
public class Program
{
public static void Main()
{
var config = new MapperConfiguration(cfg => 
{
cfg.CreateMap<StepUp, NuevoStepUpViewModel>()
.ForMember(vm => vm.TieneAuxiliar, opt => opt.MapFrom(e => e.auxValue.HasValue))
.ForMember(vm => vm.Example, opt => opt.MapFrom(e => e.Example))
.AfterMap((e, vm) => 
{
vm.CargaDatosElectricos.Example2 = e.Example2;
});
});
var mapper = config.CreateMapper();
var stepUp = new StepUp()
{
Example = "Example 1",
Example2 = "Example 2",
auxValue = 10m
};
var viewModel = mapper.Map<StepUp, NuevoStepUpViewModel>(stepUp);
Console.WriteLine("SteUp was converted to ViewModel");
Console.WriteLine("TieneAuxiliar: {0}", viewModel.TieneAuxiliar);
Console.WriteLine("Example: {0}", viewModel.Example);
Console.WriteLine("CargaDatosElectricos.TieneAuxiliar: {0}", viewModel.CargaDatosElectricos.TieneAuxiliar);
Console.WriteLine("CargaDatosElectricos.Exemple2: {0}", viewModel.CargaDatosElectricos.Example2);
}
public class StepUp 
{
public string Example { get; set; }
public string Example2 { get; set; }
public decimal? auxValue { get; set; }
}
public class NuevoStepUpViewModel
{
public bool TieneAuxiliar { get; set; }
public string Example { get;set; }
public CargaDatosElectricos CargaDatosElectricos { get; set; }
public NuevoStepUpViewModel() 
{
this.CargaDatosElectricos = new CargaDatosElectricos();
}
}
public class CargaDatosElectricos 
{
public CargaDatosElectricos()
{
}
public bool TieneAuxiliar { get; set; }
public string Example2 { get; set; }
}
}

相关内容

  • 没有找到相关文章

最新更新