让AutoMapper的Map忽略一些属性?

时间:2015-08-04 14:12:39

标签: c# automapper

我的模型对象具有延迟加载集合的一些属性,而AutoMapper用于加载这些集合,即使我不需要它们(这导致我的数据库中有数千个查询执行)。当我调用Mapper.Map时,是否可以让AutoMapper忽略一些属性?

public TTarget Adapt<TSource, TTarget>(TSource source)
{
    return Mapper.Map<TTarget>(source);
}

3 个答案:

答案 0 :(得分:4)

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }    
}

public class Doctor
{
    public int Id { get; set; }
    public string Name { get; set;}
}

以下是我如何使用Automapper忽略属性(我已经在源和目标对象中包含了如何忽略它们):

Mapper.CreateMap<Person, Doctor>()
      .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.LastName))
      .ForMember(dest => dest.Id, opt => opt.Ignore())
      .ForSourceMember(src=> src.FirstName, opt => opt.Ignore());

答案 1 :(得分:2)

Mapper.CreateMap<SourceClass, DestinationClass>()
                .ForMember(b=>b.SomeMember, c=>c.Ignore());

答案 2 :(得分:1)

使用AutoMapper 8.0,@ Prabu的答案不再起作用。

8.0 Upgrade Guide - ForSourceMember Ignore

因此调整后的答案将是:

Mapper.CreateMap<Person, Doctor>()
      .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.LastName))
      .ForMember(dest => dest.Id, opt => opt.Ignore())
      .ForSourceMember(src=> src.FirstName, opt => opt.DoNotValidate());