Skip to content

Instantly share code, notes, and snippets.

@HakanL
Created April 19, 2017 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HakanL/95fa3f8f7313ef563b9c0e7afca50ef1 to your computer and use it in GitHub Desktop.
Save HakanL/95fa3f8f7313ef563b9c0e7afca50ef1 to your computer and use it in GitHub Desktop.
Property setting for Data Model/Business Object transformations with dirty/modified tracking
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Haukcode.DataAccess.Util
{
internal static class PropertyHelper
{
public static void Set<T, TProp>(T target, Expression<Func<T, TProp>> memberLamda, TProp sourceValue, ref bool isDirty)
{
Set(target, memberLamda, sourceValue, (a, b) =>
{
if (b == null && a == null)
return true;
if ((b == null && a != null) || !b.Equals(a))
return false;
return true;
}, ref isDirty);
}
public static void Set<T, TProp>(T target, Expression<Func<T, TProp>> memberLamda, TProp sourceValue, Func<TProp, TProp, bool> comparer, ref bool isDirty)
{
var memberSelectorExpression = memberLamda.Body as MemberExpression;
if (memberSelectorExpression != null)
{
var property = memberSelectorExpression.Member as PropertyInfo;
if (property != null)
{
var targetValue = (TProp)property.GetValue(target);
if (!comparer(sourceValue, targetValue))
{
// Changed
property.SetValue(target, sourceValue, null);
isDirty = true;
}
}
else
throw new ArgumentException("Invalid property type");
}
else
throw new ArgumentException("Invalid property");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment