Check latest registration through linq

2

I have to get the most updated record from the following table

for the most recent record query (the most recent date) I have the following sentence

contexto.Set<Tabla1>().LastOrDefault(x => x.Id_Registro == idRegistro);

is this form of consultation correct for this last record? or do I have to apply another filter to the query? in this case, how should this filter?

Greetings and thanks

    
asked by Luis Gabriel Fabres 22.03.2017 в 14:00
source

3 answers

3

I do it like this:

var LastRegister = Contexto.tabla1
            .OrderByDescending(x => x.fecha)
            .First().fecha;
    
answered by 07.04.2017 в 21:42
2

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
    
answered by 08.04.2017 в 04:32
1

This weird means as you do the query I would do this

Contexto.Table1.orderByDesc().FirstorDefault();

And so you will get the last record the table has Sorry I did not put it in code format of the page is that I did from the mobile

    
answered by 07.04.2017 в 04:32