Adr*_*tov 8 .net c# automapper
我使用virtual关键字为我的一些属性EF延迟加载.我有一个案例,virtual在将源映射到目标时,应该从AutoMapper中忽略我的模型中标记为的所有属性.
是否有自动方式可以实现此目的,还是应该手动忽略每个成员?
小智 28
您可以创建映射扩展并使用它:
namespace MywebProject.Extensions.Mapping
{
public static class IgnoreVirtualExtensions
{
public static IMappingExpression<TSource, TDestination>
IgnoreAllVirtual<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> expression)
{
var desType = typeof(TDestination);
foreach (var property in desType.GetProperties().Where(p =>
p.GetGetMethod().IsVirtual))
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
return expression;
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
Mapper.CreateMap<Source,Destination>().IgnoreAllVirtual();
Run Code Online (Sandbox Code Playgroud)
inquisitive的答案很好用,但是当从数据模型到服务模型执行某些映射并且应忽略源类型的虚拟成员时,可以将其用于现实生活中。
同样,如果该类型实现某些接口,则这些属性将显示为虚拟,因此!IsFinal必须添加条件以删除这些错误的肯定虚拟属性。
public static class AutoMapperExtensions
{
public static IMappingExpression<TSource, TDestination> IgnoreAllDestinationVirtual<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var desType = typeof(TDestination);
foreach (var property in desType.GetProperties().Where(p => p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal))
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
return expression;
}
public static IMappingExpression<TSource, TDestination> IgnoreAllSourceVirtual<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var srcType = typeof(TSource);
foreach (var property in srcType.GetProperties().Where(p => p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal))
{
expression.ForSourceMember(property.Name, opt => opt.Ignore());
}
return expression;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4250 次 |
| 最近记录: |