2014-09-17 1 views
0

값 다음 제품 ID의 전체 주식을 요약하는 나는 현재 제품의 내용을 선택하고 주식 테이블에 두번째 전화를 걸SQL 테이블을 가입하고 SUM 내가 두 개의 테이블이

제품 및 재고 그것은 매우 느립니다.

경우 : 내가 좋아하는 것이 무엇

아래와 같은 제품 테이블의 내용을 얻을 수 있으며 (제품 ID에 연결) 주식 테이블에 StockInHand의 총 합계를 뭔가를 데이터베이스에 단일 통화를 만드는 것입니다 누군가가 내가 성공적으로 테이블에 가입하고 ProductID에 대한 동일한 호출에서 Stock 테이블의 QtyInHand를 합산하면 정말 좋을 것입니다.

내 원래 코드 :

  var query = from products in data.Products 
         where products.Deleted == false 
         orderby products.FullPath 
         select new 
         { 
          ProductID = products.ProductID, 
          Description = products.Description, 
          Price = products.RetailPrice ?? 0, 
>>>> VERY SLOW!    StockLevel = cProducts.GetStockTotalForProduct(products.ProductID), 
          FullPath = products.FullPath 
         }; 

      if (query != null) 
      { 
       dgv.DataSource = query; 
      } 

나는 테이블을 조인해야한다는 것을 이해하지만, 나는이 사용 LINQ 할 구문 확실치 :이 일을해야한다고 생각

var query = 
       from product in data.Products 
       join stock in data.ProductStocks on product.ProductID equals stock.ProductID 
DO SOMETHING CLEVER HERE!! 
       select new 
       { 
        ProductID = product.ProductID, 
        Description = product.Description, 
        Price = product.RetailPrice ?? 0, 
        StockLevel = >>>>>>>> CALL TO THE OTHER TABLE IS VERY SLOW, 
        FullPath = products.FullPath 
       }; 

      if (query != null) 
      { 
       dgv.DataSource = query; 
      } 

답변

1

난 당신이 합계를 할 수있는 group by 찾고있는 생각 :

var query = from p in data.Products 
      join s in data.ProductStocks on p.ProductID equals s.ProductID 
      group s by p into g 
      select new { 
       ProductID = g.Key.ProductID, 
       Description = g.Key.Description, 
       Price = g.Key.Price ?? 0, 
       FullPath = g.Key.FullPath, 
       StockLevel = g.Sum(s => s.StockInHand) 
      }; 
+0

완벽한 ... – Belliez

1

을 :

var query = from product in data.Products 
       join stock in data.ProductStocks on product.ProductID equals stock.ProductID 
       select new 
       { 
        ProductID = product.ProductID, 
        Description = product.Description, 
        Price = product.RetailPrice ?? 0, 
        StockLevel = stock.StockLevel, 
        FullPath = products.FullPath 
       };