1

By default, I have lazy loading enabled on all my models, and that's the way I want to keep things. However, sometimes I want to eagerly fetch all the data up front on an individual query. From everything I've read, I should be using FetchMany() for this purpose. However, if I do:

var dbRecipe = (from r in session.Query<Models.Recipes>().FetchMany(x => x.Ingredients)
                where r.RecipeId == recipeId
                select r).FirstOrDefault();

Then dbRecipe.Ingredients.Count() returns 1. In other words, it only returns the first ingredient of that recipe. However, if I do:

var dbRecipe = (from r in session.Query<Models.Recipes>()
                where r.RecipeId == recipeId
                select r).FirstOrDefault();

Then dbRecipe.Ingredients.Count() returns 12, which is correct, however it performs a second query to load the ingredients for that recipe.

How do I make FetchMany fetch all 12 records up front? I was assuming that was the difference between Fetch and FetchMany. I'm clearly doing something wrong.

1 Answer 1

2

You can work around this by not running FirstOrDefault as the last statement. This will cause nh to run a top(1) query which yields wrong results...

Instead use .ToList().FirstOrDefault().

Or you use QueryOver<> which works fine

session.QueryOver<Models.Recipes>()
   .Fetch(prop => prop.Ingredients)
   .Eager
   .Where(p => p.RecipeId == recipeId)
   .SingleOrDefault();
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly! (Ended up using the QueryOver<> method)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.