Print Page | Close Window

Overriding GetHashCode / Equals of Entity

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2012
Forum Discription: For .NET 4.5
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=4284
Printed Date: 25-May-2025 at 8:57am


Topic: Overriding GetHashCode / Equals of Entity
Posted By: smi-dan
Subject: Overriding GetHashCode / Equals of Entity
Date Posted: 20-Aug-2013 at 10:11am
We have some projections that return an entity as a property. When grouping on those properties, despite the entity being the same, it will group based on reference and so we end up with two groups for what is the same entity. 

As a solution I've overridden GetHashCode and Equals on the entity with;

        public override int GetHashCode()
        {
            return DealerId == 0 ? base.GetHashCode() : DealerId.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            var x = obj as Dealer;
            if (x == null) 
                return false;

            if (DealerId == 0 && x.DealerId == 0) 
                return ReferenceEquals(this, x);

            return DealerId == x.DealerId;
        }

Which works fine, however, is there another solution? As this solution would require I override these methods for all entities in my model.



Replies:
Posted By: kimj
Date Posted: 20-Aug-2013 at 12:58pm
I'm not sure I understand in what situations reference equality wouldn't be appropriate for an entity, unless you're working across EntityManagers.  But anyway, GroupBy accepts an IEqualityComparer, so you could implement a simple comparer which uses the EntityKey to determine equality.



Print Page | Close Window