This project has moved and is read-only. For the latest updates, please go here.

Should you override GetHashCode for equality/comparison

Nov 27, 2011 at 11:12 AM

I'm having the following problem with SterlingDB:

  • I save an instance of Person with Id 1 (I'm actually using Guids, but this is easier)
  • In another view, I create two instances of Order.
  • Order has a Person-property, which I set to the Person I created earlier, for both instances
  • I save these instances
  • Now, when I retrieve them again later, I can see both Orders have a Person property with the same Id (1), but a different result for GetHashCode()

The problem is that for LINQ (and other operations), these two Person instances will be different. But in my SterlingDB, there still is only one Person.

Is this normal behavior, and thus, should I override GetHashCode? I believe so, but wanted to check if this is the way to go.

If this is indeed the way to go, should I always override GetHashCode when using SterlingDB?

Dec 1, 2011 at 2:43 PM

I should add to that only overriding GetHashCode won't work. I suspect I'll also need to override Equals, as found on StackOverflow. I'll see if I have time to implement this tonight and post the answer here.

Dec 13, 2011 at 8:02 AM
Edited Dec 13, 2011 at 8:03 AM

That did the trick for me: override GetHashCode and Equals. Luckily, I had a BaseEntity that all other entities inherit from:


	public abstract class BaseEntity
		public BaseEntity()
			Id = Guid.NewGuid();

		public Guid Id { get; set; }
	        public override int GetHashCode()
	            return Id.GetHashCode();
	        public override bool Equals(object obj)
	            var entity = obj as BaseEntity;
	            if (entity == null) return false;
	            if (entity.GetType() == GetType())
	                return entity.Id == Id;
	            return false;