开发者

NHibernate returns id outside of session, but not through a property

I have an interface like this:

public interface ICoreType {
    int TypeID {get;}
}

And an NHibernate class that implements it like this:

public class DueDateType : ICoreType {
    public virtual int Due开发者_StackOverflow社区DateTypeID {get;set;}
    ...
    public virtual int TypeID { get{ return this.DueDateTypeID; } }
}

Here's my mapping:

 <class name="DueDateType" table="tdfDueDateType" lazy="true" >
    <cache usage="read-write" include="all"/>
    <id name="DueDateTypeID" column="DueDateTypeID" >
      <generator class="identity"/>
    </id>
    ...
  </class>

When I get an instance of the object from NHibernate, and then return it outside the scope of the active session it was created in, I can get the value DueDateTypeID just fine, but accessing TypeID throws a LazyInitializationException. There is no mapping for TypeID, as I simply want it to return whatever DueDateTypeID's value is.

Marking the class lazy="false" in my mapping erases the problem. From what I've been reading, that is because there is no proxy generated for a non-lazy mapped class.

I would like to use the lazy loading features of NHibernate in this case; do I need to implement IInterceptor or some such, in order to get NHibernate to treat this property differently?


The problem is that all members of the entity trigger lazy initialization when accessed (except of the id). NH can't know what you actually are doing within the member. When triggering lazy initialization outside of the session, you get an error.

Suggestions:

  • Try to avoid any access to entities outside the session. It is only safe when turning off lazy loading - which is usually not a way to go.
  • Don't wrap the id. If you access TypeID, the entity is initialized although it is not necessary, which is bad for performance.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜