tags:

views:

213

answers:

4

The following linq2sql code is causing me much headache and I was hoping someone could help

 DateTime _maxRecordedDate = (from snapshot in _ctx.Usage_Snapshots
                                         where snapshot.server_id == server_id
                                         orderby snapshot.reported_on descending
                                         select snapshot.reported_on).First().Value;

This code works in LinqPad and compiles fine but when the project runs there is a 'Specified Method is Unsupported".

If I don't use Value or cast it I get the following error:

**

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)

**

+1  A: 

Does it not want First().Value? Maybe just First().

I'm looking at this.

DOK
using First() alone causes a DateTime? != DateTime error.
jdiaz
Yeah, so either assign it to a DateTime? variable, or use var _maxRecordedDate.
Richard Hein
+1  A: 

DateTime? _maxRecordedDate = _ctx.Usage_Snapshots.Where(s => s.server_id == server_id).Max(d => d.reported_on);

Robert
Same error as using First() Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)
jdiaz
Yeah, the type being returned is DateTime? (Nullable<DateTime>), just assign it to the correct matching type.
Richard Hein
A: 

Robert provided a better way to do it, but the problem with your code is that you are calling .Value and that will running in the context of SQL Server, so there is no .Value operation that can be translated to SQL. You'd have to call .ToList().First().Value, or assign to DateTime?. Since you can't call .First().ToList() ... since First() returns a single DateTime? then you're better off just assigning to DateTime?, because you don't want to return the entire list from SQL.

Richard Hein
returns 'Specified Method Unsupported'. It seems that anything added to the end of the select causes an error
jdiaz
A: 

After much searching I was able to find that the problem stems from using ADO.NET Data Services. Apparently they use a limited subset of Linq and it's currently not possible to use methods like Max, First, etc. Bummme

jdiaz
You didn't mention ADO.NET Data Services in your question. That would have nothing to do with your error message. Just call .ToList().First().
Richard Hein