One way is to simply hand code one assignment statement for each field they have in common.
Another option is to use an open source mapping library like AutoMapper.
Still other times you might find yourself in the middle ground of not wanting to hand code all the assignments and also not wanting to deal with a 3rd party library.
Here is an example of how you can roll your own automapper in a few lines of code. This snippet copies like-named properties from a source to a target. It recurses on any properies that don't have a type starting with "System." and it ignores source properties with value of null.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void CopyProperties(object sourceObject, object targetObject, bool deepCopy = true) | |
{ | |
if (sourceObject != null && targetObject != null) | |
{ | |
(from sourceProperty in sourceObject.GetType().GetProperties().AsEnumerable() | |
from targetProperty in targetObject.GetType().GetProperties().AsEnumerable() | |
where sourceProperty.Name.ToUpper() == targetProperty.Name.ToUpper() | |
let sourceValue = sourceProperty.GetValue(sourceObject, null) | |
where sourceValue != null | |
select CopyProperty(targetProperty, targetObject, sourceValue, deepCopy)) | |
.ToList() | |
.ForEach(c => c()); | |
} | |
} | |
static Action CopyProperty(PropertyInfo propertyInfo, object targetObject, object sourceValue, bool deepCopy) | |
{ | |
if (!deepCopy || sourceValue.GetType().FullName.StartsWith("System.")) | |
return () => propertyInfo.SetValue(targetObject, sourceValue, null); | |
else | |
return () => CopyProperties(sourceValue, propertyInfo.GetValue(targetObject, null)); | |
} |
No comments:
Post a Comment