In my ASP.NET Core web application I fetch IQueryable<Task>
using Entity Framework Core from my database to a result
variable in my controller. See data definitions at the end.
If I inspect result
the ListTag
is populated as expected and each item in it has it's User
populated. So, everything is OK.
Before passing the results to a view (.cshtml
), I want to transform the IQueryable to a PaginatedList
(so as to use pager in my index page). The resulting PaginatedList
still has child list ListTag
populated, but its User
is NULL
.
Why?
Note: in the repository I use both Include(x => x.ListTag)
and ThenInclude(u => u.User)
when fetching data from the database.
All the code and data definitions (short):
Get paginated list:
indexModel.ListTasks = await PaginatedList<DetailModel>.CreateAsync(result.AsNoTracking(), pageNumber, pageSize);
PaginatedList
class:
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage
{
get { return (PageIndex > 1); }
}
public bool HasNextPage
{
get { return (PageIndex < TotalPages); }
}
public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
}
Entity Framework Core data models:
class Task
{
public int IdTask
public string Subject
public List<Tag> ListTag
}
class Tag
{
public int IdTag
public string Tag
[ForeignKey("IdTask")]
public Task Task{ get; set; }
public int IdUser
[ForeignKey("IdUser")]
public User User
}
class User
{
public int IdUser
public string Name
}
Index and Detail model (for the cshtml views):
class IndexModel
{
public Helpers.PaginatedList<DetailModel> ListTasks
}
class DetailModel
{
public int IdTask
public string Subject
public List<Tag> ListTag
}
Read more here: https://stackoverflow.com/questions/66323379/custom-paginated-list-setting-child-objects-in-iqueryable-to-null
Content Attribution
This content was originally published by TheMixy at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.