9
votes

I'm trying to map a simple data structure in nhibernate

Tables:

Employees
employeeID int
username varchar(30)
departmentID int

Departments
departmentID int
deptName varchar(50)

My department mapping is like so:

public class DepartmentMap: ClassMap<Department>
{
    public DepartmentMap()
    {
        Id(m => m.DepartmentID).Column("departmentID");
        Map(m => m.DepartmentName).Column("deptName").Length(50);

        HasMany(m => m.Employees);

        Table("Departments");
    }
}

... and the employee mapping

public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        Id(x => x.EmployeeID, "employeeID");
        Map(x => x.UserName, "username").Length(30);

        References<Department>(x => x.Department, "departmentID");

        Table("Employees");
    }
}

I'm trying to loop through departments and pull all employees from each department:

foreach (var i in _directoryData.DepartmentCollection)
{
    foreach (var e in i.Employees)
    {
        Debug.WriteLine(i.DepartmentName + " " + e.UserName);
    }
}

which gives me an error stating "Invalid column name 'Department_id'." ... and in the generated query it uses department_id as well. When I just loop through departments and output the department name it works fine.

Any idea what I'm missing to get the correct column name for departmentID? Here are my model objects just in case:

public class Department
{
    public virtual int DepartmentID { get; set; }
    public virtual string DepartmentName { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
}

public class Employee : PersistentEntity
{
    public virtual int EmployeeID { get; set; }
    public virtual string UserName { get; set; }

    public virtual Department Department { get; set; }
}
3
@David - yes, I did. My mapping appears to be the same as the mapping wiki on fluentnhibernates site.Chris Klepeis

3 Answers

15
votes

You may either: create a Fluent NHibernate convention so that the HasMany "foreign key" is created as <'Name'>ID.

Or change the Department mapping:

 HasMany(m => m.Employees).KeyColumns.Add("DepartmentID")
11
votes

You need to specify the key column.

HasMany(m => m.Employees).KeyColumn("DepartmentId");
2
votes

You need to use the KeyColumn method on the HasMany declaration, as explained in the documentation