Skip to content

Instantly share code, notes, and snippets.

@LodewijkSioen
Created March 20, 2013 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LodewijkSioen/5205797 to your computer and use it in GitHub Desktop.
Save LodewijkSioen/5205797 to your computer and use it in GitHub Desktop.
Base enity from NHibernate Cookbook
/// <summary>
/// Base Entity for NHibernate that implements equality
/// </summary>
/// <typeparam name="TId">Type of the identifier of the entity</typeparam>
/// <remarks>Code from the book NHibernate 3.0 Cookbook - Chapter 1 - Setting up a base entity class</remarks>
public abstract class Entity<TId>
{
/// <summary>
/// Gets or sets the id
/// </summary>
/// <value>
/// The id
/// </value>
public virtual TId Id { get; protected set; }
/// <summary>
/// Gets or sets the version. Used for optimistic concurrency
/// </summary>
/// <value>
/// The version
/// </value>
public virtual int Version { get; set; }
/// <summary>
/// Implements equality, needed for NHibernate
/// </summary>
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();
}
/// <summary>
/// Implements equality, needed for NHibernate
/// </summary>
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 = other.GetUnproxiedType();
var thisType = GetUnproxiedType();
return thisType.IsAssignableFrom(otherType) ||
otherType.IsAssignableFrom(thisType);
}
return false;
}
private int? _hashCode;
/// <summary>
/// Implements equality, needed for NHibernate
/// </summary>
public override int GetHashCode()
{
if (_hashCode.HasValue)
{
return _hashCode.Value;
}
var isTransient = Equals(Id, default(TId));
if (isTransient)
{
_hashCode = base.GetHashCode();
return _hashCode.Value;
}
return Id.GetHashCode();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment