Home > Net >  Nested entities and performance in .NET Core Api with Entity Framework Core
Nested entities and performance in .NET Core Api with Entity Framework Core

Time:11-03

I want to build my API over .NET Core Entity Framework Core.

I am very familiar with Sequelize ORM (javascript) where you have total control about customizing the query.

i.e. imagine a data model where you have Schools and each school has many Students.

Sometimes I want to query only the schools (faster), and sometimes I want to query the schools with the students (slower).

So using axios client over Sequelize server I do:

// including students (slower)
this.$axios.$get('/api/school',{ params : { where: { Country: 'US' }, include: [{ model: 'Student' }] } })

// not including students (faster)
this.$axios.$get('/api/school',{ params : { where: { Country: 'US' } })

However I cannot find a way to do something similar with axios and .NET Core

Does anyone know or could point a link to some documentation to manage clientside optional includes in Entity Framework Core .NET Core API?

CodePudding user response:

If you query an entity with EF, you can define which child objects to include in the query, like so:

context.DbSet<School>().Include(s => s.Students).ToList();

To make this work in your endpoint, it becomes something like this:

public IActionResult Get(string country, string[] includes)
{
    var query = _context.DbSet<School>();

    foreach (var include in includes)
    {
        query = query.Include(include);
    }

    return query.ToList();
}

Although it is not really recommended to allow the client to define what to include. What if there is financial data connected to the school, and the client is including that as well?! You certainly don't want that!

I'd suggest making a seperate endpoint, and query the includes in the API, instead of doing that client side, like so:

[HttpGet("school")]
public IActionResult Get(string country)
{
    return Ok(_context.DbSet<School>().ToList());
}

[HttpGet("schoolWithStudents")]
public IActionResult Get(string country)
{
    return Ok(_context.DbSet<School>().Include(s => s.Students).ToList());
}

Ignoring the filtering on country for brevity.

  • Related