Rai*_*bal 5 c# automapper automapper-4
在我的Web API控制器方法中,在映射UpdatePlaceDTO到之前PlaceMaster,我进行数据库调用以填充Map未涵盖的属性,但由于某种原因,AutoMapper使这些属性为null.
var mappedPlaceMaster = _mapper.Map<PlaceMaster>(placeMasterDTO);
// mappedPlaceMaster.EntityId is null
Run Code Online (Sandbox Code Playgroud)
我已经尝试过IgnoreExistingMembers的许多解决方案,但它们都不起作用.
这就是我所拥有的
public class PlaceMapperProfile : Profile
{
protected override void Configure()
{
// TO DO: This Mapping doesnt work. Need to ignore other properties
//CreateMap<UpdatePlaceDto, PlaceMaster>()
// .ForMember(d => d.Name, o => o.MapFrom(s => s.Name))
// .ForMember(d => d.Description, o => o.MapFrom(s => s.Description))
// .ForMember(d => d.ParentPlaceId, o => o.MapFrom(s => s.ParentPlaceId))
// .ForMember(d => d.LeftBower, o => o.MapFrom(s => s.LeftBower))
// .ForMember(d => d.RightBower, o => o.MapFrom(s => s.RightBower)).IgnoreAllNonExisting();
}
}
Run Code Online (Sandbox Code Playgroud)
这是扩展
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
foreach (var property in expression.TypeMap.GetUnmappedPropertyNames())
{
expression.ForMember(property, opt => opt.Ignore());
}
return expression;
}
Run Code Online (Sandbox Code Playgroud)
我已经使用模块将mapper注入到我的依赖项中
protected override void Load(ContainerBuilder builder)
{
//register all profile classes in the calling assembly
var profiles =
from t in typeof(Navigator.ItemManagement.Data.MappingProfiles.PlaceMapperProfile).Assembly.GetTypes()
where typeof(Profile).IsAssignableFrom(t)
select (Profile)Activator.CreateInstance(t);
builder.Register(context => new MapperConfiguration(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
})).AsSelf().SingleInstance();
builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve))
.As<IMapper>()
.SingleInstance();
}
Run Code Online (Sandbox Code Playgroud)
我在一些线程中看到_mapper.Map实际上创建了一个新对象,所以我们如何将它添加到现有属性值的"附加"?
好吧,我找到了解决方案。它就在我面前,但我没有看到!
我只需使用 Map 函数的重载,该函数不会创建 PlaceMaster 的新实例,而是分配地图中可用的属性。
mappedPlaceMaster = _mapper.Map(placeMasterDTO, placeMasterFromDatabase);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
305 次 |
| 最近记录: |