繁体   English   中英

忽略使用 Automapper 映射一个属性

[英]Ignore mapping one property with Automapper

我正在使用 Automapper 并且我有以下场景: Class OrderModel 有一个名为“ProductName”的属性,该属性不在数据库中。 因此,当我尝试使用以下方法进行映射时:

Mapper.CreateMap<OrderModel, Orders>(); 

它产生一个异常:

“Project.ViewModels.OrderModel 上的以下 1 个属性未映射:'ProductName'

我已经在AutoMapper 的 Wiki 上阅读了相反的情况(额外的属性在目标上,而不是在源中,这实际上是我的情况)

如何避免使用 automapper 来映射此属性?

来自 Jimmy Bogard: CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());

在他博客的评论之一中

我可能有点完美主义者; 我真的不喜欢ForMember(..., x => x.Ignore())语法。 这是一件小事,但对我来说很重要。 我写了这个扩展方法让它更好一点:

public static IMappingExpression<TSource, TDestination> Ignore<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> map,
    Expression<Func<TDestination, object>> selector)
{
    map.ForMember(selector, config => config.Ignore());
    return map;
}

它可以像这样使用:

Mapper.CreateMap<JsonRecord, DatabaseRecord>()
        .Ignore(record => record.Field)
        .Ignore(record => record.AnotherField)
        .Ignore(record => record.Etc);

您也可以重写它以使用params ,但我不喜欢带有大量 lambda 表达式的方法的外观。

你可以这样做:

conf.CreateMap<SourceType, DestinationType>()
   .ForSourceMember(x => x.SourceProperty, y => y.Ignore());

或者,在最新版本的 Automapper 中,您只想告诉 Automapper 不验证该字段

conf.CreateMap<SourceType, DestinationType>()
   .ForSourceMember(x => x.SourceProperty, y => y.DoNotValidate());

现在有(AutoMapper 2.0)一个IgnoreMap属性,我将使用它而不是流利的语法,恕我直言有点沉重。

对于尝试自动执行此操作的任何人,您可以使用该扩展方法忽略目标类型上不存在的属性:

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var sourceType = typeof(TSource);
    var destinationType = typeof(TDestination);
    var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
        && x.DestinationType.Equals(destinationType));
    foreach (var property in existingMaps.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}

使用如下:

Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting();

感谢 Can Gencer 的提示:)

来源: http : //cangencer.wordpress.com/2011/06/08/auto-ignore-non-existing-properties-with-automapper/

将视图模型映射回域模型时,只需验证源成员列表而不是目标成员列表会更简洁

Mapper.CreateMap<OrderModel, Orders>(MemberList.Source); 

现在我的映射验证不会失败,每次我向域类添加属性时都需要另一个Ignore()

可以在需要忽略的属性上使用 IgnoreAttribute

大家好,请使用这个它工作正常......对于自动映射器在 C# 中使用多个.ForMember

        if (promotionCode.Any())
        {
            Mapper.Reset();
            Mapper.CreateMap<PromotionCode, PromotionCodeEntity>().ForMember(d => d.serverTime, o => o.MapFrom(s => s.promotionCodeId == null ? "date" : String.Format("{0:dd/MM/yyyy h:mm:ss tt}", DateTime.UtcNow.AddHours(7.0))))
                .ForMember(d => d.day, p => p.MapFrom(s => s.code != "" ? LeftTime(Convert.ToInt32(s.quantity), Convert.ToString(s.expiryDate), Convert.ToString(DateTime.UtcNow.AddHours(7.0))) : "Day"))
                .ForMember(d => d.subCategoryname, o => o.MapFrom(s => s.subCategoryId == 0 ? "" : Convert.ToString(subCategory.Where(z => z.subCategoryId.Equals(s.subCategoryId)).FirstOrDefault().subCategoryName)))
                .ForMember(d => d.optionalCategoryName, o => o.MapFrom(s => s.optCategoryId == 0 ? "" : Convert.ToString(optionalCategory.Where(z => z.optCategoryId.Equals(s.optCategoryId)).FirstOrDefault().optCategoryName)))
                .ForMember(d => d.logoImg, o => o.MapFrom(s => s.vendorId == 0 ? "" : Convert.ToString(vendorImg.Where(z => z.vendorId.Equals(s.vendorId)).FirstOrDefault().logoImg)))
                .ForMember(d => d.expiryDate, o => o.MapFrom(s => s.expiryDate == null ? "" : String.Format("{0:dd/MM/yyyy h:mm:ss tt}", s.expiryDate))); 
            var userPromotionModel = Mapper.Map<List<PromotionCode>, List<PromotionCodeEntity>>(promotionCode);
            return userPromotionModel;
        }
        return null;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM