No, the use of LastOrDefault()
is not appropriate in this case. That function is designed to get the last record that meets some condition . But in your case, what you want is to obtain the last record according to the order based on a certain column.
For this, the idea behind the response of @Software lover is correct. That is, to use OrderByDescending()
to sort the records by date, and then use FirstOrDefault()
to return the first record (or last record depending on your perspective).
Correcting the sentence proposed in the response of @Software lover a bit, the sentence would be:
var registroMasActualizado =
contexto.Set<Tabla1>()
.OrderByDescending(t => t.Fecha)
.FirstOrDefault();
This will produce a very efficient SQL query. For example, in SQL Server, the generated query will look like this (note the use of ORDER BY
combined with TOP (1)
:
SELECT TOP (1)
[Extent1].[Id_Registro] AS [Id_Registro],
[Extent1].[Fecha] AS [Fecha],
[Extent1].[motivo] AS [motivo],
[Extent1].[estado] AS [estado]
FROM [dbo].[Tabla1] AS [Extent1]
ORDER BY [Extent1].[Fecha] DESC