Hi,
I am trying to create a many-to-many relationship. I have a class User and Exam. User can have many exams and Exam can have many users hence many-to-many relationship. I have a UserExams table in the database that refer to the Users and Exams table. UserExams contain the UserID and ExamID from the Users, Exams table respectively.
Now, when I try to insert a new user with new exams it does not insert into the UserExams table. Here is my mapping files.
User.hbm.xml:
<bag name="Exams" access="nosetter.camelcase-underscore" cascade="save-update" lazy="true" inverse="true" table="UserExams">
<key column="UserID" />
<many-to-many class="Exam" column="ExamID" />
</bag>
Exam.hbm.xml:
<bag name="Users" access="nosetter.camelcase-underscore" cascade="save-update" lazy="true" table="UserExams">
<key column="ExamID" />
<many-to-many class="User" column="UserID" />
</bag>
And here is the code that I am using to insert many-to-many relationship into the database table UserExams.
Exam exam1 = new Exam();
exam1.Title = "Exam 1";
Exam exam2 = new Exam();
exam2.Title = "Exam 2";
User user1 = new User();
user1.FirstName = "John";
user1.LastName = "Doe";
user1.AddExam(exam1);
user1.AddExam(exam2);
ISessionFactory sessionFactory = cfg.BuildSessionFactory();
using (ISession session = sessionFactory.OpenSession())
{
session.SaveOrUpdate(user1);
}
|