Reputation: 9973
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; }
}
Upvotes: 9
Views: 14358
Reputation: 7846
You need to use the KeyColumn
method on the HasMany declaration, as explained in the documentation
Upvotes: 2
Reputation: 6726
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")
Upvotes: 15
Reputation: 17957
You need to specify the key column.
HasMany(m => m.Employees).KeyColumn("DepartmentId");
Upvotes: 11