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 = ...
}
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.
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.
精彩评论