I am a little confused with a statement I am testing out. I am working with LINQ to Entities
I have commented in the code below. It is the last Console.WriteLine which I do not understand. I appreciate anyones input on this
using(Ecommerce.Data.Entities.EcommerceEntities ents = new Ecommerce.Data.Entities.EcommerceEntities()) { //This returns 1 item as expected var items = from a in ents.Product where a.ProductVarianceOption.Count() > 0 select a; foreach (var item in items) { //This outputs AT07 as expected Console.WriteLine(item.ProductCode); //This outputs 0 , but because I was able to query //only those which had a count greater than 0 above //I do not know why this is returning 0 Console.WriteLine(item.ProductVarianceOption.Count()); } }
TIA
Andrew
UPDATE: Just incase anyone else runs into this, and thanks to Marc Gravell, here is the solution. Marc Gravell’s comment urged me to find the IsLoaded Property and also the Load method. Thanks:
using(Ecommerce.Data.Entities.EcommerceEntities ents = new Ecommerce.Data.Entities.EcommerceEntities()) { //This returns 1 item as expected var items = from a in ents.Product where a.ProductVarianceOption.Count() > 0 select a; foreach (var item in items) { //This outputs AT07 as expected Console.WriteLine(item.ProductCode); //This outputs 0 , but because I was able to query //only those which had a value greater than 0 above //I do not know why this is returning 0 Console.WriteLine(item.ProductVarianceOption.Count()); //Load in the data required item.ProductVariance.Load(); //Load in the data required item.ProductVarianceOption.Load(); //This now outputs 2. ... As Expected. Thanks to Marc Gravell. :-) Console.WriteLine(item.ProductVarianceOption.Count()); } }
With entity framework, if you have materialized the object then you must explicitly load collection associations before you can see the contents. A pain.