Automapper - simplest option to write only to destination property if original property is different?

NOTE. The script uses 2 entity framework models to synchronize data between two databases, but I would suggest that this applies to other scenarios. You can try to solve this on the EF side as well (for example, this SO question ), but I wanted to see if AutoMapper can handle this out of the box

I am trying to find out if AutoMapper can (easily :) compare source and dest values ​​(when used to synchronize with an existing object) and only make a copy if the values ​​are different (based on Equals by default, potentially passing Func, as if I would decide to do String.Equals with StringComparison.OrdinalIgnoreCase for some specific pair of values). At least for my scenario, I am fine if it is limited only to the case TSource == TDest (I will synchronize by int, string, etc., so I don’t think I need any type converters)

Looking through samples and tests, the closest thing seems to be conditional matching (src \ UnitTests \ ConditionalMapping.cs), and I would use a state overload that accepts Func (since another overload is not enough, since we need information about the destruction too). It certainly looks at first glance as if it will work fine (I have not used it yet), but in the end I will clarify this for each member (although I assume that I can define a small number of actions / methods and at least least reuse them instead of having N different lambda).

Is this the easiest route available (with the exception of changing AutoMapper) to get "a single copy if the source and destination values ​​are different", or is there another way I don’t see? If this is the easiest route, has it been done before elsewhere? Of course, it looks like I'm probably reinventing the wheel here. :)

+3
source share
1 answer

Chuck Norris (formerly known as Omu? :) already answered this, but through comments, so he simply answered and accepted the repetition of what he said.

@James , return c.SourceProp.Name = c.TargetProp.Name && c.SourceProp.Value!= c.TargetProp.Value target.InjectFrom(source);

, , EF4, , ( ), "" - Automapper ValueInject - .:)

, , *.tt , ( , ) , , :

if (ef.IsKey(primitiveProperty))

:

if (ef.IsKey(primitiveProperty) || true) // we always want the setter to include checking for the target value already being set
0

Source: https://habr.com/ru/post/1794142/


All Articles