C# – Fluent NHibernate Join with Constraint


i have an entity with its properities spread over two tables that i'd like to map to one class using Fluent NHibernate, but with a constraint on the joining table.

i've changed the domain of my problem for this question to be the familar 'customer' domain, so my example here may seam a little contrived, but it illustrates my problem. it's bascially this; i have a Customer table that has some customer attributes in it, but the first and last names of the customer are held in a separate CustomerName table as two rows linked to the customer and identified as first and last names.

the following is the table schema:

CustomerId int,
Birthday datetime

CREATE TABLE CustomerName(
CustomerId int NOT NULL,
CustomerNameTypeId int NOT NULL,
Name nvarchar(25) NOT NULL

CREATE TABLE CustomerNameTypes(
CustomerNameTypeId NOT NULL,
Description nvarchar(25) NOT NULL

with the CustomerNameTypes table containing two rows:
1, "FirstName"
2, "SecondName"

what i need is a Fluent Mapping that will map the above to the following:

public class Customer
    public virtual int CustomerId { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual DateTime Birthday { get; set; }

can anyone help?!

many thanks in advance
Chris Browne

Best Solution

I know this doesn't quite answer what you were asking, but...

If both LastName and FirstName were on the same row of the CustomerName table (but they're not), you could accomplish this with the <join> mapping. Ayende describes this HBM mapping on his blog. There is a fluent-nhibernate example of this here: Entity spanning multiple tables. The method name has since changed from WithTable() to Join(). Here's what it would look like:

public class CustomerMap : ClassMap<Customer>
    public CustomerMap()
        Id(x => x.CustomerId);
        Join("CustomerName", m =>
            m.Map(x => x.FirstName);
            m.Map(x => x.LastName);
        // ... other properties ...

I'm not sure yet how to address the problem of the two names being on separate rows.

Related Question