Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 587
James Avatar asked Jul 07 '09 14:07

James


People also ask

How do you compare two entities?

The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)

How to compare two entities in c#?

The most common way to compare objects in C# is to use the == operator. For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object.


1 Answers

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
    }
like image 154
Mark Dickinson Avatar answered Nov 12 '22 20:11

Mark Dickinson