Reduce the number of queries in EF

Posted by Gio2k on Stack Overflow See other posts from Stack Overflow or by Gio2k
Published on 2009-06-30T14:22:18Z Indexed on 2010/03/08 6:06 UTC
Read the original article Hit count: 186

Filed under:

I have the following Model:

Entities:

  • Product (Contains basic data for products: price, etc)
  • Attribute (Contains data for all possible optional attributes)
  • ProductAttribute (Contains data for optional attributes of a product, eg. Color, Model, Size). ProductAttribute is essentially a many to many relationship with payload (ProductId, AttributeID, Value)

And this piece of code:

private static void ListAttributes(Product p)
{
    p.ProductAttributes.Load();
    foreach (var att in p.ProductAttributes)
    {
        att.Attribute.load();
        Console.WriteLine("\tAttribute Name:{0} - Value {1}", 
           att.Attribute.Name,
           att.AttributeValue);
    }
}

This piece of code will fire a query for each time the att.Attribute.Load() method is called in the foreach loop, only so i can get display the name of the attribute. I would like to fetch the Attribute.Name together with the query that fetches all attribute values, i.e. join ProductAttribute and Attribute. Is there any way to achieve this within my method?

© Stack Overflow or respective owner

Related posts about entity-framework