views:

53

answers:

1

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?

+1  A: 

It seems like you have a wrapper around the EntityObject to perform the loading of each Entity on your own.

If you want to keep to this structure. I think what you need to do is overload the ProductAttributes.Load() method to accept an enum or something. Then inside that Load method you could perform a Linq-to-Entity or Entity-SQL query joins and includes the attributes for you.

var query = from c in context.Product.Include("Attributes");
Lobut
I don't have a problem with the p.ProductAttributes.Load(); part. This will fire up a query for each product, which is in the order of tens. The problem lies with the att.Attribute.load(); since this one will fire up sql queries in the order of 100's.Additionally, using the att.Attribute.IsLoaded property will reduce the number of unnecessary queries, but this is still sub-optimal.
Gio2k
Well to me, there's no way to work with the att.Attribute.load() method. Because it's a "child". It doesn't know about it's sibling attributes. If you work with the "parent" load method (p.ProductAttributes.Load()) you can make it such that that load method populates the products and the attributes in a single method call.
Lobut