我正在尝试在nhibernate中映射一个简单的数据结构
表格
Employees
employeeID int
username varchar(30)
departmentID int
Departments
departmentID int
deptName varchar(50)
我的部门映射是这样的:
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");
}
}
...和员工映射
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");
}
}
我正在尝试遍历部门并从每个部门拉出所有员工:
foreach (var i in _directoryData.DepartmentCollection)
{
foreach (var e in i.Employees)
{
Debug.WriteLine(i.DepartmentName + " " + e.UserName);
}
}
这给了我一个错误,声明“Invalid column name 'Department_id'.
”...并且在生成的查询中它也使用了department_id。当我只是循环部门并输出部门名称时,它可以正常工作。
知道我缺少什么来获取departmentID的正确列名?以下是我的模型对象:
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; }
}
答案 0 :(得分:14)
您可以:创建一个Fluent NHibernate 约定,以便将HasMany
“外键”创建为<'Name'>ID
。
或更改部门映射:
HasMany(m => m.Employees).KeyColumns.Add("DepartmentID")
答案 1 :(得分:10)
您需要指定键列。
HasMany(m => m.Employees).KeyColumn("DepartmentId");
答案 2 :(得分:1)
您需要在HasMany声明中使用KeyColumn
方法,如documentation