Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - Nested Query

Tags:

c#

sql

linq

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!

like image 865
user208662 Avatar asked May 18 '26 04:05

user208662


1 Answers

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()
              };
like image 61
BrokenGlass Avatar answered May 19 '26 18:05

BrokenGlass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!