【AutoMapper基础】值解析器--Custom value resolvers
【简介】:
虽然AutoMapper已经覆盖了大部分的映射场景,但是还有1%~5%的情况需要值解析器的帮助。
很多时候,值解析器实现的功能可以直接在实体层通过逻辑代码直接实现,然而,如果这种逻辑只是映射时需要,这就会混乱我们的源类型以及带来不必要的操作。
这种情况下,AutoMapper允许成员配置自定义值解析器以达到想要的效果。
【示例】
接上例:【AutoMapper基础】简单示例--Flatenning
如果computer中有多个InternalMemory,那么在ComputerMainInfo中要取得InternalMemorySize时就需要将所有的InternalMemory的Size相加。
【类图】
【Code】
Computer:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Computer { public string Name { get; set; } public double Price { get; set; } public DateTime ProduceDate { get; set; } public CPU CPU { get; set; } public List<InternalMemory> InternalMemories { get; set; } public Monitor Monitor { get; set; } }
值解析器CustomResolver:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class CustomResolver : ValueResolver<Computer, double> { protected override double ResolveCore(Computer source) { double totalSize = 0.0; foreach (var item in source.InternalMemories) { totalSize += item.Size; } return totalSize; } }
Program:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Program { static void Main(string[] args) { Computer computer = new Computer() { Name = "联想Y450", Price = 5199.00, ProduceDate = new DateTime(2009, 10, 10), CPU = new CPU() { MainFrequency = 2.2, ModelName = "Core T6600", ProducerName = "Intel" }, InternalMemories = new List<InternalMemory>(){ new InternalMemory() { Frequency = 1333, ModelName = "DDR3", ProducerName = "尔必达", Size = 4.0 }, new InternalMemory() { Frequency = 1333, ModelName = "DDR3", ProducerName = "尔必达", Size = 4.0 } }, Monitor = new Monitor() { ProducerName = "LG", Size = 14.0 } }; // 添加值解析器映射 AutoMapper.Mapper.CreateMap<Computer, ComputerMainInfo>().ForMember(dest => dest.InternalMemorySize, opt => opt.ResolveUsing<CustomResolver>() ); ComputerMainInfo computerMainInfo = AutoMapper.Mapper.Map<Computer, ComputerMainInfo>(computer); Console.WriteLine(computerMainInfo.CPUModelName); Console.WriteLine(computerMainInfo.InternalMemorySize); Console.Read(); } }
这样通过值解析器就能计算出内存的总大小了。
请注明文章出处[http://www.cnblogs.com/fb-boy/]