3

I'm not very familiar with AutoMapper but am trying to update AutoMapper 4 to AutoMapper 10 (last version to support .Net Framework) on a project, and I have run into a problem: The ResolutionContext changed in the 4-5 upgrade so that it no longer has a Parent property.

The existing code works with an attribute that is put on properties in the view model where zero is supposed to be treated as a null, and the existing type converter has this code in it:

var prop = context.Parent.Parent.DestinationType.GetProperty(context.MemberName);
var attributes = prop.GetCustomAttributes(false);
var zeroAttr = attributes.Where(a => a.GetType() == typeof(ZAttribute)).ToList();

But as of AutoMapper 5, ResolutionContext.Parent and ResolutionContext.Member no longer exists.

This allows mapping zero to null for any/all view model, as long as the property has the attribute, there doesn't need to a specific mapping for that type (I think that is how it works). If the attribute isn’t on the property the normal mapping is done (zero stays zero).

How can this be done with AutoMapper 10?

I'm thinking it might be some type of ValueResolver...

jmoreno
  • 12,752
  • 4
  • 60
  • 91
  • Migration aside, maybe try to explain from scratch _exactly_ what you're trying to do here. – Lucian Bargaoanu Aug 10 '22 at 03:27
  • @LucianBargaoanu: when mapping from one class to another, I want to be able to map a decimal/int to a nullable decimal/int with zero being treated as null. And do this via an attribute on the class and not by declaring a custom mapping by hand. Basically, be able to use an attribute to say use this conversion. – jmoreno Aug 10 '22 at 10:48
  • All you need is a custom type converter, that will apply everywhere. I don't see why you need the attribute. – Lucian Bargaoanu Aug 10 '22 at 10:51
  • @LucianBargaoanu: because I don’t want it to apply everywhere. Lots of classes don’t have this behavior at all, others have it only for specific properties. – jmoreno Aug 10 '22 at 11:55
  • Then you need to apply a resolver using `ForAllPropertyMaps`. – Lucian Bargaoanu Aug 10 '22 at 14:13
  • @LucianBargaoanu: if it makes any difference, I was a bit sloppy about where the attribute goes, it goes on the property that is to be mapped to zero instead of to null. – jmoreno Aug 10 '22 at 14:47
  • You probably mean on the source property instead of the destination property. It doesn't matter. – Lucian Bargaoanu Aug 10 '22 at 14:53

0 Answers0