tags:

views:

298

answers:

2
+2  Q: 

Linq Error

Get value out of DateTime column if null to return String.Empty else DateTime.ToShortDateString

What am i doing wrong => query produced below:

var queryable = from p in Products
 select new {
         selldate = p.SellEndDate == null
         ? string.Empty
         : p.SellEndDate.Value.ToShortDateString()  };

Error: InvalidOperationException: Could not translate expression 'Table(Product).Select(p => new <>f__AnonymousType01(selldate = IIF((p.SellEndDate = null), Invoke(value(System.Func1[System.String])), p.SellEndDate.Value.ToShortDateString())))' into SQL and could not treat it as a local expression.

+3  A: 

Basically what's happening here is that LINQ to SQL is taking your entire query and trying to convert it into something that SQL Server can understand. The problem, though, is that SQL Server has no concept of DateTime.ToShortDateString, so the conversion to SQL fails.

You'll have to change your query so that it just selects SellEndDate (which will get it as a Nullable<DateTime>) and then when you use the results of that query you can do the conversion to string. For example:

var list = (from p in Products
           select p.SellEndDate).ToList();

// calling ToList() above means we have the entire resultset in memory and
// no longer have to pass the query back to SQL Server

var stuff = from p in list select new
{ 
    selldate = p.SellEndDate == null ?
                   string.Empty :
                   p.SellEndDate.Value.ToShortDateString()
};
Matt Hamilton
I got this done as : var queryable = from p in Products let Date = (p.SellEndDate.Value != null) ? p.SellEndDate.Value.ToShortDateString() : String.Empty select new { SellDate = Date };it works.
Nev_Rahd
Wow, it looks like it goes to SQL and comes back to c# when the time comes to execute functions like ToShortDateString.
shahkalpesh
You don't really need to call ToList() - you can just call AsEnumerable(). That's enough to force it to use local execution.
Jon Skeet
@Jon, will the execution be different when ToList is called vs AsEnumerable? I mean - does it fetch 1 record, come to c#, call the ToShort.., go back to SQL and repeat
shahkalpesh
@Jon yeah I must admit I wasn't sure about AsEnumerable. LINQ can be so "late-bound" that I often just call ToList() just to be sure. ;-)
Matt Hamilton
+1  A: 

ToShortDateString doesn't seem to have equivalent SQL translation.
Use ToString instead.

shahkalpesh