NHibernate mapping problem - Could not initialize proxy - no Session

拈花ヽ惹草 提交于 2019-12-31 05:25:12

问题


I have just started to learn NHibernate, and are following tutorials. On my own learning project, I have made up a problem for myself. I have two tables:

Team:
TeamId*
Name


Match:
MatchId*
TeamAId
TeamBId

The model entities are:

Team

public virtual int? TeamId { get; private set; }
public virtual string Name { get; set; }
public virtual IList<Match> HomeMatches { get; set; }
public virtual IList<Match> AwayMatches { get; set; }

Match

public virtual int? MatchId { get; private set; }
public virtual Team TeamA { get; set; }
public virtual Team TeamB { get; set; }

And this is my mapping for Team:

    <property name="Name" type="string">
        <column name="Name" sql-type="nvarchar" not-null="true"/>
    </property>


    <bag name="HomeMatches" inverse="true" cascade="all-delete-orphan">
        <key column="TeamAId" />
        <one-to-many class="Match"/>
    </bag>

    <bag name="AwayMatches" inverse="true" cascade="all-delete-orphan">
        <key column="TeamBId" />
        <one-to-many class="Match"/>
    </bag>

And this is for Match:

    <many-to-one name="TeamA" class="Team">
        <column name="TeamAId" sql-type="int" not-null="true" />
    </many-to-one>

    <many-to-one name="TeamB" class="Team">
        <column name="TeamBId" sql-type="int" not-null="true" />
    </many-to-one>

I guess this isn't the right way to do it, since I get an error message: NHibernate.LazyInitializationException: Initializing[MyProject.Domain.Entities.Team#1]-Could not initialize proxy - no Session.

  1. Is there something wrong with my mapping?
  2. If not, any suggestion on how I can handle the error?

Thanks.


回答1:


The problem is not with your mapping, but with your session handling.

You are closing the session and then trying to access a lazily-loaded property (a Team).



来源:https://stackoverflow.com/questions/3934016/nhibernate-mapping-problem-could-not-initialize-proxy-no-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!