如何将sql查询转换为linq到实体查询?

时间:2013-10-10 08:03:51

标签: sql linq-to-entities

  select sr.Name as Sale_Rep,ag.Name as Agent ,
         sum(tr.Amount) Debit_tran 
  from DebtorTransactions as tr 
       join Warranty as wr on tr.ProductID=wr.Id 
       join Agents as ag on ag.pkfAgentID=wr.fldAgentID 
       join SalesReps as sr on wr.fldSrId =sr.pkfSrID 
  where tr.Product=0  
  group by ag.Name, sr.Name 

我想将此查询转换为Linq to Entity但不能...可以将此查询转换为Linq to entity for me plz

这是我尝试过的:

var abc= from tr in db.DebtorTransactions 
         from wr in db.Warranties 
         from sr in db.SalesReps 
         from ag in db.Agents 
         where tr.ProductID==wr.Id 
            && ag.pkfAgentID==wr.fldAgentID 
            && wr.fldSrId ==sr.pkfSrID 
            && tr.Product==0 
         select new { ag.Name, sr.Name, tr.Amount };

但我没有得到任何输出

2 个答案:

答案 0 :(得分:1)

要匹配您的SQL查询,您需要按相同的列进行分组:

from tr in db.DebtorTransactions 
join wr in db.Warranties on tr.ProductID equals wr.Id
join ag in db.Agents on wr.fldAgentID equals ag.pkfAgentID
join sr in db.SalesReps on wr.fldSrId equals sr.pkfSrID 
group tr 
    by new { Sale_Rep = sr.Name, Agent = ag.Name }
    into transactions
select new {
    transactions.Key.Sale_Rep,
    transactions.Key.Agent,
    Debit_tran = transactions.Sum(tr => tr.Amount)
}

答案 1 :(得分:0)

var abc = from tr in db.DebtorTransactions 
          join wr in db.Warranties tr.ProductID equals wr.Id
          join sr in db.SalesReps wr.fldSrId equals sr.pkfSrID 
          join ag in db.Agents wr.fldAgentID equals ag.pkfAgentID
          where tr.Product==0 
          select new { ag.Name, sr.Name, tr.Amount };