Get the next and previous entity of a specific identifier with Entity Framework?

I have an employee form for editing or displaying personal information in my project using ASP.NET MVC5, this form receives Idand displays information about the employee.

In this form, I must have a button Nextand Previousso that the administrator can go to the next or previous employee (if there is no employee, the button must be disabled). On the other hand, this form has a sort variable that is set by Admin.

So, I want to put two tags <a />with the next and previous employee ID associated with the employee form.

<< Previous employee Id by sorting             Next employee Id by sorting >>

I know how to get the current employee, it is quite easy in the Entity Framework.

But how can I get the next and previous identifier of the current identifier with Entity Framework?

+4
source share
2 answers

If I understand your question correctly, the concept of “next” or “previous” is related to the rule that you use for sorting. Now let me use a simple "order by ID" as a sort rule. With three queries, you can get the current, next, and previous items:

int id = 562;  // the current id
var curr = (from x in dbCtx.Employees where x.ID == id select x).Single();
var prev = (from x in dbCtx.Employees where x.ID < id orderby x.ID descending select x).FirstOrDefault();
var next = (from x in dbCtx.Employees where x.ID > id orderby x.ID ascending select x).FirstOrDefault();

You can reduce from 3 to 2 queries. The first and second can be mixed in one request. This query returns the current and previous item:

(from x in dbCtx.Employees where x.ID <= id orderby x.ID descending select x).take(2)  
+9
source

, . . , , , .

PageController ActionResults:

public ActionResult EditNext(int id)
{
    Page next= db.Pages.Where(x => x.Id > id).FirstOrDefault();
    return View("~/Areas/Admin/Views/Pages/Edit.cshtml", next);
}

public ActionResult EditPrev(int id)
{
    Page prev = db.Pages.Where(x => x.Id < id).OrderByDescending(y => y.Id).FirstOrDefault();
    return View("~/Areas/Admin/Views/Pages/Edit.cshtml", prev);
}

:

<div layout="row" layout-align="space-between center" ng-cloak> 
    <md-button class="md-primary md-btn-small" href="@Url.Action("EditPrev", "Pages", new { id = Model.Id })">Previous</md-button>
    <md-button class="md-primary md-btn-small" href="@Url.Action("EditNext", "Pages", new { id = Model.Id })">Next</md-button>
</div>
+1

All Articles