假设我们有两个类,一个是源类,一个是目标类,每个类中都有一个集合属性。
源类:
public class Source
{
public List List1 { get; set; }
public List List2 { get; set; }
}
目标类:
public class Destination
{
public List List3 { get; set; }
public List List4 { get; set; }
}
我们可以使用Automapper或Mapster来将“Source”类的集合属性映射到“Destination”类的集合属性。
对于Automapper,我们可以使用“ForMember”方法来指定如何映射特定成员的值。此方法需要指定目标成员的名称和一个Lambda表达式,该表达式返回一个新的值。在此Lambda表达式内部,我们可以使用LINQ查询从Source.List1或Source.List2中选择元素,并将其映射到Destination.List3或Destination.List4。
使用Automapper进行映射:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap()
.ForMember(dest => dest.List3, opt => opt.MapFrom(src => src.List1.Where(x => x > 5)))
.ForMember(dest => dest.List4, opt => opt.MapFrom(src => src.List2));
});
var mapper = config.CreateMapper();
var source = new Source { List1 = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, List2 = new List { 10, 11, 12 } };
var destination = mapper.Map(source);
对于Mapster,我们可以使用“MapTo”方法来指定如何映射到特定的属性。此方法需要指定目标成员的名称和一个Lambda表达式,该表达式返回一个新的值。在此Lambda表达式内部,我们可以使用LINQ查询从Source
上一篇:AutoMapper.ProjectTo与条件查询被本地评估
下一篇:AutoMapper10.0或AutoMapper.Data5.0现在在AddDataReaderMapping调用时会抛出InvalidOperationException。