views:

219

answers:

2

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());
            }

        }
+2  A: 

With entity framework, if you have materialized the object then you must explicitly load collection associations before you can see the contents. A pain.

Marc Gravell
A: 

You might want to have a look at Transparent Lazy Loading for Entity Framework. This replaces the original code generator with a new one. The new one generates entities that handle loading under the hood. Note that the code is not perfect - there are some issues. The biggest one - as far as I am concerned - is a data binding issue, but you can easily add a fix because you get the sources.

Daniel Brückner