如何忽略标记为虚拟的所有属性

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)

  • 请注意,接口中定义的属性始终是虚拟的.一种解决方案是将`!p.GetGetMethod().IsFinal`添加到`Where`谓词.http://stackoverflow.com/a/4793253/941764 (7认同)

Ale*_*xei 5

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)