I have a problem understanding and working with the Include command, primarily when working on a nopCommerce 1.9 site, but I have the same problem everywhere. I have searched the net, and on stackoverflow, but can’t seem to find anyone else having the same problem, so I guess it’s just me that is getting this wrong.
I think that the problem is very simple, but plainly: When I include the child entities when querying the parent entity, EF loads all of the entities, but not the collection which means that when I try and access the collection, EF goes back to the database to load the collection.
To clarify, consider the following:
var products = (from p in _context.Products.Include("NpProductVariants") select p).ToList();
var productvariant = products.ProductVariants[2]; //Loads the NpProductVariants collection
I think that the additional fetch is superflous, indeed, if I create an object to hold the navigation collection and code using the holder, I can avoid further fetches, but this is annoying i.e.
var products = (from p in _context.Products.Include("NpProductVariants") select new productholder() { product = p, variants = p.NpProductVariants }).ToList();
This proves that the collection is available during query execution because I can store it, but it doesn’t automatically appear as attached to the ObjectContext until I try and access properties which requires an extra query.
I think that the problem is clear, but what am I doing wrong?
Any help would be much appreciated.
Thanks.
Mark
You are including
"NpProductVariants", but you are accessingProductVariants.There are two things you can do, depending on your actual EF model:
Change the
Includeto"ProductVariants":Change the property you access to
NpProductVariants: