Search code examples
linq.net-coreentity-framework-core

If LINQ query retruns IEnumerable<int> does it matter if I add AsNoTracking()?


If LINQ query retruns IEnumerable does it matter if I add AsNoTracking()?

For instance:

return _context.People
     .Include(person => person.Cars)
     .AsNoTracking()
     .SelectMany(person => person.Cars)
     .Select(car => car.Id)
     .ToImmutableHashSet();

Does adding .AsNoTracking() actually changes anything, I don't think EF would track just ints.


Solution

  • It's not "just ints". EF Core tracks only entity instances, returned either directly or as part of a non entity class projection. Everything else is not tracked, so yes, AsNoTracking is not needed (it is simply ignored for such type of queries).

    The same btw applies to Include - they have effect only for queries returning entity instances to load (populate) their navigation properties. They are also ignored for non entity returning queries.

    So you sample query should be simply

    return _context.People
        .SelectMany(person => person.Cars)
        .Select(car => car.Id)
        .ToImmutableHashSet();