C#C
C#11mo ago
Cydo

✅ How to get better at writing EF Queries?

Maybe I just don't really understand things, but I create database tables try to separate things and do all the relationships, and then I start having to do these massive includes like this, and I feel like its just going to cause performance issues
    public async Task<IEnumerable<Category>> GetAllCategoriesTaskListsAsync(string userId, string categoryName)
    {
        return await _context.Categories
            .Include(c => c.TaskLists)
            .ThenInclude(tl => tl.User)
            .Include(c => c.TaskLists)
            .ThenInclude(tl => tl.TaskListItems)
            .Include(c => c.TaskLists)
            .ThenInclude(tl => tl.UserTaskLists)
            .Where(c => c.UserId == userId && c.Name.ToLower() == categoryName.ToLower())
            .ToListAsync();
    }

Is there a better way to make these queries? I tried doing courses on EF Core itself to learn better but its always just these simple queries and then my personal projects require more complex queries where I start to hit a world of issues.

I've managed to refactor the above into this

    public async Task<List<TaskList>> GetAllTaskListsInCategoryAsync(int categoryId)
    {
        return await _context.TaskLists.Where(t => t.CategoryId == categoryId)
            .Include(t => t.TaskListItems)
            .Include(t => t.TaskListAssignments)
            .ThenInclude(tla => tla.User)
            .ToListAsync();
    }

But I still feel like repeatedly doing includes causes issues.
Was this page helpful?