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.