© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
2 replies
kopuo.

❔ How to Select Data with Included nested objects?

When extracting data from the database for the main object, I want to extract only the necessary data.

My code now:
_dbContext.Units    // I need only two fields from here, not whole object
    .Include(p => p.Shops)              
        .ThenInclude(p => p.Department)
            .ThenInclude(p => p.Products.Where(i => i.Availability == available))
    .AsNoTracking()
    .SingleOrDefaultAsync(p => p.UnitId == unitId);
_dbContext.Units    // I need only two fields from here, not whole object
    .Include(p => p.Shops)              
        .ThenInclude(p => p.Department)
            .ThenInclude(p => p.Products.Where(i => i.Availability == available))
    .AsNoTracking()
    .SingleOrDefaultAsync(p => p.UnitId == unitId);


I want something like this:
_dbContext.Units
    .Select(x => new
    {
        UnitId = x.UnitId,
        Name = x.Name
    })
    .Include(p => p.Shops)
        .ThenInclude(p => p.Department)
            .ThenInclude(p => p.Products.Where(i => i.Availability == available))
    .AsNoTracking()
    .SingleOrDefaultAsync(p => p.UnitId == unitId);
_dbContext.Units
    .Select(x => new
    {
        UnitId = x.UnitId,
        Name = x.Name
    })
    .Include(p => p.Shops)
        .ThenInclude(p => p.Department)
            .ThenInclude(p => p.Products.Where(i => i.Availability == available))
    .AsNoTracking()
    .SingleOrDefaultAsync(p => p.UnitId == unitId);
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

GetFromJsonAsync and nested objects using FluentResults
C#CC# / help
15mo ago
Idiomatic C# Data Objects with Immutable Collections?
C#CC# / help
15mo ago
✅ Trying to extract nested JSON data
C#CC# / help
2y ago
✅ how to destroy game objects with three clicks
C#CC# / help
3y ago