在 LinqToSql 中使用 LEFT OUTER JOIN 时如何处理 DateTime 字段

发布于 2024-08-14 05:13:28 字数 696 浏览 8 评论 0原文

我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆で 2024-08-21 05:13:28

在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文