在nhibernate 4.0双向关系 [英] Bi-directional relationship in nhibernate 4.0
问题描述
我有一个在NHibernate 3.1上工作完美的代码,但是当它不能在NHibernate 4.0上运行时,所以这是类关系。
public class Employee:BaseEntity
{
...
Public Department Dept {get;组; }
}
public class Department:BaseEntity
{
...
public IList< Employee>员工{get;组; }
}
对于映射我们有这个
DepartmentMap:ClassMap< Department>
{
表(....);
HasMany(x => x.Employees).KeyColumn(DeptId)。Not.KeyNullable();
}
EmployeeMap:ClassMap< Employee>
{
引用(x => x.Dept).Column(DeptId);
}
当我添加这样的员工时
var dept = session.Load< Department>(deptId);
newEmployee.Dept = dept;
session.Save(newEmployee);
但是却出现错误:
NHibernate.PropertyValueException:非空属性引用空
或瞬态值
阅读我必须以两种方式添加关系,所以我将其修改为
var dept = session.Load< Department> ;(DEPTID);
newEmployee.Dept = dept;
dept.Employees.Add(newEmployee);
session.Save(newEmployee);
但现在我有这个错误:
NHibernate.PropertyValueException:将属性值
出错的错误... System.IndexOutOfRangeException:此
的SqlParameterCollection无效索引7,Count = 7。 b
所以,我想知道如何解决这个问题,以及在哪里可以阅读有关双向的NHibernate的变化
我找到了这个问题的解决方法:
解决这个问题的方法是在父文件的映射中添加Inverse。
因此,Department的映射是:
DepartmentMap:ClassMap< Department>
{
表(....);
HasMany(x => x.Employees).KeyColumn(DeptId)。Inverse()。Not.KeyNullable();
}
I have a code that was working perfectly on NHibernate 3.1, but when it is not working on NHibernate 4.0
So, this is the class relations
public class Employee : BaseEntity
{
...
public Department Dept { get; set; }
}
public class Department : BaseEntity
{
...
public IList<Employee> Employees { get; set; }
}
and for the mapping we have this
DepartmentMap : ClassMap<Department>
{
Table("....");
HasMany(x => x.Employees).KeyColumn("DeptId").Not.KeyNullable();
}
EmployeeMap : ClassMap<Employee>
{
Reference(x => x.Dept).Column("DeptId");
}
and when I am adding an employee like that
var dept = session.Load<Department>(deptId);
newEmployee.Dept = dept;
session.Save(newEmployee);
But it is throwing an error:
NHibernate.PropertyValueException: not-null property references a null or transient value
I read that I have to add the relation in two ways, so I modified it to this
var dept = session.Load<Department>(deptId);
newEmployee.Dept = dept;
dept.Employees.Add(newEmployee);
session.Save(newEmployee);
But now I have this error :
NHibernate.PropertyValueException: Error dehydrating property value for... System.IndexOutOfRangeException: Invalid index 7 for this SqlParameterCollection with Count=7.
So, I want to know how to fix it and where I can read about the changes in NHibernate about this with bi-direction
I found the fix for the problem: The fix for the problem is to add Inverse to the mapping of the parent file. So, the mapping for Department will be:
DepartmentMap : ClassMap<Department>
{
Table("....");
HasMany(x => x.Employees).KeyColumn("DeptId").Inverse().Not.KeyNullable();
}
这篇关于在nhibernate 4.0双向关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!