我是AutoMapper新手,正在使用版本6.2.2。 我试图将视图模型映射到实体(也使用Entity Framework)。 我只想更新视图模型和实体中都存在的属性。 实体具有其他导航属性和相关对象,这些都不是源视图模型的一部分。 我当前收到一个错误,指出目标实体上存在未映射的属性。 我的视图模型和实体都有超过40个属性,因此我不想将每个属性都明确添加到映射中。
这是我的代码:
映射:
public static void RegisterMaps()
{
AutoMapper.Mapper.Initialize(config =>
{
config.CreateMap<EditApplicationViewModel, Application>();
});
}
我也尝试了以下方法,但是出现了相同的错误:
config.CreateMap<EditApplicationViewModel, Application>(MemberList.source);
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditApplicationViewModel viewModel)
{
if (ModelState.IsValid)
{
Application application = _applicationService.GetById(viewModel.ApplicationId);
application = Mapper.Map(viewModel, application);
}
}
错误信息:
InnerException: HResult=-2146233088 Message= Unmapped members were found. Review the types and members below. Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters ========================================================== String -> User (Destination member list) System.String -> ..***.entities.User (Destination member list)
Unmapped properties: removed - a very long list of related objects and properties on the destination
Source=AutoMapper StackTrace: at lambda_method(Closure , EditApplicationViewModel , Application , ResolutionContext )
更新:
我还尝试了以下地图。虽然没有收到任何错误信息,但目标上的源属性都没有更新。
config.CreateMap<EditApplicationViewModel, Application>().ForAllOtherMembers(opts=>opts.Ignore());