How to access next and previous record with C # using Entity Framework

7

I'm developing a Windows Form application, with Entity Framework 6 + MySQL.

As is common in systems, I have in each form navigation buttons (First Record, Previous Record, Next Record, Last Record)

The question: Is there any definite syntax (LINQ or Lambda) that leads me directly to the previous or next EXISTING record?

Example: I have the form displaying the record ID = 6. If I click the previous button, I should display record 5. Similarly, the next one is record 7. However, if record 7 does not exist, record 8 must be displayed .

I can easily solve with programming logic, but I would like to know if there is a native language way to solve this type of operation.

Thank you.

    
asked by anonymous 02.08.2015 / 02:54

2 answers

6

The most elegant way I know is used to create paging in ASP.NET MVC applications, using Skip() and Take() :

var registroAtual = 6;
var registroAnterior = contexto.Entidade.Skip(registroAtual - 2).Take(1).FirstOrDefault();
var proximoRegistro = contexto.Entidade.Skip(registroAtual).Take(1).FirstOrDefault();

EDIT

Assuming I specifically want to find the records before and next to Id 6:

var registroAnterior = contexto.Entidade.Where(e => e.Id <= 6).OrderByDescending(e => e.Id).Skip(1).Take(1).FirstOrDefault();
var proximoRegistro = contexto.Entidade.Where(e => e.Id >= 6).OrderBy(e => e.Id).Skip(1).Take(1).FirstOrDefault();
    
02.08.2015 / 03:42
6

You can use the following:

For the item prior to ID 6:

Context.NomeEntidades.where(c=>c.ID<6).OrderByDescending(c=>c.ID).firstOrDefault();

And for the following:

Context.NomeEntidades.where(c=>c.ID>6).OrderBy(c=>c.ID).firstOrDefault();
    
02.08.2015 / 03:24