Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate HasMany Foreign Key Mapping Problem

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; }
}
like image 513
Chris Klepeis Avatar asked May 11 '11 16:05

Chris Klepeis


1 Answers

You need to specify the key column.

HasMany(m => m.Employees).KeyColumn("DepartmentId");
like image 114
Vadim Avatar answered Oct 26 '22 08:10

Vadim