在 LinqToSql 中使用 LEFT OUTER JOIN 时如何处理 DateTime 字段
我有 2 张表,员工表和缺勤表。我想要进行左外连接,以便获得所有员工和任何相关的缺勤情况。在 LINQ2SQL 中,我可以使用以下内容来创建 LEFT OUTER JOIN:
from e in Employees
join a in Absences on e.EmployeeID equals a.EmployeeID into ae
from x in ae.DefaultIfEmpty()
select new { FullName = e.Surname + ", " + e.Forename }
这是我正在寻找的内容,但我想显示任何缺勤开始日期。我可以将 select 语句更改为,
select new { FullName = e.Surname + ", " + e.Forename, x.StartDate }
但出现错误,因为 DateTime 不可为空。 如果没有 StartDate 或有实际日期,如何显示空字符串?我尝试使用 x.StartDate.ToShortDateString() 但如果它为空,这显然会引发错误,我也尝试过:
select new {Surname = e.Surname, StartDate = x.StartDate == null ? "" : x.StartDate }
但这也不起作用。有什么建议吗?
I have 2 tables, Employee and Absence. I want to do a left outer join so that I get all employees and any associated absences. In LINQ2SQL I can use the following to create the LEFT OUTER JOIN:
from e in Employees
join a in Absences on e.EmployeeID equals a.EmployeeID into ae
from x in ae.DefaultIfEmpty()
select new { FullName = e.Surname + ", " + e.Forename }
This is what I'm looking for but I want to show any absence start dates. I can change the select statement to
select new { FullName = e.Surname + ", " + e.Forename, x.StartDate }
but I get an error because DateTime is not nullable.
How can I show an empty string if there is no StartDate or the actual Date if there is one? I tried using x.StartDate.ToShortDateString() but this obviously throws an error if it's null, I've also tried:
select new {Surname = e.Surname, StartDate = x.StartDate == null ? "" : x.StartDate }
but this doesn't work either. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 select 语句中写入
select new { FullName = e.Surname + ", " + e.Forename,StartDate=(DateTime?)x.StartDate }
这应该适合您。
In select statement write
select new { FullName = e.Surname + ", " + e.Forename,StartDate=(DateTime?)x.StartDate }
This should work for you.