简体   繁体   中英

Entity Framework Simple Report

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 .

如果我正确地理解了您的架构,那应该是简单获取产品列表的简单情况,并且您的显示列表应该只显示“ thisProduct.Category.Name”列。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM