Fluent NHibernate HasMany Foreign Key Mapping Prob

2020-05-27 08:19发布

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

3条回答
戒情不戒烟
2楼-- · 2020-05-27 08:48

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

查看更多
ら.Afraid
3楼-- · 2020-05-27 08:49

You need to specify the key column.

HasMany(m => m.Employees).KeyColumn("DepartmentId");
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-05-27 08:55

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")
查看更多
登录 后发表回答