Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate LazyLoad Issues

I couldn't find an answer to this issue so I assume it is something I am doing wrong.

I have a PersistenceModel set up where I have set a convention as follows: -

persistenceModel.Conventions.Add(DefaultLazy.Always());

However, for one of the HasManyToMany relationships in one of my entities I want eager loading to take place which I am setting up as follows: -

HasManyToMany(x => x.Affiliates).Not.LazyLoad();

Intuitively, I expect eager loading to take place as I am overriding the lazy load default that I have specified as a convention but it still lazy loads. If I set the DefaultLazy convention to never and then set LazyLoad on an individual relationship it doesn't work either.

Any ideas?

like image 647
Dotnet Avatar asked Nov 16 '10 17:11

Dotnet


1 Answers

When you set Not.LazyLoad(), you tell NHibernate to load Affiliates when the parent loads. NHibernate will do this by performing another select on the Affliates many-to-many table regardless of whether you access the Affiliates collection or not. NHibernate is using another select because that is the default fetching mode. You want to override fetching mode as well, either in the query or in the mapping. To do it in the mapping, add the following:

HasManyToMany(x => x.Affiliates)
    .Not.LazyLoad()
    .Fetch.Join();

You might also want to include a ".Cascade.AllDeleteOrphan()" if you want NHibernate to persist new Affiliaites added to the collection and delete orphaned ones. If you do not do this, you will have to explicitly call session.Save(newAffiliate). Otherwise you'll receive a TransientObjectException when your Affiliates collection contains a new Affiliate.

like image 76
James Kovacs Avatar answered Sep 20 '22 23:09

James Kovacs