Created
January 23, 2017 21:34
-
-
Save ajai8085/d3727dc444ae6acf410e41f57f1c9ae1 to your computer and use it in GitHub Desktop.
Shallow Copy public properties between unrelated objects which has same property name , this can also copy the fields from derived class to base class and maintain a pure base class object . (useful when passing parameter to dapper)
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
public static void CopyMatchingProperties<TResult, TInput>(this TInput input, TResult result) | |
where TResult : class | |
where TInput : class | |
{ | |
var properties = typeof(TResult).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); | |
var propertiesInput = typeof(TInput).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); | |
properties.ForEach(p => | |
{ | |
var value = p.GetValue(input); | |
//if (value != null) | |
{ | |
var pdest = | |
propertiesInput.FirstOrDefault(i => i.Name.Equals(p.Name) && p.PropertyType == i.PropertyType); | |
if (pdest != null) | |
{ | |
pdest.SetValue(result, value); | |
} | |
} | |
}); | |
} | |
public static TEntity CopyPropertisToNewInstance<TEntity>(this TEntity input) | |
where TEntity : class, new() | |
{ | |
var result = new TEntity(); | |
input.CopyMatchingProperties(result); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment