我刚刚开始使用automapper映射DTO 实体,它似乎工作得很好.
I just started to use automapper to map DTOs<->Entities and it seems to be working great.
在某些特殊情况下,我只想映射某些属性并执行其他检查.没有自动映射器,代码如下所示(使用fasterflect的PropertyExtensions):
In some special cases I want to map only some properties and perform additional checks. Without automapper the code looks like this (using fasterflect's PropertyExtensions):
object target; object source; string[] changedPropertyNames = { }; foreach (var changedPropertyName in changedPropertyNames) { var newValue = source.GetPropertyValue(changedPropertyName); target.SetPropertyValue(changedPropertyName, newValue); }当然,如果需要类型转换,则此代码将不起作用. Automapper使用内置的TypeConverters,我还创建了一些特定的TypeConverter实现.
Of course this code won't work if type conversions are required. Automapper uses built-in TypeConverters and I also created some specific TypeConverter implementations.
现在,我想知道是否可以映射单个属性并使用automapper的类型转换实现
Now I wonder whether it is possible to map individual properties and use automapper's type conversion implementation, something like this
Mapper.Map(source, target, changedPropertyName);更新
我认为需要更多信息:
Update
I think more information is necessary:
我已经创建了一些地图,例如
I already created some maps, e.g.
Mapper.CreateMap<CalendarEvent, CalendarEventForm>()并且我还为CalendarEvent中的可为null的dateTime属性创建了一个带有自定义类型转换器的地图,例如
and I also created a map with a custom typeconverter for the nullable dateTime property in CalendarEvent, e.g.
Mapper.CreateMap<DateTimeOffset?, DateTime?>().ConvertUsing<NullableDateTimeOffsetConverter>();我在Web API OData Controller中使用这些映射.发布新的EntityDTO时,我使用
I use these maps in a web api OData Controller. When posting new EntityDTOs, I use
Mapper.Map(entityDto, entity);,然后将实体保存到数据存储中.
and save the entity to a datastore.
但是如果使用PATCH,则会将Delta<TDto> entityDto传递给我的控制器方法.因此,我需要调用entityDto.GetChangedPropertyNames()并使用更改后的值更新我现有的持久性实体.
But if using PATCH, a Delta<TDto> entityDto is passed to my controller methods. Therefore I need to call entityDto.GetChangedPropertyNames() and update my existing persistent entity with the changed values.
基本上,这可以与我的简单解决方案一起使用,但是如果更改的属性之一是DateTimeOffset?我想使用我的NullableDateTimeOffsetConverter.
Basically this is working with my simple solution, but if one of the changed properties is e.g. a DateTimeOffset? I would like to use my NullableDateTimeOffsetConverter.
推荐答案如果您只想映射某些select属性,而不必执行以下操作
If you just want to map only some select property than you have to do as below
// Create a map var map = CreateMap<Source,Target>(); // ingnore all existing binding of property map.ForAllMembers(opt => opt.Ignore()); // than map property as following map.ForMember(dest => dest.prop1, opt => opt.MapFrom( src => src.prop1)); map.ForMember(dest => dest.prop2, opt => opt.MapFrom( src => src.prop2));更多推荐
自动映射器:手动映射属性
发布评论