Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework do Paging on a query with a join

I have a query with a left join in it:

   var query = (from v in context.Vehicles

                //left join vehicleAttributes
                join va in context.VehicleAttributes on v.VehicleId equals va.VehicleId into vAttributes
                from vehicleAttributes in vAttributes.DefaultIfEmpty()

                where v.FleetId == fleetId

                select new { v, vehicleAttributes });

And now I need to do a paging on it.

this works but gets all rows, so much more than i actually need

query.ToList().Select(x => x.v).Distinct().Skip(10 * (page - 1)).Take(10).ToList();

this is what I tried instead but now I don't have the joint values

query.Select(x => x.v).Distinct().ToList().Skip(10 * (page - 1)).Take(10).ToList();

any ideas?

Thanks

like image 441
Timothy Avatar asked Jun 11 '13 14:06

Timothy


People also ask

How to do paging in mvc table?

MVC from NuGet Package manager, so go to the NuGet Package Manager and then install PagedList. MVC. Now add a controller with name EmployeeController and write the following code. Now add two views, One for adding some Employee and second for Views Employee and Paging and Sorting.

How to create pagination in asp net mvc?

In the ASP . NET application to insert page pagination, first need to install Paged List and PagedList. MVC from the NuGet packages for the project. Then I have included sample method which return the list of books from database.

What is keyset pagination?

Keyset pagination (also known as the "seek method") is used to fetch a subset of records from a table quickly. It does this by restricting the set of records returned with a combination of WHERE and LIMIT clauses.


1 Answers

The ToList() triggers the call to the database so you need to only do this after you apply the Skip and Take. You'll need an OrderBy clause as well.

You should be able to do something like this:

var data = (from v in context.Vehicles
         join va in context.VehicleAttributes on v.VehicleId equals va.VehicleId into vAttributes
         from vehicleAttributes in vAttributes.DefaultIfEmpty()
         where v.FleetId == fleetId
         select new { v, vehicleAttributes })
         .OrderBy(p => p.v.FleetId)
         .Skip(10 * (page - 1))
         .Take(10)
         .ToList();
like image 86
Sean Kenny Avatar answered Oct 10 '22 22:10

Sean Kenny