简体   繁体   English

实体框架简单报告

[英]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 . EF映射自引用关联时 ,它会创建两个相关的导航属性,分别为ProductCategory1ProductCategory2 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. 这两个名称都不是特别有用,这些导航属性之一是指父类别或关系的0..1端。 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 . 要了解哪个是哪个,请右键单击ProductCategory1,在属性窗口中,ProductCategory1多重性是*(多),所以ProductCategory1代表为孩子或子类别的导航属性(也很型的EntityCollection<ProductCategory> )和其他一个-ProductCategory2-表示该类别的父类别,其类型为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 . 除了-使您的查询更具可读性-您可以重命名ProductCategory1小类ProductCategory2ParentCategory。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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