问题
In the MVC CORE demo from https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page the Contoso university sample program uses a model on the paginating example page
var students = from s in _context.Students
select s;
return View(await PaginatedList<Student>.CreateAsync(students.AsNoTracking(), page ?? 1, pageSize));
while the viewmodel gets passed back as a complete entity like this
var viewModel = new InstructorIndexData();
viewModel.Instructors = await _context.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.CourseAssignments)
.ThenInclude(i => i.Course)
.ThenInclude(i => i.Department)
.OrderBy(i => i.LastName)
.ToListAsync();
return View(viewModel);
How do I paginate through the returned records of a viewmodel.
I've tried passing the viewmodel into the PaginatedList like this.
return View(await PaginatedList<InstructorIndexData>.CreateAsync(viewModel.AsNoTracking(), page ?? 1, pageSize));
which has the error
Error CS1061 'InstructorIndexData' does not contain a definition for 'AsNoTracking' and no extension method 'AsNoTracking' accepting a first argument of type 'InstructorIndexData' could be found (are you missing a using directive or an assembly reference?)
Edit The ViewModel is
namespace ContosoUniversity.Models.SchoolViewModels
{
public class InstructorIndexData
{
public IEnumerable<Instructor> Instructors { get; set; }
public IEnumerable<Course> Courses { get; set; }
public IEnumerable<Enrollment> Enrollments { get; set; }
}
}
changing the IEnumerable to IQueryable causes the following
var viewModel = new InstructorIndexData();
viewModel.Instructors = await _context.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.CourseAssignments)
.ThenInclude(i => i.Course)
.ThenInclude(i => i.Department)
.OrderBy(i => i.LastName)
.ToListAsync();
to produce the error
Cannot implicitly convert type 'System.Collections.Generic.List<ContosoUniversity.Models.Instructor>' to 'System.Linq.IQueryable<ContosoUniversity.Models.Instructor>'. An explicit conversion exists (are you missing a cast?)
回答1:
AsNoTracking()
is an Extension Method defnied in the DbExtension assembly. The property "Instructors" must be of a type that implements "IQueryable" to enable this extension method.
Also, in your provided code sample
return View(await PaginatedList<InstructorIndexData>.CreateAsync(viewModel.AsNoTracking(), page ?? 1, pageSize));
You are using the extension method over the viewModel itself and not the property "Instructors"
来源:https://stackoverflow.com/questions/45413078/how-do-i-paginate-through-a-viewmodel-in-mvc-core