使用 Automapper 忽略映射一项属性

发布于 2024-09-29 23:19:51 字数 461 浏览 0 评论 0原文

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

Mapper.CreateMap<OrderModel, Orders>(); 

它会生成异常:

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

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

我怎样才能避免 automapper来映射这个属性?

I'm using Automapper and I have the following scenario:
Class OrderModel has a property called 'ProductName' that isn't in the database.
So when I try to do the mapping with:

Mapper.CreateMap<OrderModel, Orders>(); 

It generates an exception :

"The following 1 properties on Project.ViewModels.OrderModel are not mapped: 'ProductName'

I've read at AutoMapper's Wiki for Projections the opposite case (the extra attribute is on the destination, not in the source which is actually my case )

How can I avoid automapper to make the mapping of this property?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

楠木可依 2024-10-06 23:19:51

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

它位于 他的博客中的评论之一

更新(摘自 Jamie 的评论,2019 年 1 月 4 日 11:11:)

ForSourceMember 中的“忽略”已替换为“DoNotValidate”:
https://github.com/AutoMapper/AutoMapper/blob /master/docs/8.0-Upgrade-Guide.md

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

It's in one of the comments at his blog.

UPDATE(from Jamie's comment Jan 4 '19 at 11:11:)

Ignore has been replaced with DoNotValidate in ForSourceMember:
https://github.com/AutoMapper/AutoMapper/blob/master/docs/8.0-Upgrade-Guide.md

永不分离 2024-10-06 23:19:51

我可能是一个有点完美主义者;我不太喜欢 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 一起使用,但我不喜欢带有负载的方法的外观拉姆达。

I'm perhaps a bit of a perfectionist; I don't really like the ForMember(..., x => x.Ignore()) syntax. It's a little thing, but it matters to me. I wrote this extension method to make it a bit nicer:

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;
}

It can be used like so:

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

You could also rewrite it to work with params, but I don't like the look of a method with loads of lambdas.

幻想少年梦 2024-10-06 23:19:51

您可以这样做:

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

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

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

You can do this:

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

Or, in latest version of Automapper, you simply want to tell Automapper to not validate the field

conf.CreateMap<SourceType, DestinationType>()
   .ForSourceMember(x => x.SourceProperty, y => y.DoNotValidate());
素年丶 2024-10-06 23:19:51

在 Automapper 12 中,有一个 Ignore 属性:
“忽略此成员进行配置验证并在映射期间跳过。”
[老的]
现在(AutoMapper 2.0)有一个 IgnoreMap 属性,我将使用它,而不是恕我直言有点重的流畅语法。

In Automapper 12, there's an Ignore attribute :
"Ignore this member for configuration validation and skip during mapping."
[Old]
There is now (AutoMapper 2.0) an IgnoreMap attribute, which I'm going to use rather than the fluent syntax which is a bit heavy IMHO.

倥絔 2024-10-06 23:19:51

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

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/

Just for anyone trying to do this automatically, you can use that extension method to ignore non existing properties on the destination type :

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;
}

to be used as follow :

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

thanks to Can Gencer for the tip :)

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

々眼睛长脚气 2024-10-06 23:19:51

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

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

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

When mapping a view model back to a domain model, it can be much cleaner to simply validate the source member list rather than the destination member list

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

Now my mapping validation doesn't fail, requiring another Ignore(), every time I add a property to my domain class.

梦里兽 2024-10-06 23:19:51

也可以像这样忽略全局属性:

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

用法:

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
});

It is also possible to ignore globally properties like this :

  1. Using the AddGlobalIgnore(string propertyNameStartingWith) method in the mapper configuration to ignore properties with name starting with a specified string.
  2. Using the ShouldMapProperty to provide a predicate and conditionally selecting which properties to map. ShouldMapField and ShouldMapMethod properties are also available.

Usage :

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"
    }
}

Or :

var config = new MapperConfiguration(cfg => {
    // other configs...
    cfg.AddGlobalIgnore("foo"); // way 1
    cfg.ShouldMapProperty = p => p.Name != "bar"; // way 2
});
时光磨忆 2024-10-06 23:19:51

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

Could use IgnoreAttribute on the property which needs to be ignored

揽月 2024-10-06 23:19:51

您可以使用属性:[IgnoreMap]
或映射器配置文件:

CreateMap<TollgateEto, UpdateTollgateModel>()
  .ForMember(x => x.QLX3_ID, opt => opt.Ignore());

you can use attribute: [IgnoreMap]
or mapper profile:

CreateMap<TollgateEto, UpdateTollgateModel>()
  .ForMember(x => x.QLX3_ID, opt => opt.Ignore());
心清如水 2024-10-06 23:19:51

大家好,请使用它,它工作正常...对于自动映射器,在 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;

Hello All Please Use this it's working fine... for auto mapper use multiple .ForMember in C#

        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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文