Please see the code below, which I am currently using in a production application. :
public abstract class Entity
{
public virtual long Id { get; protected set; }
public override bool Equals(object obj)
{
var compareTo = obj as Entity;
if (ReferenceEquals(compareTo, null))
return false;
if (ReferenceEquals(this, compareTo))
return true;
if (GetRealType() != compareTo.GetRealType())
return false;
if (!IsTransient() && !compareTo.IsTransient() && Id == compareTo.Id)
return true;
return false;
}
public static bool operator ==(Entity a, Entity b)
{
if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
return true;
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
return false;
return a.Equals(b);
}
public static bool operator !=(Entity a, Entity b)
{
return !(a == b);
}
public override int GetHashCode()
{
return (GetRealType().ToString() + Id).GetHashCode();
}
public virtual bool IsTransient()
{
return Id == 0;
}
public virtual Type GetRealType()
{
return NHibernateUtil.GetClass(this);
}
}
Every Entity class inherits from it.
It is a slight variation of the code here: https://github.com/vkhorikov/DddInAction/blob/master/DddInPractice.Logic/Common/Entity.cs
I am trying to decide whether to remove this base entity type from my application because of the feedback I have received when talking about it.
Is it normal to have a base Entity type (and base ValueObject) that has a base implementation for comparisons e.g. Object.Equals, IEquality.Equals etc?
It seems logical to me. Say I have the following entities:
Customer
Supplier
Product
Production
etc
Why is it a bad idea for them all to be compared by ID by default?
I have a separate domain model and data model if that has any bearing.