在AutoMapper中, MemberList.None选项被设置为不将源对象的成员映射到目标对象中。但是,即使使用了此选项,目标对象的属性仍会被绑定。这可能会导致不必要的属性赋值,从而影响性能。
要解决此问题,可以在AutoMapper的CreateMap方法中,使用ForMember方法来显式地将目标对象的属性忽略掉,如下所示:
CreateMap
使用Ignore方法显式地告诉AutoMapper忽略目标对象的属性,即使将MemberList.None选项设置为默认设置。
示例代码:
using AutoMapper;
class Program
{
static void Main(string[] args)
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap
var source = new Source { Id = 1, Name = "John", Email = "john@example.com" };
var destination = Mapper.Map(source);
}
}
class Source { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } }
class Destination { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } public string PropertyToIgnore { get; set; } }