Set String To "" In A LINQ Query Where NULL
I have the following query, sometimes ExpirationDate
is null which blows up the query and the application crashes. If ExpirationDate
is null I want to return ""
for 开发者_如何学JAVAExpirationDate
. How do I put this if condition in LINQ?
List<PData> pressData =
(from press in dataContext.CPress
where press.ID.ToString() == this.PressID
select new PData
{
Heading = press.Heading,
Description = press.MetaDescription,
DatePublished = press.PublishDate.ToShortDateString(),
ExpirationDate = press.ExpirationDate.Value.ToShortDateString(),
Body = press.BodyContent,
CreatedBy=press.CreatedBy
}).ToList();
UPDATE :
Adding the code Jon suggested I get the following exception
Could not translate expression 'Table(CPress).Where(press =>
(press.PressID.ToString() = Invoke(value(System.Func`1[System.String])))).Select(press => new PData() {Heading = press.Heading, Description = press.MetaDescription, DatePublished = press.PublishDate.ToShortDateString(), ExpirationDate = IIF((press.ExpirationDate = null), "", press.ExpirationDate.Value.ToShortDateString()), Body = press.BodyContent, ID = press.PressID, CreatedBy = press.CreatedBy})' into SQL and could not treat it as a local expression.
Taking ExpirationDate out totally the exception goes away
I'd use:
ExpirationDate = press.ExpirationDate == null ? "":
press.ExpirationDate.Value.ToShortDateString()
EDIT: Having said that, it will only work around the immediate problem. I agree with Nelson's approach of keeping it as a DateTime?
and performing the conversion at display time. Aside from anything else, that means you can apply the appropriate culture information etc for the user at that point.
I know it doesn't answer you question directly, but...
If possible, I would keep the date as DateTime?
. Usually you want to format it (ToShortDateString()
, etc.) whenever you display it, not before.
Edit: Similarly in where press.ID.ToString() == this.PressID
: this.PressID
would ideally match the type of press.ID
. Really, the language is strongly-typed for a reason. If you make all your variables strings, it defeats the whole purpose.
Of course there are some unusual circumstances where you might have to do this and yours may be one of them, but I see no indication that is the case.
Personally I'd go for the option that @Jon Skeet has suggested, but an alternative if you don't like the syntax is to write an extension method and call that
public static string ToShortDateStringOrEmpty(this DateTime? dt)
{
if (dt == null)
return String.Empty;
else
return dt.ToShortDateString();
}
This has the advantage of being neater if you're doing a complex query (such as if the order isn't null, show me the sum of all the line items) and traversing a lot of objects.
精彩评论