c# - 使用自定义解析器跳过空值

标签 c# automapper

我想使用自动映射器在我的公共(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/

相关文章:

c# - float/double/decimal 中的精度数字是什么意思?

c# - 当 source 上的属性为 false 时是否可以映射到 null?

c# - 在 C++ 中正确返回 uint16_t 数组的方法

c# - LINQtoCSV |如何在 CSV 文件末尾写入文本

数据库未在客户端系统上运行的 C# Windows 窗体应用程序

c# - 嵌套类中的 Automapper 映射成员

c# - 在 ASP.NET MVC 中将 AutoMapper QueryableExtensions 与 Entity Framework 一起使用会导致 "Operation could destabilize the runtime"异常

c# - 修改模型时的 ASP.NET MVC TryValidateModel() 问题

c# - 如何为 .net 3.5 安装 Automapper

c# - AutoMapper:为没有映射的嵌套属性设置引用