New Posts New Posts RSS Feed: Overriding GetHashCode / Equals of Entity
  FAQ FAQ  Forum Search   Calendar   Register Register  Login Login

Overriding GetHashCode / Equals of Entity

 Post Reply Post Reply
Author
smi-dan View Drop Down
Newbie
Newbie


Joined: 26-Jan-2011
Location: Dallas, Texas
Posts: 3
Post Options Post Options   Quote smi-dan Quote  Post ReplyReply Direct Link To This Post Topic: Overriding GetHashCode / Equals of Entity
    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.


Edited by smi-dan - 20-Aug-2013 at 10:13am
Back to Top
kimj View Drop Down
IdeaBlade
IdeaBlade
Avatar

Joined: 09-May-2007
Posts: 1391
Post Options Post Options   Quote kimj Quote  Post ReplyReply Direct Link To This Post 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.
Back to Top
 Post Reply Post Reply

Forum Jump Forum Permissions View Drop Down