避免实体查询没有结果时出现错误
我有一个简单的实体查询:
Dim rhcexists = From p In dbContracts.Signatures _
Where p.StudentID = people_code_id _
And p.ContractType = "rhc" _
Order By p.ID Descending _
Select p
然后我使用 if..then 检查其中一个结果值是否比六个月前更新:
If rhcexists.First.SignatureDate > Date.Today.AddMonths(-6) Then
End If
但是,如果没有返回结果,则会返回错误。如果根本没有价值,我有没有办法告诉它表现得好像日期早于六个月?例如,我可以伪做类似的事情:
If Exists(rhcexists.First.SignatureDate, Date.Today.AddMonths(-8)) > Date.Today.AddMonths(-6) Then
End If
I have a simple Entity query:
Dim rhcexists = From p In dbContracts.Signatures _
Where p.StudentID = people_code_id _
And p.ContractType = "rhc" _
Order By p.ID Descending _
Select p
I then check whether one of the result values is more recent than six months ago using an if..then like so:
If rhcexists.First.SignatureDate > Date.Today.AddMonths(-6) Then
End If
However, if there are no results returned this will return an error. Is there a way for me to tell it to act as if the date is older than six months if there is no value at all? e.g., could I in pseudo do something like:
If Exists(rhcexists.First.SignatureDate, Date.Today.AddMonths(-8)) > Date.Today.AddMonths(-6) Then
End If
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用
First
扩展方法,如果没有结果,该方法将会失败。您可以这样做:如果没有结果,
FirstOrDefault
将返回Nothing
,而不是抛出异常。You're using the
First
extension method, which will go bang if there are no results. You could do:FirstOrDefault
will returnNothing
if there are no results, instead of throwing an exception.使用 FirstOrDefault 而不是 First。然后你可以设置默认返回的内容
Use FirstOrDefault instead of First. Then you can setup what default returns