Neerav

Neerav

  • NA
  • 26
  • 1.9k

Converting Sql Query to Linq

Mar 15 2018 6:31 AM
Hello Friends,
 
I have a chart which i have built using the linq query which is as below
  1. public List<DatewiseStockDetailViewModel> getProductSoldByYear(int CompanyId)  
  2. {  
  3. var userData = (from m in datewise.GetAll()  
  4. join s in stock.GetAll()  
  5. on m.Stock_Id equals s.Stock_Id  
  6. join p in product.GetAll()  
  7. on s.ProductId equals p.ProductId  
  8. where s.CompanyId == CompanyId && m.IsProductDeducted == true  
  9. group new { m, s, p } by new { Convert.ToDateTime(m.CreatedDate.ToString()).Year, p.ProductName, p.ProductId } into g  
  10. select new DatewiseStockDetailViewModel  
  11. {  
  12. productId = Convert.ToInt32(g.Key.ProductId),  
  13. productName = g.Key.ProductName,  
  14. ProductQuantity = g.Sum(x => x.m.ProductQuantity),  
  15. year = g.Key.Year.ToString()  
  16. }).Distinct().ToList<DatewiseStockDetailViewModel>();  
  17. return userData;  
  18. }  
The Output for the same is 
 
But i want to write a code by which i am able to use the pivot code in linq to get the output as
 
ProductName   2016   2017   2018
cedar oil            NULL  16         34
computer           NULL   8         1
grain                  NULL   21       NULL
Keyboard            2           3       NULL
marie                  NULL  26     NULL
Pine Oil               NULL   4            5
harabhara kebabNULL      5         1
 
For this i have written the sql query
  1. select *  
  2. from(  
  3. select pd.ProductName,year(dsm.CreatedDate)as [Year],sum(dsm.ProductQuantity)as ProductQuantity  
  4. from dbo.DatewiseStockDetailMaster dsm  
  5. left join dbo.StockMaster sm on  
  6. dsm.stock_Id=sm.stock_Id  
  7. left join dbo.ProductDetails pd  
  8. on sm.ProductId=pd.ProductId  
  9. where sm.CompanyId=17 and dsm.IsProductDeducted=1  
  10. group by year(dsm.CreatedDate),pd.ProductName  
  11. )as SourceTable  
  12. pivot  
  13. (  
  14. sum(ProductQuantity)  
  15. for [Year]  
  16. in([2016],[2017],[2018])  
  17. )  
  18. as pivotTable  
Can anyone help me convert this SQL to Linq

Answers (3)