Since I've settled on EF4, I've gone through and reworked a lot of things, including my base entity. I dropped a lot of things from my old one based on comments here about domain equality, but have a question about hash codes. Below is my current rewrite. I am satisfied with everything as-is, but was wondering if there were any reason to do more with GetHashCode?
Code Csharp:namespace Genesis.Infrastructure.Domain { /// <summary> /// Entity base class. /// </summary> /// <typeparam name="T">Type of the Id prpoerty.</typeparam> public abstract class Entity<T> { /// <summary> /// The Id property, settable only by the orm. /// </summary> public T Id { get; protected set; } /// <summary> /// Determines if the entity is transient or not. /// </summary> public bool IsTransient { get { return Id.Equals(default(T)); } } /// <summary> /// Performs domain comparison on the supplied entity. /// </summary> /// <param name="obj">The entity to compare to.</param> /// <returns>bool</returns> public override bool Equals(object obj) { // return true if reference is the same if (ReferenceEquals(this, obj)) return true; // return true if the Id is the same if (Equals(this.Id, (obj as Entity<T>).Id)) return true; // resort to default return Equals(this, obj); } /// <summary> /// Returns the hash code for this entity. /// </summary> /// <returns>int</returns> public override int GetHashCode() { // resort to default return base.GetHashCode(); } /// <summary> /// Compares two entities. /// </summary> /// <param name="primary">The left-side entity.</param> /// <param name="secondary">The right-side entity.</param> /// <returns>bool</returns> public static bool operator ==(Entity<T> primary, Entity<T> secondary) { // use our custom Equals method return primary.Equals(secondary); } /// <summary> /// Compares two entities. /// </summary> /// <param name="primary">The left-side entity.</param> /// <param name="secondary">The right-side entity.</param> /// <returns>bool</returns> public static bool operator !=(Entity<T> primary, Entity<T> secondary) { // use our custom Equals method return !primary.Equals(secondary); } } }







Bookmarks