简体   繁体   English

如何让 AutoMapper:忽略非映射属性,包括常规映射并使用 QueryableExtensions

[英]How get AutoMapper to: ignore non mapped properties, include conventional mapping and work with QueryableExtensions

I've found two solution to ignore non mapped properties but one of them also ignore the conventional mappings, and the second doesn't work with QueryableExtensions to return an IQueryable (don't know why but I get the error Argument types do not match ).我找到了两种忽略非映射属性的解决方案,但其中一种也忽略了常规映射,而第二种解决方案不适用于QueryableExtensions以返回 IQueryable(不知道为什么,但我收到错误Argument types do not match )。

Does anyone has a solution to ignore non mapped properties that covers both aspects above?有没有人有解决方案可以忽略涵盖上述两个方面的非映射属性?

When using QueryableExtensions you have to be explicit with some type conversions, such as int?使用QueryableExtensions 时,您必须明确某些类型转换,例如int? to int .int This is probably the source of the "Argument types do not match" exception.这可能是“参数类型不匹配”异常的来源。

If you have many properties that need a type conversion -- like if you had many other properties where you find you are doing c.MyVariable ?? 0如果你有很多需要类型转换的属性——就像你有很多其他的属性,你发现你在做c.MyVariable ?? 0 c.MyVariable ?? 0 -- you can instead define a conversion rule and not have to be explicit about every property. c.MyVariable ?? 0 -- 您可以改为定义转换规则,而不必对每个属性都进行明确说明。

Normally, to do type conversions in Automapper, you would use ConvertUsing but when using QueryableExtensions, you need to instead use ProjectUsing .通常,要在 Automapper 中进行类型转换,您将使用ConvertUsing但在使用 QueryableExtensions 时,您需要使用ProjectUsing

You could use the following line and it will take care of all mappings from int?您可以使用以下行,它将处理来自int? to int without the need to explicitly specify the mappings for each property:int而无需明确指定每个属性的映射:

cfg.CreateMap<int?, int>().ProjectUsing(src => src.HasValue ? src.Value : 0);

Problem solved.问题解决了。 It was in this line of code它在这行代码中

.ForMember(p => p.Gender, opt => opt.MapFrom(c => c.GenderCode))

where p.Gender was of type int and GenderCode of type int?.其中 p.Gender 的类型为 int,而 GenderCode 的类型为 int?。 so changing to所以改成

.ForMember(p => p.Gender, opt => opt.MapFrom(c => c.GenderCode ?? 0))

fixed the problem.解决了这个问题。 What made it hard to troubleshoot is that the mapping code above was working until I try to return IQueryable.使故障排除变得困难的是,在我尝试返回 IQueryable 之前,上面的映射代码一直在工作。

Chaining at the end of the mapping with the .ForAllOtherMembers(opt => opt.Ignore());在映射末尾链接.ForAllOtherMembers(opt => opt.Ignore()); worked for me.为我工作。 This should be the last method in the method chain.这应该是方法链中的最后一个方法。

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

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