简体   繁体   中英

What is the best way to do eager joins in NHibernate?

I am using NHibernate and started using the NHibernate profiler and realized that I am running a lot of SQL queries that I don't need to. The one main optimization is for me to eager joins up front to avoid having Select N + 1 issues.

I am trying to figure out the best way to do eager joins using NHibernate:

IList projects = session.CreateQuery(
      "from Project p left join fetch p.Sponsors left join fetch p.Desks")
      .List();

But this keeps coming up with the error:

QueryException: Could not resolve Property on Sponsors of Domain.Project

What is the best way to do eager joins using NHibernate?

That exception means Project.Sponsors is not mapped.

Anyway, there's a better way to do eager feching of collections, especially when retrieving more than one: http://ayende.com/Blog/archive/2010/01/16/eagerly-loading-entity-associations-efficiently-with-nhibernate.aspx

Make sure your Project object has Sponsors mapped correctly.

Should (hopefully) look something like

 [BelongsTo(Column = "Sponsor_ID")]
    public Sponsor sponsors { get; set; }

The same should be done with Desks as well.

Might want to check out http://nmg.codeplex.com/ for a good mapping generator with plenty of options.

There is also Afo Castle Generator which doesn't have quite as many options and may have some slight quirks but still works. (It's the one I originally used) http://www.agilityfororms.com/Home/Products/AfoCastleActiveRecordModelCodeGenerator/

Also if you are looking at eager loading you can always try using criteria.

Some good tutorials for Nhibernate can be found here: http://www.summerofnhibernate.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM