Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to write an entity comparator in C# (with example code of first attempt)
    primarykey
    data
    text
    <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1092534/what-is-the-best-way-to-compare-two-entity-framework-entities">What is the best way to compare two entity framework entities?</a> </p> </blockquote> <p>I want to know the most efficient way of comparing two entities of the same type.</p> <p>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.</p> <p>I want to know if the property values are the same in each instance.</p> <p>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?</p> <p>Any suggestions would be welcome.</p> <p>Many thanks,</p> <p>James</p> <p>UPDATE</p> <p>I came up with this:</p> <pre><code>static class ObjectComparator&lt;T&gt; { 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&lt;PropertyInfo&gt;(pi =&gt; pi.Name == newProperty.Name); if (newProperty.GetValue(newObject, null) != oldProperty.GetValue(oldObject, null)) { return false; } } catch { return false; } } return true; } } } </code></pre> <p>I haven't tested it yet, it is more of a food for thought to generate some more ideas from the group.</p> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload