Joined: Sun May 29, 2005 3:55 pm Posts: 13
|
I have two entities User and Exam. The relationship between them is many-to-many since a single User can take many exams and a single Exam is given to many users.
I have a exam persisted in the database and now I want to fetch the exam but not the Users of the exam. So, I have a mapping in my Exam.hbm.xml something like this:
<bag name="Users" access="nosetter.camelcase-underscore" inverse="true" lazy="true" cascade="save-update" table="UserExams" >
<key column="ExamID" />
<many-to-many class="User" column="UserID" />
</bag>
The ExamManager.GetById method fetches the Exam
public static Exam GetById(int id)
{
Exam exam = null;
using (ISession session = sessionFactory.OpenSession())
{
exam = session.Get<Exam>(id);
// initialize the collection
NHibernateUtil.Initialize(exam.Users);
}
return exam;
}
And here is the code that is blowing off:
Exam exam = ExamManager.GetById(55);
foreach (User u in exam.Users)
{
// blows when I try to access the FirstName
Console.WriteLine(u.FirstName);
}
The exception is "Failed to Initialize a Lazy Collection". The inner exception is "Object Reference not set to an instance of an object".
Here is the Exam.cs:
private IList<User> _users = new List<User>();
And the Users property:
public IList<User> Users
{
get {
return new ReadOnlyCollection<User>(_users); }
}
Thanks!
|
|