Trying to get max date from table using Linq2Sql

The following linq2sql code is giving me a big 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 starts, "The specified method is not supported."

If I don't use a value or apply it, I get the following error:

**

Can't implicitly convert type 'System.DateTime? To' System.DateTime. Explicit conversion exists (are you missing the cast?)

**

0


a source to share


4 answers


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

      



+1


a source


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



I'm watching this one .

+1


a source


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

0


a source


After searching for a long time, I was able to find that the problem was related to using ADO.NET Data Services. Apparently they use a limited subset of Linq and it is currently not possible to use methods like Max, First, etc. Bummme

0


a source







All Articles