What is the best way to compare two entity framework entities?

comparison entity-framework

Question

I want to know the most efficient way of comparing two entities of the same type.

One entity is created from an xml file by hand ( ie new instance and manually set properties) and the other is retvied from my object context.

I want to know if the property values are the same in each instance.

My first thoughts are to generate a hash of the property values from each object and compare the hashes, but there might be another way, or a built in way?

Any suggestions would be welcome.

Many thanks,

James

UPDATE

I came up with this:

static class ObjectComparator<T>
{
    static bool CompareProperties(T newObject, T oldObject)
    {
        if (newObject.GetType().GetProperties().Length != oldObject.GetType().GetProperties().Length)
        {
            return false;
        }
        else
        {
            var oldProperties = oldObject.GetType().GetProperties();

            foreach (PropertyInfo newProperty in newObject.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo oldProperty = oldProperties.Single<PropertyInfo>(pi => pi.Name == newProperty.Name);

                    if (newProperty.GetValue(newObject, null) != oldProperty.GetValue(oldObject, null))
                    {
                        return false;
                    }
                }
                catch
                {
                    return false;
                }
            }

            return true;
        }
    }
}

I haven't tested it yet, it is more of a food for thought to generate some more ideas from the group.

One thing that might be a problem is comparing properties that have entity values themselves, if the default comparator compares on object reference then it will never be true. A possible fix is to overload the equality operator on my entities so that it compares on entity ID.

Popular Answer

Override the Equals method of your object and write an implementation that compares the properties that make it equal.

    public override bool Equals(object obj)
    {
        return MyProperty == ((MyObject)obj).MyProperty
    }


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why