I\'m now starting out on DDD, I\'ve already found a nice implementation for ValueObject but I cant seem to find any good implementation for Entities, i want a generic base entit
The only characteristic of an Entity is that it has a long-lived and (semi-)permanent identity. You can encapsulate and express that by implementing IEquatable
. Here's one way to do it:
public abstract class Entity : IEquatable>
{
private readonly TId id;
protected Entity(TId id)
{
if (object.Equals(id, default(TId)))
{
throw new ArgumentException("The ID cannot be the default value.", "id");
}
this.id = id;
}
public TId Id
{
get { return this.id; }
}
public override bool Equals(object obj)
{
var entity = obj as Entity;
if (entity != null)
{
return this.Equals(entity);
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
#region IEquatable Members
public bool Equals(Entity other)
{
if (other == null)
{
return false;
}
return this.Id.Equals(other.Id);
}
#endregion
}