I am trying to display a nullable date time in my JSON response. In my MVC Controller I am running the following query:
var re开发者_如何学Goquests =
(from r in _context.TestRequests
where r.scheduled_time == null && r.TestRequestRuns.Count > 0
select new
{
id = r.id,
name = r.name,
start = DateAndTimeDisplayString(r.TestRequestRuns.First().start_dt),
end = r.TestRequestRuns.First().end_dt.HasValue
? DateAndTimeDisplayString(r.TestRequestRuns.First().end_dt.Value)
: string.Empty
});
When I run requests.ToArray()
I get the following exception:
Could not translate expression '
Table(TestRequest)
.Where(r =>
((r.scheduled_time == null) AndAlso (r.TestRequestRuns.Count > 0)))
.Select(r => new <>f__AnonymousType18`4(id = r.id, name = r.name,
start = value(QAWebTools.Controllers.TestRequestsController).
DateAndTimeDisplayString(r.TestRequestRuns.First().start_dt),
end = IIF(r.TestRequestRuns.First().end_dt.HasValue,
value(QAWebTools.Controllers.TestRequestsController).
DateAndTimeDisplayString(r.TestRequestRuns.First().end_dt.Value),
Invoke(value(System.Func`1[System.String])))))'
into SQL and could not treat it as a local expression.
If I comment out the end =
line, everything seems to run correctly, so it doesn't seem to be the use of my local DateAndTimeDisplayString
method, so the only thing I can think of is Linq to Sql doesn't like Ternary operators? I think I've used ternary operators before, but I can't remember if I did it in this code base or another code base (that uses EF4 instead of L2S).
Is this true, or am I missing some other issue?
Modify the DateAndTimeDisplayString to accept a different argument type and have a query like this:
end = DateAndTimeDisplayString(r.TestRequestRuns.FirstOrDefault())
This way, you can do the ternary stuff in your code.
By the way, it's actually this part which looks bad, because the ternary gets translated to IIF and seems to be handled, maybe try a null string:
Invoke(value(System.Func`1[System.String])))))
Have you considered using the Null coalescing operationg? (??)
Your code would then look like this:
end = r.TestRequestRuns.First().end_dt ?? string.Empty
You could modify your DateAndTimeDisplayString method to return null if passed null.
精彩评论