Nhibernate many to many xml



我想在Nhibernate中建立一个多对多关系,但我现在被卡住了,我有3个sql表,学生类和学生类关系,我在c#中写了2个类

class Student
{ 
public virtual int StudentID { get; set; }
public virtual string name { get; set; }
public virtual IList<Class> Classes { get; set; }
public virtual void AddClass(Class Classer) {
Classes.Add(Classer);
}
}
'''
class Class
{

public virtual int ClassID { get; set; }
public virtual string name { get; set; }
public virtual string teacher { get; set; }

public virtual List<Student> students { get; set; }
public virtual void AddStudent(Student stud) {
students.Add(stud);

}
}

我的xml文件看起来像这样,另一个是相同的

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="NHibernateTutorialPart1"
namespace="NHibernateTutorialPart1">
<class name="Student">
<id name="StudentID" column="StudentID" >

</id>
<property name="name" />

<bag name ="Classes" table="ClassStudentRelation" cascade ="all" inverse ="true" >
<key column="ClassID"></key>
<many-to-many class="Class"> </many-to-many>
</bag>
</class>
</hibernate-mapping>

我主要创建了这个对象

Student sven= new Student {StudentID=7,  name = "sven" };
Class Ai = new Class {ClassID=7, name = "AI", teacher = "lauer" };
List<Class> tmp = new List<Class>();
List<Student> save = new List<Student>();
save.Add(sven);
tmp.Add(Ai);
Student sven2= new Student { StudentID = 62, name = "sven2",Classes=tmp };
Class Ai2 = new Class { ClassID = 62, name = "AI2", teacher = "lauer2",students=save };
mySession.Save(sven2);
mySession.Save(Ai2);
mySession.Transaction.Commit();

如果我在没有sven和ai的情况下提交,我可以在正确的sql表中提交信息,但我想提交ai2和sven2,并将其他信息的列表放入3个表中,但这不起作用——有人知道如何修复它。该错误与不匹配

NHibernate.Collection.Generic.PersistentGenericBag and NHibernate.Collection.Generic.PersistentGenericList

Classes包映射存在问题。假设ClassStudentRelation连接表具有StudentID和ClassID外键。映射应为:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="NHibernateTutorialPart1"
namespace="NHibernateTutorialPart1">
<class name="Student">
<id name="StudentID" column="StudentID" >        
</id>
<property name="name" />

<bag name="Classes" table="ClassStudentRelation" cascade="all" inverse="false">
<key column="StudentID"></key>
<many-to-many class="Class" column="ClassID" />
</bag>
</class>
</hibernate-mapping>

inverse属性应设置为false,因为集合负责管理关系。

Class对象的映射类似于:

<class name="Class">
<id name="ClassID" column="ClassID" >        
</id>
<property name="name" />

<bag name="Students" table="ClassStudentRelation" cascade="all" inverse="false">
<key column="ClassID"></key>
<many-to-many class="Student" column="StudentID" />
</bag>
</class>
</hibernate-mapping>

此外,您不能覆盖nhibernate实体中的集合。集合应尽快初始化,然后可以使用AddClass/AddStudent方法。

class Student
{ 
...
public virtual IList<Class> Classes { get; set; } = new List<Class>();
...
}
Student sven2= new Student { StudentID = 62, name = "sven2" };
sven2.AddClass(Ai);
Ai.AddStudent(sven2);
mySession.Save(sven2);
mySession.Save(Ai);

相关内容

  • 没有找到相关文章

最新更新