我正在尝试将以下mysql查询转换为linq。但是我没有过去使用linq中的连接的经验。我可以得到一些关于如何处理这个问题的提示。
SELECT db.jm_job.jobID
, sum(MaterialPrice+LaborPrice+ExpensePrice) * db.jm_workorderdetail.quantity
FROM db.jm_workorderdetail
left join db.jm_workorder
on db.jm_workorderdetail.WorkOrderID=db.jm_workorder.WorkOrderID
left join db.jm_job
on db.jm_job.JobID=db.jm_workorder.JobID
group by db.jm_job.jobID
答案 0 :(得分:1)
LINQ中的内连接很简单,但左连接有点棘手,涉及临时LINQ变量。
显然,您在此处拥有MSDN文档:http://msdn.microsoft.com/en-us/library/bb397895.aspx
关于同一主题的另一篇SO帖子:LEFT OUTER JOIN in LINQ
关于JOIN如何在LINQ中工作的一些示例:http://msdn.microsoft.com/en-us/vstudio/ee908647.aspx#leftouterjoin
我将留下SELECT和WHERE块让你弄清楚,但这里大致是你的联接应该最终看起来如何:
var results = from wod in db.jm_workorderdetail
from wo in db.jm_workorder.Where(w => w.WorkOrderID == wod.WorkOrderID).DefaultIfEmpty()
from job in db.jm_job.Where(j => j.JobID == wo.JobID).DefaultIfEmpty()
select new {SELECT LOGIC GOES HERE}
这里最重要的部分是.DefaultIfEmpty()子句,因为如果WHERE不起作用,就会创建返回null的“左连接”行为
这也省略了group by子句,只需谷歌搜索'LINQ Group By'就可以找到一些好的资源
答案 1 :(得分:0)
SELECT db.jm_job.jobID,
sum( MaterialPrice + LaborPrice + ExpensePrice) * db.jm_workorderdetail.quantity
FROM db.jm_workorderdetail
LEFT JOIN db.jm_workorder
ON db.jm_workorderdetail.WorkOrderID = db.jm_workorder.WorkOrderID
LEFT JOIN db.jm_job on db.jm_job.JobID=db.jm_workorder.JobID
GROUP BY db.jm_job.jobID
认为它是这样的:
from detail in db.jm_workorderdetail
join wo in db.jm_workorder
on db.jm_workorderdetail.WorkOrderID equals db.jm_workorder.WorkOrderID
join job in db.jm_job
on db.jm_job.JobID equals db.jm_workorder.JobID
group jm_job by job.jobId into grp
select new
{
jobId = grp.key,
something = (MaterialPrice + LaborPrice + ExpensePrice) * wo.jm_workorderdetail.quantity
}
```