在我的 View 域模型中,我有以下对象作为我的属性的支持字段
public class ModelProperty<T>// where t:struct
{
public T Value { get; set; }
public string Description { get; set; }
public string LabelName { get; set; }
}
对象依次呈现为:
public partial class Incident : BaseEntityModel
{
private ModelProperty<string> typeCode = new ModelProperty<string>{Description="1-C", LabelName = "Type Code"};
private ModelProperty<string> typeText = new ModelProperty<string>{Description="1-C", LabelName = "Type Text"};
public ModelProperty<string> TypeCode { get {return typeCode;}}
public ModelProperty<string> TypeText { get {return typeText;}}
}
业务对象(我的来源)没有那么复杂。
public partial class Incident : ObjectBase
{
public string TypeCode { get; set; }
public string TypeText { get; set; }
}
是否可以将值从源映射到目标。使用 Automapper 我有以下映射设置
//note SrcObj is not an object but a namespace alias since the domain and business objects are of the same name
Mapper.CreateMap<SrcObj.Incident, Incident>()
.ForMember(ui => ui.TypeText.Value,
opt => opt.MapFrom(src => src.TypeText));
但我收到异常表达式必须解析为顶级成员而不是任何子对象的属性。改为对子类型或 AfterMap 选项使用自定义解析器。
我是 automapper 的新手,但在查看文档时,我正在使用的对象是否过于复杂(基于这里实际上存在三种类型而不是两种的想法)?
如果可以处理这种类型的映射,这是怎么做到的?
更新
根据 Jimmy 的建议,我更新了我的代码如下:
Mapper.CreateMap<SrcObj.Incident, Incident>();
Mapper.CreateMap<string, ModelProperty<string>>()
.ConvertUsing(src => new ModelProperty<string> { Value = src });
Mapper.AssertConfigurationIsValid();
SrcObj.Incident viewModelDto = md.GenerateMockIncident(); //populate the business object with mock data
uibase = Mapper.Map<SrcObj.Incident, Incident>(viewModelDto);
代码执行并且我没有收到任何异常,但是在业务对象中设置和返回的值仍然没有分配给支持属性 Value 它仍然是 null。
我错过了什么?
-干杯
请您参考如下方法:
一种更简单的方法是创建类型转换器:
Mapper.CreateMap<string, ModelProperty<string>>()
.ConvertUsing(src => new ModelProperty<string> { Value = src });
然后每次 AutoMapper 看到字符串 -> ModelProperty 时,您都会有这个。您根本不需要进行特定于成员的配置。
