Setting up a base entity class
In this recipe, we'll show how to set up a base class for your entities. The purpose of this class is to provide base implementations of potentially tricky Equals
and GetHashCode
methods.
How to do it…
We create a base class, where the type of
Id
is specified using a generic argument, as shown:public abstract class Entity<TId> { public virtual TId Id { get; protected set; } public override bool Equals(object obj) { return Equals(obj as Entity<TId>); } private static bool IsTransient(Entity<TId> obj) { return obj != null && Equals(obj.Id, default(TId)); } private Type GetUnproxiedType() { return GetType(); } public virtual bool Equals(Entity<TId> other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; if (!IsTransient(this) && !IsTransient(other) && Equals(Id, other.Id)) { var otherType...