LINQ - 嵌套查询

时间:2012-02-17 20:27:05

标签: c# sql linq

我有一个SQL语句,我试图转换为LINQ查询。我需要这样做,因为我无法编辑我的数据库:(。无论如何,我有一个如下所示的SQL语句:

SELECT
  CustomerID,
  FirstName,
  LastName,
  Gender,
  BirthMonth,
  (SELECT COUNT(ID) FROM PurchaseOrder WHERE [CustomerID]=CustomerID) as TotalPurchases
FROM
  MyEntities

我知道如何在LINQ中执行除嵌套查询部分之外的所有操作。目前,我有以下内容:

var results = from x in context.MyEntities 
              select new Customer() 
              { 
                CustomerID = x.CustomerID, 
                FirstName = x.FirstName, 
                LastName = x.LastName, 
                Gender = x.Gender, 
                BirthMonth = x.BirthMonth,
                TotalPurchases = ? 
              };

如何在LINQ中执行嵌套查询以获取TotalPurchases的值?

非常感谢你!

3 个答案:

答案 0 :(得分:6)

您也可以将Linq嵌套到实体查询中:

var results = from x in context.MyEntities 
              select new Customer() 
              { 
                CustomerID = x.CustomerID, 
                FirstName = x.FirstName, 
                LastName = x.LastName, 
                Gender = x.Gender, 
                BirthMonth = x.BirthMonth,
                TotalPurchases = context.PurchaseOrders
                                        .Where(po=>po.CustomerId == x.CustomerId)
                                        .Count()
              };

答案 1 :(得分:3)

只需对" PurchaseOrders"的导航属性进行计数。我假设是在客户实体上。

TotalPurchases = x.PurchaseOrders.Count()

答案 2 :(得分:0)

在使用Linq to Entities时,BrokenGlass的答案对我不起作用,并导致错误声明"无法创建类型' MyEntity'的常量值。在此上下文中仅支持原始类型或枚举类型。"

为了克服这个问题,我使用了以下内容:

var results = from x in context.MyEntities
              join po in context.PurchaseOrders on x.CustomerID equals po.CustomerID into purchaseOrders
              select new Customer() 
              { 
                CustomerID = x.CustomerID, 
                FirstName = x.FirstName, 
                LastName = x.LastName, 
                Gender = x.Gender, 
                BirthMonth = x.BirthMonth,
                TotalPurchases = purchaseOrders.Count()
              };