LINQ-嵌套查询 [英] LINQ - Nested Query
本文介绍了LINQ-嵌套查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个SQL语句,试图将其转换为LINQ查询.我需要这样做是因为我无法编辑数据库:(.无论如何,我都有一个如下所示的SQL语句:
I have a SQL Statement that I am trying to convert to a LINQ query. I need to do this because I can't edit my database :(. Regardless, I have a SQL Statement that looks like the following:
SELECT
CustomerID,
FirstName,
LastName,
Gender,
BirthMonth,
(SELECT COUNT(ID) FROM PurchaseOrder WHERE [CustomerID]=CustomerID) as TotalPurchases
FROM
MyEntities
除了嵌套查询部分,我知道如何在LINQ中执行所有操作.目前,我有以下内容:
I know how to do everything in LINQ excepted for the nested query part. Currently, I have the following:
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的值?
How do I execute a nested query in LINQ to get the value for TotalPurchases?
非常感谢您!
推荐答案
您也可以将Linq to Entities查询嵌套:
You can just nest the Linq to Entities query as well:
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()
};
这篇关于LINQ-嵌套查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文