views:

109

answers:

2

Working on a website that has Employee and Branch entities, using a database table "Employees" which also contains the branch id and branch name. I can't change the client's database so I need to map Employees and Branches from the same table.

I guess I need some type of distinct clause in the mapping XML to get a distinct list or set of branches from the employee table?

Is there a way I can map both classes on the same table? (Can it be done with Fluent NHibernate?)

+1  A: 

Use components. I don't know FluentNhibernate, but in xml, it looks like this:

<class name="Employee">
  ...

  <component name="MyBranch">
    <!-- Branche properties are here: -->
    <property name="BrancheName"/>
    <property name="..."/>
  </component>
</class>

class Employee
{
  Branch MyBranch { get; private set; }
}

class Branch
{
  string BrancheName { get; private set; }
}

It's actually pretty straight-forward. You also do this for performance reasons, because you don't need to join tables when there is always a branch on an employee.

Note: If all columns are null, myBranch will be null.

Stefan Steinegger
+2  A: 

Stefan is correct, use components. In FluentNHibernate, it will look like:

class Branch
{
    string Name { get; set; }
    DateTime DateOpened { get; set; }
}

class Employee
{
    int Id { get; set; }
    string Name { get; set; }
    Branch Branch { get; set; }
}

class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        Component<Branch>(x => x.Branch, c => {
            c.Map(x => x.Name);
            c.Map(x => x.DateOpened);
        });
    }
}

The Component<Branch> can be shortened to just Component since the compiler will figure out the type automatically. Also, what I like to do is provide an AsComponent function on a class for my component so I don't have to repeat myself everywhere I map the component:

public static class BranchMap
{
    public Action<ComponentPart<Branch>> AsComponent()
    {
        return c =>
        {
            c.Map(x => x.Name);
            c.Map(x => x.DateOpened);
        };
    }
}

This also makes it easy to add in prefix/suffix functions for the cases where an entity may have more than one instance of a component with a different naming scheme.

Stuart Childs
Thanks for that, got it working in Fluent NHibernate as you suggested.
Jonathan Sewell