将此SQL查询转换为Linq

时间:2014-04-29 11:35:47

标签: c# sql sql-server linq linq-to-sql

我正在努力学习linq,但发现它很难。有人可以将此SQL查询转换为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

另外我正在制作一个MVC C#程序,我是否需要在linq语句周围添加 using context 语句?

1 个答案:

答案 0 :(得分:1)

此查询中有很多内容,如果您有任何疑问,请与我们联系。

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();
}