I am trying to learn linq, but finding it tough. Can someone convert this sql query to Linq...

SELECT 
    sl.Id,
    sl.Name,
    t.Quantity
FROM StorageLocations sl
LEFT JOIN PartLocations pl ON sl.Id = pl.StorageLocationId
LEFT JOIN (SELECT 
           PartLocationId, 
           SUM( CASE WHEN TransactionTypeId = 2 THEN Quantity * -1 
           ELSE Quantity END) AS Quantity
           FROM Transactions WHERE Active = '1'
           GROUP BY PartLocationId) t  ON pl.Id = t.PartLocationId  
WHERE t.Quantity < 1 OR  t.Quantity is null

Also I am making a MVC C# program, do I need to put the using context statement around the linq statement?

有帮助吗?

解决方案

You have a lot going on in this query, please let me know if you have any questions.

using(var context = new YourContext())
{
   var query = from sl in context.StorageLocations
               from pl in context.PartLocations.Where(x => sl.Id == x.StorageLocationId).DefaultIfEmpty()
               from t in 
               (
                 from tr in context.Transactions
                 where tr.Active == "1"
                 group tr by tr.PartLocationId into g
                 select new {
                   PartLocationId = g.Key,
                   Quantity = g.Sum(y => y.TransactionTypeId == 2 ? (y.Quantity * -1) : y.Quantity)
                 }
               ).Where(x => pl.Id == x.PartLocationId).DefaultIfEmpty()
               where t.Quantity < 1 || t.Quantity == null
               select new
               {
                 sl.Id,
                 sl.Name,
                 t.Quantity
               };
    var result = query.ToList();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top