0

When mapping an EF result to DTO, adding AsNoTracking to EF query has any effect on performance?

Ex.

_context.Students.Where(x => x.age > 15).AsEnumerable().Select(x => ToDTO(x)).ToList();

Vs.

_context.Students.Where(x => x.age > 15).AsNoTracking().AsEnumerable().Select(x => ToDTO(x)).ToList();
Shivanka
  • 723
  • 2
  • 8
  • 21
  • I doubt is it even works - how EF will translate ToDTO to SQL? However, `AsNoTracking` will not have any effect, because you return DTO not actual context's class, EF can't track DTO. – Slava Utesinov Jul 31 '19 at 05:17
  • @SlavaUtesinov: The problem here is AsEnumerable() method, which materializes entities, thus context will set up change tracking. That means unnecessary overhead. – dropoutcoder Aug 02 '19 at 20:47
  • Similar discussion [here](https://stackoverflow.com/a/57233397/861716). You could mark you question as duplicate of that one. – Gert Arnold Aug 03 '19 at 21:15

1 Answers1

1

Yes, it will have effect. So far the query is materialized via AsEnumerable() method and will set up change tracking for every single entity returned, thus there will be overhead.

In general, if you are querying data and using them just for read-only purposes it is reasonable to disable tracking.

Tracking vs. No-Tracking Queries

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dropoutcoder
  • 2,627
  • 2
  • 14
  • 32