我有一个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的值?
太感谢了!
您也可以嵌套Linq to Entities查询:
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() };