我想使用automapper在我的公共数据协定和我的数据库模型之间进行映射.我创建了一个自动完成所有契约的类创建映射.我唯一的问题是,如果值不为null,我只想将合约中的值映射到数据库模
这是我的一些代码
var mapToTarget = AutoMapper.Mapper.CreateMap(contract, mappedTo); foreach (var property in contract.GetProperties().Where(property => property.CustomAttributes.Any(a => a.AttributeType == typeof(MapsToProperty)))) { var attribute = property.GetCustomAttributes(typeof(MapsToProperty), true).FirstOrDefault() as MapsToProperty; if (attribute == null) continue; mapToTarget.ForMember(attribute.MappedToName, opt => opt.ResolveUsing<ContractToSourceResolver>() .ConstructedBy(() => new ContractToSourceResolver(new MapsToProperty(property.Name, attribute.SourceToContractMethod, attribute.ContractToSourceMethod)))); } private class ContractToSourceResolver : ValueResolver<IDataContract, object> { private MapsToProperty Property { get; set; } public ContractToSourceResolver(MapsToProperty property) { Property = property; } protected override object ResolveCore(IDataContract contract) { object result = null; if (Property.ContractToSourceMethod != null) { var method = contract.GetType() .GetMethod(Property.ContractToSourceMethod, BindingFlags.Public | BindingFlags.Static); result = method != null ? method.Invoke(null, new object[] {contract}) : null; } else { var property = contract.GetType().GetProperties().FirstOrDefault(p => p.Name == Property.MappedToName); if (property != null) { result = property.GetValue(contract); } } return result; } }
这就是我想要使用它的方式
AutoMapper.Mapper.Map(dataContract, dbModel)
这当前工作得很好,但如果dataContract中有一个NULL值,那么它将替换dbModel中的现有值,这不是我想要的.如何使AutoMapper忽略空源值?
编辑
正如其中一个答案所指出的那样
Mapper.CreateMap<SourceType, DestinationType>().ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));
这是理想的,除了.ForAllMembers无法访问的事实
Mapper.CreateMap(SourceType, DestinationType)更新:IsSourceValueNull是 not available starting from V5.
如果希望忽略具有空值的所有源属性,则可以使用:
Mapper.CreateMap<SourceType, DestinationType>() .ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));
否则,您可以为每个成员执行类似的操作.
阅读this.