简体   繁体   中英

Sql Query into Linq to Entity Framework

I'm wondering if it is even possible to write the below sql query as a LINQ to Entity statement. Below is a simplified example of a real world problem that I'm trying to figure out:

Select
c.CustomerID,
c.CustomerName,
(Select count(p.ProductID) from Products p 
    where p.CustomerID = c.CustomerID and p.Category = 'HomeAppliance') as ApplianceCount,
(Select count(p.ProductID) from Products p
    where p.CustomerID = c.CustomerID and p.Category = 'Furnishing') as FurnishingCount
from Customer c
where 
c.CustomerMarket = 'GB'
order by c.CustomerID desc;

Any suggestions would be appreciated. Performance of the LINQ to Entity would need to be considered as it would involve retrieving lot of rows.

Something like (assuming the obvious context):

var res = await (from c in dbCtx.Customers
                 where c.CustomerMarket = "GB"
                 let homeCount = c.Products.Where(p => p.Category = "HomeAppliance").Count()
                 let furnCount = c.Products.Where(p => p.Category = "Furnishing").Count()
                 orderby c.CustomerID descending
                 select new {
                   CustomerID = c.CustomerID,
                   CustomerName = c.CustomerName,
                   ApplianceCount = homeCount,
                   FurnishingCount = furnCount
                 }).ToListAsync();

Performance of the LINQ to Entity would need to be considered as it would involve retrieving lot of rows.

You'll need to confirm the SQL generated is reasonable (best way to help that is not getting more columns than you need), after that performance is down to how well the server runs that SQL.

Yes, it is possible:

customers
    .Where(cust => cust.CustomerMarket == "GB")
    .Select(cust => new
    {
        cust.CustomerId,
        cust.CustomerName,
        ApplianceCount = products
            .Where(prod => prod.CustomerId == cust.CustomerId && prod.Category == "HomeAppliance")
            .Select(prod => prod.ProductId)
            .Count(),
        FurnishingCount = products
            .Where(prod => prod.CustomerId == cust.CustomerId && prod.Category == "Furnishing")
            .Select(prod => prod.ProductId)
            .Count(),
    });

Here both customers and products are IQueryable<T> s of the respective type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM