忽略使用 Automapper 映射一个属性

问题描述 投票:0回答:9

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

Mapper.CreateMap<OrderModel, Orders>(); 

它生成一个异常:

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

我在 AutoMapper's Wiki for Projections 中读到了相反的情况(额外的属性位于目标上,而不是在源中,这实际上是我的情况)

如何避免自动映射器对该属性进行映射?

c# model viewmodel automapper object-object-mapping
9个回答
654
投票
来自吉米·博加德:

CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());


它在

他博客的一条评论中

更新(摘自

Jamie 2019 年 1 月 4 日 11:11 的评论:)

ForSourceMember 中的
Ignore 已替换为

DoNotValidatehttps://github.com/AutoMapper/AutoMapper/blob/master/docs/8.0-Upgrade-Guide.md


280
投票
我可能是一个有点完美主义者;我不太喜欢

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 的方法的外观。


97
投票
你可以这样做:

conf.CreateMap<SourceType, DestinationType>() .ForSourceMember(x => x.SourceProperty, y => y.Ignore());
或者,在最新版本的 Automapper 中,您只是想告诉 Automapper 不要验证该字段

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

34
投票
在 Automapper 12 中,有一个 Ignore 属性: “忽略此成员进行配置验证并在映射期间跳过。” [老的] 现在(AutoMapper 2.0)有一个

IgnoreMap

 属性,我将使用它,而不是恕我直言,它有点重的流畅语法。


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

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/


30
投票
将视图模型映射回域模型时,简单地验证源成员列表而不是目标成员列表会更干净

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

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

Ignore()


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


2
投票
也可以忽略这样的全局属性:

    在映射器配置中使用
  1. AddGlobalIgnore(string propertyNameStartingWith)
     方法来忽略名称以指定字符串开头的属性。
  2. 使用
  3. ShouldMapProperty
     提供谓词并有条件地选择要映射的属性。 
    ShouldMapField
    ShouldMapMethod
     属性也可用。
用途:

public class MappingProfile : Profile { public MappingProfile() { // other configs... AddGlobalIgnore("foo")); // this will ignore properties with name starting with "foo" ShouldMapProperty = p => p.Name != "bar"; // this will ignore properties with name "bar" } }
或者:

var config = new MapperConfiguration(cfg => { // other configs... cfg.AddGlobalIgnore("foo"); // way 1 cfg.ShouldMapProperty = p => p.Name != "bar"; // way 2 });
    

-5
投票
大家好,请使用它,它工作正常...对于自动映射器,在 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;
    
© www.soinside.com 2019 - 2024. All rights reserved.