Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the latest date inserted from the table with Linq to entities

how to retrieve the latestdate inspected from a column

In our app a user can inspect an item and when it inspected the current date is entered into the table. For the same item someother can uninspect it this time nothing is inserted into the table. Another user can inspect it and current date is inserted I need to get the LatestDate Inserted..how to get this with Linq

Let say table name is Statuses and col name is LastdateInspected

like image 952
GANI Avatar asked Mar 01 '12 22:03

GANI


People also ask

How to get latest Date from linq in c#?

Select(grp => new { ID = grp.Key.ID, Day = grp. Key. Day, Date = grp.

How do I get the last inserted record in Linq?

Go to your SSMS or whatever tool you use and run your queries from there. If you can get your output from there then you can translate it to code. If you look at the previous comments, everyone, in essence, is telling you to review your data model.

Can I use LINQ with Entity Framework?

Entity Framework Core uses Language-Integrated Query (LINQ) to query data from the database. LINQ allows you to use C# (or your . NET language of choice) to write strongly typed queries.

What is Linq to Entity in C#?

LINQ to Entities provides Language-Integrated Query (LINQ) support that enables developers to write queries against the Entity Framework conceptual model using Visual Basic or Visual C#. Queries against the Entity Framework are represented by command tree queries, which execute against the object context.


1 Answers

Sounds like you want something like:

var query = db.Statuses
              .OrderByDescending(x => x.LastDateInspected)
              .FirstOrDefault();

That will return null if there are no entries, or the value with the latest LastDateInspected value otherwise (i.e. the first result, having ordered by the last date inspected latest-first).

That will get you the whole record, of course. If you only want the date, you can select the LastDateInspected column.

like image 176
Jon Skeet Avatar answered Nov 20 '22 02:11

Jon Skeet