Thursday, May 31, 2012

How to add a unique constraint on multiple columns with FluentNHibernate

For example, we have table ‘WebsiteLinks’ and two columns ‘WebsiteId’ and ‘Url’ and we would like to make unique constraint which includes those two columns. In FluentNHibernate this is archived by using ‘UniqueKey’ construct. Here follows example:
public class WebsiteLinkMap : ClassMap<WebsiteLink>
{
    public WebsiteLinkMap()
    {
        Table("WebsiteLinks");

        Id(x => x.Id).GeneratedBy.Identity();

        Map(x => x.Url).Not.Nullable().Length(256).UniqueKey("UQ_WebsiteLinks_URL_ WebsiteId");
        References(x => x. Website).UniqueKey("UQ_WebsiteLinks_URL_WebsiteId ");
    }
}