Fluent NHibernate HasMany Foreign Key Mapping Problem
Asked Answered
W

3

9

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; }
}
Woodwork answered 11/5, 2011 at 16:42 Comment(1)
@David - yes, I did. My mapping appears to be the same as the mapping wiki on fluentnhibernates site.Woodwork
W
15

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")
Warrenwarrener answered 11/5, 2011 at 16:53 Comment(1)
Thanks, I must have overlooked that part in fluents wiki.Woodwork
B
11

You need to specify the key column.

HasMany(m => m.Employees).KeyColumn("DepartmentId");
Bedrock answered 11/5, 2011 at 16:53 Comment(0)
C
2

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

Convertiplane answered 11/5, 2011 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.