简体   繁体   English

使用LINQ to SQL在查询中包括条件检查

[英]Include conditional checking in query with LINQ to SQL

Suggestion either in C# or VB.NET are welcome. 欢迎在C#或VB.NET中提出建议。

Table relationship: 表关系:

  • Student 1:N TimeSheet (FK StudentId) 学生1:N时间表(FK StudentId)
  • TimeSheet 1:N TimeRecord (FK TimeSheetId) TimeSheet 1:N TimeRecord(FK TimeSheetId)

     Dim query = From s In db.Students _ Let pair = (From ts In db.TimeSheets _ Join tr In db.TimeRecords On tr.TimeSheetId Equals ts.TimeSheetId _ Where ts.IsArchive = False And ts.IsCompleted = False _ Group By key = New With {ts.TimeSheetId, ts.StudentId} Into TotalHour = Sum(tr.BonusHour)) _ From part In pair _ Where part.key.StudentId = s.StudentId _ Select New With {.StudentId = s.StudentId, .AssignedId = s.AssignedId,.TotalTime = part.TotalHour} 

Here's the result of the query: 这是查询的结果:

  • 734 -- 159 : 9 hrs 35 mm 28 sec 734-159:9小时35毫米28秒
  • 2655 -- 160 : 93 hrs 33 mm 50 sec 2655-160:93小时33毫米50秒
  • 1566 -- 161 : 37 hrs 23 mm 53 sec 1566-161:37小时23毫米53秒
  • 3114 -- 162 : 25 hrs 0 mm 21 sec 3114-162:25小时0毫米21秒

Wanted result of query: 想要的查询结果:

  • 733 -- 158 : 0 hr 0mm 0 sec 733-158:0小时0毫米0秒
  • 734 -- 159 : 9 hrs 35 mm 28 sec 734-159:9小时35毫米28秒
  • 736 -- 169 : 0 hrs 0mm 0sec 736-169:0小时0毫米0秒
  • 2655 -- 160 : 93 hrs 33 mm 50 sec 2655-160:93小时33毫米50秒
  • 1566 -- 161 : 37 hrs 23 mm 53 sec 1566-161:37小时23毫米53秒
  • 3114 -- 162 : 25 hrs 0 mm 21 sec 3114-162:25小时0毫米21秒
  • 2165 -- 189 : 0 hr 0 mm 21 sec 2165-189:0小时0毫米21秒

There are some TimeSheet that have no TimeRecord, which I need to select as well. 有些TimeSheet没有TimeRecord,我也需要选择它。 How can I select all of them to make selection like above wanted result? 我如何选择所有这些对象以进行如上所需结果的选择? I'm thinking of how I can include some condtion checking in the query to see if this TimeSheet has no TimeRecord then no need to Sum(tr.BonusHour) just assign TotalHour to zero. 我正在考虑如何在查询中包括一些条件检查,以查看此TimeSheet是否没有TimeRecord,然后无需将Sum(tr.BonusHour)分配为零即可。 I don't know it's right way to go. 我不知道这是正确的方法。

Any sugestion is welcome. 欢迎提出任何建议。

You can try doing something like this with the Sum (C#): 您可以尝试使用Sum (C#)执行以下操作:

Sum(tr.BonusHour ?? 0)

which would be the same as 这将与

Sum(tr.BonusHour != null ? tr.BonusHour : 0)

I am not sure what type your BonusHour has, so you would use zero-correspondent object of this type instead of the 0 in the sample. 我不确定您的BonusHour具有哪种类型,因此您将使用此类型的零对应对象,而不是示例中的0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM