views:

71

answers:

4

With our current persistence framework properties on a child entity that point to it's parent always point to the same instance. For example, given the following entity classes

public class Order
{
    public int OrderId{get;set;}
    public EntityCollection<LineItem> Items{get;}
}

public class LineItem
{
    public Order Order{ get;set;}
}

We can load an order from the database like this:

var order = Order.FindById( 1000 );

Now here's the key to my question the following is true for our current framework

object.ReferenceEquals( order, order.Items[ 0 ].Order );

That is, the Order property on the line item points to the exact same instance of the order object in memory when accessed through the Items property.

I'm kinda tired of maintaining our entity tools and want to switch to NHibernate or another persistence framework. My question then is, does the lazy loading features of NHibernate work the same way or will it load a new instance of the Order object for each line item?

+1  A: 

NHibernate works this way within a single session (Unit Of Work). There are ways to make it work this way beyond a single session by using the NHibernate second level cache. A great explanation of this can be found here First And Second Level Caching In NHibernate

ShaneC
+1  A: 

Yes. They reference the same instance! Same for LINQ to SQL and Entity Framework.

Andrew Siemer
A: 

Yes, NHibernate uses an Identity Map in ISession to manage entity references. Other persitence frameworks do (or should do) the same.

Paco
+1  A: 
object.ReferenceEquals( order,order.Items[ 0 ].Order );

Might not always be true , it depends on how you set up the many-to-one side in nihibernate mapping, if you set it up as lazy ( like below )

<many-to-one name="order"  lazy="proxy" />

then reference equals wont return true.

But if you get the intial order in the same session in the previous line as you mentioned then you might get the real object not proxy

Surya