Dei*_*lan 24 .net c# mapping asp.net-mvc automapper
假设我有以下"目的地"类:
public class Destination
{
public String WritableProperty { get; set; }
public String ReadOnlyProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和一个"source"类,ReadOnly其中一个属性的属性:
public class Source
{
public String WritableProperty { get; set; }
[ReadOnly(true)]
public String ReadOnlyProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
很明显,但要明确:我将按照以下方式从一个Source类映射到另一个Destination类:
Mapper.Map(source, destination);
Run Code Online (Sandbox Code Playgroud)
配置Automapper以自动忽略属性ReadOnly(true)属性的方法有哪些?
我使用Automapper的Profile类进行配置.我不想弄脏具有Automapper特定属性的类.我不想为每个只读属性配置Automapper,并且通过这种方式导致大量重复.
IgnoreMap向属性添加属性: [ReadOnly(true)]
[IgnoreMap]
public String ReadOnlyProperty { get; set; }
Run Code Online (Sandbox Code Playgroud)
我不想使用特定于自动化程序的属性来弄脏类并使其依赖于它.另外,我不想在属性中添加其他ReadOnly属性.
CreateMap<Source, Destination>()
.ForSourceMember(src => src.ReadOnlyProperty, opt => opt.Ignore())
Run Code Online (Sandbox Code Playgroud)
这不是一种方式,因为它迫使我为每个地方的每一处房产做这件事,也造成很多重复.
Vin*_*kal 25
写扩展方法如下所示:
public static class IgnoreReadOnlyExtensions
{
public static IMappingExpression<TSource, TDestination> IgnoreReadOnly<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
foreach (var property in sourceType.GetProperties())
{
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(sourceType)[property.Name];
ReadOnlyAttribute attribute = (ReadOnlyAttribute) descriptor.Attributes[typeof(ReadOnlyAttribute)];
if(attribute.IsReadOnly == true)
expression.ForMember(property.Name, opt => opt.Ignore());
}
return expression;
}
}
Run Code Online (Sandbox Code Playgroud)
要调用扩展方法:
Mapper.CreateMap<ViewModel, DomainModel>().IgnoreReadOnly();
Dre*_*sel 11
现在您还可以使用ForAllPropertyMaps全局禁用它:
configure.ForAllPropertyMaps(map =>
map.SourceMember.GetCustomAttributes().OfType<ReadOnlyAttribute>().Any(x => x.IsReadOnly),
(map, configuration) =>
{
configuration.Ignore();
});
Run Code Online (Sandbox Code Playgroud)