我想使用自动映射器在我的公共(public)数据契约(Contract)和我的数据库模型之间进行映射。我创建了一个类,它自动遍历所有契约(Contract)并创建映射。我遇到的唯一问题是,如果值不为空,我只想将值从契约(Contract)映射到数据库模型。我在这里查看了其他问题,但看不到使用自定义解析器的示例。
这是我的一些代码
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 .
关于c# - 使用自定义解析器跳过空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20021633/