我正在尝试为新模块实现 AutoMapper。
我在网站上有 MVC 模型,我正在研究它,它看起来像这样:
public class MvcModel
{
public Params Params { get; set; }
public Steps Steps { get; set; }
}
public class Params
{
public int? RequestId { get; set; }
public bool NewClient { get; set; }
}
public class Steps
{
public Step1 Step1 { get; set; }
public Step2 Step2 { get; set; }
public Step3 Step3 { get; set; }
}
public class Step1
{
public int Name { get; set; }
}
public class Step2
{
public int Phone { get; set; }
}
public class Step3
{
public int Email { get; set; }
}
另一方面,我有下一堂课,我必须将其传递给某些服务:
public class Request
{
public Parameters Parameters { get; set; }
public RequestContent RequestContent { get; set; }
}
public class Parameters
{
public int NewClient { get; set; }
}
public class RequestContent
{
public int Id { get; set; }
public int InnerId { get; set; }
public string Session { get; set; }
public string Clerk { get; set; }
public bool Private { get; set; }
public PersonalDetails PersonalDetails { get; set; }
public Phones Phones { get; set; }
public ElectonicCommunication ElectonicCommunication { get; set; }
}
public class PersonalDetails
{
public int Name { get; set; }
}
public class Phones
{
public int Phone { get; set; }
}
public class ElectonicCommunication
{
public int Email { get; set; }
}
我创建了一个新的 AutoMapper 配置类(从 Global.asax 调用):
public class AutoMapperConfig
{
public static void Configure()
{
MapperConfiguration MapperConfiguration = new MapperConfiguration(cfg => {
cfg.AddProfile<Out>();
cfg.AddProfile<In>();
cfg.CreateMap<MvcModel, Request>();
});
MapperConfiguration.AssertConfigurationIsValid();
}
}
public class Out: Profile
{
protected override void Configure()
{
CreateMap<MvcModel, Request>()
.ForMember(dest => dest.Parameters, opt => opt.MapFrom(src => src.Params))
.ForMember(dest => dest.RequestContent, opt => opt.MapFrom(src => src.Steps));
}
}
public class In: Profile
{
protected override void Configure()
{
CreateMap<Request, MvcModel>()
.ForMember(dest => dest.Params, opt => opt.MapFrom(src => src.Parameters))
.ForMember(dest => dest.Steps, opt => opt.MapFrom(src => src.RequestContent));
}
}
这些在原理上是相似的,尽管真实的物体更大一些并且有不同的名称。
期望: MvcModel
要映射到Request
和向后。
更准确地说:
-
MvcModel.Params
要映射到Request.Parameters
和向后
-
MvcModel.Steps
要映射到Request.RequestContent
和向后
-
InnerId
, Session
, Clerk
, Private
from Request.RequestContent
必须被忽略
问题:应用程序启动时出现错误:
无法映射 ... 上的以下属性:
添加自定义映射表达式、忽略、添加自定义解析器或修改
目的地类型...
语境:
映射到属性...从...到...
从类型...映射到...
从源类型 AutoMapperMessageBugTests.SourceChild 映射到类型
引发了“AutoMapper.AutoMapperConfigurationException”类型的异常。
我没有找到关于如何在应用程序中全局使用 AutoMapper 的良好文档,并且无法弄清楚如何正确使用它以及我到底做错了什么。
我找不到复杂对象映射以太的好例子......
有人可以帮我弄这个吗?