NHibernate cheat sheet using Attributes

A few common mapping examples when using the NHibernate ORM with Attributes.

Class

This is a required attribute for all Entity classes:
[Class(NameType=typeof(Being),Table="Being",Lazy=false)]
public class Being ...

Id
All classes should specify a unique table identifier:
[Id(0, Name="Id", Column="Id")]
[Generator(1, Class="native")]
public long Id
{
get;
set;
}


Sub-classing (joined table per sub-class)
When extending a class you can use 3 types of subclassing that NHibernate recognises. For subclassing by creating a table per sub-class use:
[JoinedSubclass(NameType=typeof(BusinessContact),
ExtendsType=typeof(Being),
Table="BusinessContact", Lazy=false)]

public class BusinessContact : Being ...

In this case sub-classes must override the Id property:
[Key(Column = "Id")]
public override Id {
get { return base.Id; }
set { base.Id = value; }
}


One to One
Use this when a one-to-one association is required between two classes (in this case PrintingSettings is within a BulkPrintingJob class):
[Key(0, Column = "BulkPrintingJobId")]
[OneToOne(1,
ClassType = typeof(PrintingSettings),
Cascade = "save-update")]

public virtual PrintingSettings Settings
{
get;
set;
}


One to One v2
Similar to above but for same class types ('Address') e.g. linked lists. Set to unique and contained within another Address.
[ManyToOne(0, ClassType = typeof(Address),
Cascade = "none",
Unique = true)]

public Address PreviousAddress
{
get;
set;
}


One to Many
Typically used for holding multiple objects relating to an object. Example where a business contact has multiple email addresses:
[Bag(0, Cascade = "all-delete-orphan", Lazy = false)]
[Key(1, Column = "BusinessContactId")]
[OneToMany(2, ClassType = typeof(Email))]
public IList Emails { get; set; }

Many to Many (IList example)
An example where categories have accessors who can access these:
[Bag(0, Cascade = "none", Lazy = false)]
[Key(1, Column = "CategoryId")]
[ManyToMany(2, ClassType = typeof(Accessor))]
public IList Accessors
{
get;
set;
}


Many to Many (Array example)
Example where a group has group members (uses Arrays instead of ILists):
[Array(0, Cascade = "none")]
[Key(1, Column = "BeingGroupId")]
[Index(2)]
[ManyToMany(3, ClassType = typeof(Being),
Column = "_beingId")]

public Being[] GroupMembers
{
get;
set;
}


Many to One (& parent/child)
An example where a BeingGroup contains other BeingGroups.
[ManyToOne(0, ClassType = typeof(BeingGroup),
Cascade = "none")]

public BeingGroup Parent
{
get;
set;
}