Optimizing an NHibernate query
I've got the following piece of code which (obviously) gives me HUGE performance problems, and I seek an advice on how to make it better. The idea is, for each base item in a list, I look if there is at least one derived item, and if not, I create one. The problem is, for each base item there's a separate database query:
var derivedItems = from item in baseItems sele开发者_StackOverflow社区ct item.GetDerivedItem(session);
where
public virtual DerivedListItem GetDerivedItem(ISession session)
{
var items = session.Query<DerivedItem>()
.Where(item => item.BaseItem == this);
if (items.Any())
return items.First();
var newItem = new DerivedItem(this);
session.Save(newItem);
return newItem;
}
How would you improve this kind of code?
If you use Criteria, you can add an alias to the criteria to prefetch the joins for your query.
It would go something like this:
DetachedCriteria.For(GetType(MyQueriedType)).CreateAlias("DerivedItem", "d", SqlCommand.JoinType.LeftOuterJoin)
Obviously, you can then proceed to get further info from other tables by repeasting the process. Don't forget to map the next alias to any potential alias.
As a matter of fact, if you're reluctant to stop using linq to nhibernate, i'd recommend looking into joins for linq to nhibernate. Perhaps this post can help
精彩评论