9

我正在尝试在 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。当我只是遍历部门并输出部门名称时,它工作正常。

知道我缺少什么来获取部门ID 的正确列名吗?这是我的模型对象以防万一:

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; }
}
4

3 回答 3

15

您可以:创建一个 Fluent NHibernate约定,以便将HasMany“外键”创建为<'Name'>ID.

或更改部门映射:

 HasMany(m => m.Employees).KeyColumns.Add("DepartmentID")
于 2011-05-11T16:53:29.730 回答
11

您需要指定键列。

HasMany(m => m.Employees).KeyColumn("DepartmentId");
于 2011-05-11T16:53:41.430 回答
2

您需要KeyColumn在 HasMany 声明中使用该方法,如文档中所述

于 2011-05-11T16:56:22.963 回答