How would we achieve mapping all properties in one object to others by using expression trees instead of reflection? what would be the alternatives for the following snippet?
public class Mapper<TSource, TDestination> where TDestination : new()
{
protected virtual void CopyMatchingProperties(TSource source, TDestination destination)
{
foreach (var destProp in typeof(TDestination).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite))
{
var sourceProp = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.Name == destProp.Name && p.PropertyType == destProp.PropertyType).FirstOrDefault();
if (sourceProp != null)
{
destProp.SetValue(destination, sourceProp.GetValue(source, null), null);
}
}
}
public virtual TDestination MapObject(TSource source, TDestination destination)
{
CopyMatchingProperties(source, destination);
return destination;
}
public virtual TDestination CreateMappedObject(TSource source)
{
TDestination destination = new TDestination();
return MapObject(source, destination);
}
}
Aucun commentaire:
Enregistrer un commentaire