我是LINQ的新手并试图将下面的TSQL转换为LINQ,有什么方法可以做到这一点吗?感谢您的帮助。
这是我试图转换的SQL语句
SELECT [t5].[StatusID], [t5].[FriendlyName], sum(1) AS [Count]
FROM (
SELECT distinct [t0].DealID, [t0].[StatusID], [t1].[FriendlyName]
FROM [DR_Deal] AS [t0]
INNER JOIN [DR_DealStage] AS [t1] ON [t0].[StatusID] = [t1].[DealStageID]
INNER JOIN [DR_Deal_ApproverInfo] AS [t2] ON [t0].[DealID] = [t2].[DealID]
INNER JOIN [DR_Approver] AS [t3] ON [t2].[ApproverID] = ([t3].[ApproverID])
INNER JOIN [DR_Profile] AS [t4] ON [t3].[ProfileID] = ([t4].[ProfileID])
WHERE (LOWER([t4].[Email]) = @p0) OR (LOWER([t0].[CreatedBy]) = @p1)
) AS [t5]
GROUP BY [StatusID], [FriendlyName]
ORDER BY [t5].[StatusID]
EDITS
是的,上面的sql是使用linqpad生成的,这就是我真正想要转换为linq的内容
SELECT COUNT(DISTINCT [t0].DealID) AS count, [t0].[StatusID], [t1].[FriendlyName]
FROM [DR_Deal] AS [t0]
INNER JOIN [DR_DealStage] AS [t1] ON [t0].[StatusID] = [t1].[DealStageID]
INNER JOIN [DR_Deal_ApproverInfo] AS [t2] ON [t0].[DealID] = [t2].[DealID]
INNER JOIN [DR_Approver] AS [t3] ON [t2].[ApproverID] = ([t3].[ApproverID])
INNER JOIN [DR_Profile] AS [t4] ON [t3].[ProfileID] = ([t4].[ProfileID])
WHERE (LOWER([t4].[Email]) = LOWER(@Email)) OR (LOWER([t0].[CreatedBy]) = LOWER(@UserName))
GROUP BY [t0].[StatusID], [t1].[FriendlyName]
ORDER BY [t0].[StatusID]
而且我认为我找到了使用linq执行count(distinct)
的解决方案,我最初偶然发现,但仍然转换后的解决方案无法正常工作,我认为下面的linq代码无效,因为我正在使用 sql 2000 并且生成的sql已经嵌套选择并且似乎有一些限制与sql 2000.我仍然不确定我的结论,可能是linq blelow是错误的altogther或者可能有更好的方法写上面的sql。
var query = (from d in DR_Deal
join s in DR_DealStage
on d.StatusID equals s.DealStageID
join da in DR_Deal_ApproverInfo
on d.DealID equals da.DealID
join a in DR_Approver
on da.ApproverID equals a.ApproverID
join p in DR_Profile
on a.ProfileID equals p.ProfileID
where p.Email.ToLower().Equals("test@test.com")
|| d.CreatedBy.ToLower().Equals("test")
group d.DealID by new { d.StatusID, s.FriendlyName}
into grp
select new
{
StatusID = grp.Key.StatusID,
FriendlyName = grp.Key.FriendlyName,
Count = grp.Distinct().Count()
}).OrderBy(x=> x.StatusID);
答案 0 :(得分:0)
我认为有很多方法可以做到这一点,但我做了一些相似的事情并将其映射到一个对象。这个陈述并不完全适合您的问题,但您可以使用以下内容将不同的值与agregate(有,组,计数,总和)值等混合。
IEnumerable<MyObject> myObj
= (from d in dbContext.DR_Deal
/*DO ALL YOUR JOINS */
join ds in dbContext.DR_DealStage on d.statusID equals ds.dealstageID
where ds.mycolumn == myvalue
select new MyObject()
{
groupedByObject = d,
singleColumnsValue = ds.columnName
/* For calculated values have inner LINQ statements which join
back to elements from the main query. These can also
return objects*/
agregateValue = (from x in dbContext.OtherTable
where x.id == d.id).Count()
})
答案 1 :(得分:0)
我总是依靠101 LinQ样本