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 ExpirationDate. 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 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.PressIDwould ideally match the type ofpress.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.