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
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 = ?
};
How do I execute a nested query in LINQ to get the value for TotalPurchases?
Thank you so much!
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()
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With