Created
March 20, 2013 15:50
-
-
Save LodewijkSioen/5205797 to your computer and use it in GitHub Desktop.
Base enity from NHibernate Cookbook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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