I am considered new to NHibernate. I want my Article entity class to have two lazy properties. One of them is User other is Content. My entity and mapping is like
<class name="Article" table="TBL_ARTICLE">
<id name="Id" column="ART_ID">
<generator class="native" />
</id>
<property name="UserId" column="USR_ID" not-null="true" />
<many-to-one name="User" column="USR_ID" insert="false" update="false" />
<property name="Content" column="ART_CONTENT" not-null="true" lazy="true" />
</class>
public class Article
{
public virtual long Id { get; set; }
public virtual long UserId { get; set; }
public virtual User User { get; set; }
public virtual string Content { get; set; }
}
I select it like
using(ISession session = sessionFactory.OpenSession()) {
return session.Query<Article>()
.SingleOrDefault(a => a.Id == id);
}
It works fine. When I try to access User or Content property outside the using block I get some kind of lazy loading exception. This is what I've expected.
For some cases I like to fetch User data eagerly. I select it like:
using(ISession session = sessionFactory.OpenSession()) {
return session.Query<Article>()
.Fetch(a => a.User)
.SingleOrDefault(a => a.Id == id);
}
It still works fine. When I try to access User property outside the using block I can have its property values but when try to access Content property I stil get some kind of lazy loading exception and this is still what I've expected.
When I want to fetch content data like
using(ISession session = sessionFactory.OpenSession()) {
return session.Query<Article>()
.Fetch(a => a.Content)
.SingleOrDefault(a => a.Id == id);
}
I get an exception:
Invalid join: a.Content
[.SingleOrDefault[Repository.NH.Article](.Fetch[Repository.NH.Article,System.String]
(NHibernate.Linq.NhQueryable`1[Repository.NH.Article], Quote((a, ) => (a.Content)), ),
Quote((a, ) => (Equal(a.Id, 1))), )]
I read some blog post about doing this by HQL but I am looking for a solution using Linq Provider.