0

I would like to compare two LINQ entities of the same type and return a list differences between the two. I have code that compares properties and returns the differences.

(from: https://stackoverflow.com/a/5812100/2343826)

    public static void WriteChanges<T>(T obj1, T obj2, string objName, int objId, int userId)
    {
        PropertyInfo[] properties = typeof(T).GetProperties();
        StringBuilder sb = new StringBuilder();

        foreach (PropertyInfo pi in properties)
        {
            object value1 = typeof(T).GetProperty(pi.Name).GetValue(obj1, null);
            object value2 = typeof(T).GetProperty(pi.Name).GetValue(obj2, null);

            if (value1 != value2 && (value1 == null || !value1.Equals(value2)))
            {
                sb.Append(string.Format("Property {0} changed from {1} to {2}" + Environment.NewLine, pi.Name, value1, value2));
            }
        }
        Write(objName, objId, sb.ToString(), userId);
    }

Results IN:

Property oItem changed from NS.oItem to NS.oItem
Property dvPC changed from pcName1 to pcName2

Can this code be modified to determine if the property is also a LINQ entity and if so recursively check the child entity for differences?

For instance, in the example results above, NS.oItem is a child entity associated to obj1. I would like the method to iterate through the child object to compare the differences in it between obj1 and obj2

Thanks for your help

Fraze
  • 908
  • 2
  • 8
  • 20
  • You can use that method in your Linq Expression. I couldn't figure out your problem properly. Would you provide some code please ? – lucky Nov 15 '17 at 19:30
  • hi @Rainman - thanks for your willingness... I've altered my question above to be more concise. Let me know.. Thanks again! – Fraze Nov 15 '17 at 19:55

1 Answers1

0

You can do that, but mixing templates and reflection makes it unnecessarily complex - I'd re-write this as a non-template function, it can just take two variables of type object and fail up-front if they're not of the same type. I'm not sure why you need to check whether a property "is" a LINQ entity (which doesn't really make sense - do you mean, is mapped to an Entity Framework entity? But do you need to prevent infinite recursion where an object of type A has a property of type B, which also has a property of type A. (this is not uncommon with EF entities in order to capture foreign-key relationships - and not recursing for any property with a ForeignKey annotation is probably what you want).

Dylan Nicholson
  • 1,301
  • 9
  • 23