在这篇文章中,我将向你展示如何通过AutoMapper自动映射来忽略属性。假设源和目标都有一个同名的属性,但用于表示不同的信息,那么我们肯定不希望自动映射该属性。我们可以在AutoMapper中创建映射时进行如下配置。
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Source, Destination>().ForMember(x =>x.DestinationPropertyName, opt => opt.Ignore());
});
示例:
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Person, PersonVM>().ForMember(x =>x.Name, opt => opt.Ignore());
});
由于AutoMapper支持FluentAPI,如果忽略多个属性,则可以多次调用FormMember方法,代码如下:
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Foo, FooCopy>()
.ForMember(x =>x.Name, opt => opt.Ignore())
.ForMember(x => x.Age , opt => opt.Ignore() );
});
完整代码示例:
using System;
using AutoMapper;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string Email { get; set; }
}
public class PersonVM
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Person, PersonVM>().ForMember(x =>x.Name, opt => opt.Ignore());
});
IMapper mapper = config.CreateMapper();
var person = new Person { Name="test", Age=10, Email = "[email protected]", Address="Test Address" };
var personVM = mapper.Map<PersonVM>(person);
Console.WriteLine("\nperson.Name : {0} \nperson.Age : {1} \nperson.Address : {2} \nperson.Email : {3}", person.Name, person.Age, person.Email, person.Address);
Console.WriteLine("\npersonVM.Name : {0} \npersonVM.Age : {1} ", personVM.Name, personVM.Age);
}
}
输出:
person.Name : test
person.Age : 10
person.Address : [email protected]
person.Email : Test Address
personVM.Name :
personVM.Age : 10
下一篇 忽略大量映射属性
https://blog.csdn.net/hefeng_aspnet/article/details/124754933