public abstract class EntityBase<TEntity> where TEntity : EntityBase<TEntity>
{
private int? oldHashCode;
public virtual Guid Id { get; protected set; }
public virtual bool Equals(EntityBase<TEntity> other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Id, Id);
}
public override int GetHashCode()
{
if (oldHashCode.HasValue)
return oldHashCode.Value;
var thisIsTransient = Equals(Id, Guid.Empty);
if (thisIsTransient)
{
oldHashCode = base.GetHashCode();
return oldHashCode.Value;
}
return Id.GetHashCode();
}
public override bool Equals(object obj)
{
var other = obj as TEntity;
if (other == null)
return false;
var otherIsTransient = Equals(other.Id, Guid.Empty);
var thisIsTransient = Equals(Id, Guid.Empty);
if (otherIsTransient && thisIsTransient)
return ReferenceEquals(other, this);
return other.Id.Equals(Id);
}
}