I want to apply/practice DDD with my new project hence I am creating those typical DDD base classes, i.e., Entity
, ValueObject
, AggregateRoot
and so on.
Question:
When you have the Entity base object implement IEquatable
, should two entities with default value of the identity (Id) be considered as Not equal or equal?
For example, I use Guid
type for the identity
public interface IEntity
{
Guid LocalId { get; }
}
public abstract class Entity : IEntity, IEquatable<Entity>
{
public Guid LocalId { get; private set; }
protected Entity()
{
this.LocalId = Guid.Empty;
}
protected Entity(Guid id)
{
if (Guid.Empty == id)
{
id = Guid.NewGuid();
}
this.LocalId = id;
}
public bool Equals(Entity other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(other, this))
{
return true;
}
// **Question** - should I return false or true here?
if (other.LocalId == Guid.Empty && this.LocalId == Guid.Empty)
{
return false;
}
return (other.LocalId == this.LocalId);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, null))
{
return false;
}
if (ReferenceEquals(obj, this))
{
return true;
}
if (!obj.GetType().Equals(typeof(Entity)))
{
return false;
}
return Equals((Entity)obj);
}
public override int GetHashCode()
{
return this.LocalId.GetHashCode();
}
public static bool operator==(Entity left, Entity right)
{
return Equals(left, right);
}
public static bool operator!=(Entity left, Entity right)
{
return !Equals(left, right);
}
}