Conditional Include in LINQ c# .Net (Dot Net)

Code Snippets 4 U

It may not be the best way. If you know better and not much complicated way of achieving the same then please comment.

The below LINQ query is for a table schema in which a Project can have section and both project and section can have test cases (But Unique). So, I need to fetch the project detail including section and its test cases and project test cases (test cases which are not part of any section but are part of a project).

var projectQueryable = await _projectRepository.GetAsync(proj => proj.Id == projectId); // get the queryable variable for project
var project = projectQueryable
 .Include(proj => proj.Section)
 .ThenInclude(section => section.TestCase)
 .Include(proj => proj.TestCase)
 .FirstOrDefault(); // fetch all the required data in memory

project.TestCase = project.TestCase
 .Where(test => test.SectionId == null)
 .ToList(); // filter the data

Leave a Reply

Your email address will not be published. Required fields are marked *

thirty six + = thirty eight