views:

29

answers:

1

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.

+2  A: 

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).

Diego Mijelshon
This was correct. I was however using ASP.NET MVC and because of this I had to implement some extra functionality to handle lazy-loading with views.
Buginator