views:

38

answers:

2

How would I write a query using entity framework where I need to make a list with a column for the product, category and parent category. I have not figured out how to get the parent category. Any Help is appreciated. So far I have the following:

from product in Products
select new { Ctg = (from prdCategory in ProductCategories
                    where prdCategory.Products.Contains(product)
                    select prdCategory.CategoryName).FirstOrDefault(),
             Name = product.ProductName
             ParentCtg = ...
    }
A: 

If i understand your schema correctly, it should be a simple case of getting a plain list of Products, and your display list should just have a column with 'thisProduct.Category.Name' displayed.

Chris
+1  A: 

Ok, if all the associations has been set up correctly from your database then that's going to be one easy query:

var product = from p in context.Products
              select new {
                 Name = product.ProductName,
                 CategoryNames = p.ProductCategories
                         .Select(c => c.CategoryName).ToList(),
                 ParentCategories = p.ProductCategories
                         .Select(c => c.ProductCategory2.CategoryName).ToList()
              };

When EF maps Self-Referencing Associations, it creates two relevant navigation properties named ProductCategory1 and ProductCategory2. Neither of these names is particularly helpful, one of these navigation properties refers to the parent category or the 0..1 side of the relationship. The other refers to the children or the * side of the relationship.
To understand which is which, right-click ProductCategory1, in the property window, the multiplicity for ProductCategory1 is * (many), so ProductCategory1 represents the navigation property for the children or subcategories (also it's of type EntityCollection<ProductCategory>) and the other one - ProductCategory2 - represents parent category for this category and it's of type ProductCategory. For your query, we are interested in this one.
In addition - to make your query more readable - you can rename ProductCategory1 to Subcategories and ProductCategory2 to ParentCategory.

Morteza Manavi
I just realized that it is actually a many to many relationship so I am actually getting p.ProductCategories which is an entity collection instead of p.ProductCategory.CategoryName
Mike
Ok, we'll take care of that, but the parent category is still a self reference column in the same ProductCategories table, correct?
Morteza Manavi
Yes, the parent category for the category is a self reference column in the ProductCategories table.
Mike
Ok, I've updated my code and it should works for you based on what you described.
Morteza Manavi
I only had to edit the last select to "pc => pc.CategoryID == product.ProductCategories.FirstOrDefault().ParentID" and it now works. Thanks for your help!
Mike
No problem, I'm glad it helped.
Morteza Manavi