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?)
**
a source to share
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.
a source to share