2

In my application I have a basic architecture as shown:

RepositoryMethods (DO) --> BusinessEngines (DTO) --> Controller (ViewModel)

I like to keep all the Entity Framework / DbContext access code in one place. My Repository methods all have the DbContext injected and are all API style as opposed to a generic repository:

Task<Post> GetAllPostsInCategory(int categoryId);

So as the entities (Domain Objects) are converted to Data Transfer Objects and then to View Models, can entity framework still track them or should I always be using .AsNoTracking() in every Repository method? In dot net core I think this can be set globally am I correct?

Stephen Wilson
  • 1,484
  • 1
  • 15
  • 30
  • Maybe it is enough to call `Context.Configuration.AutoDetectChangesEnabled = false;` in your DataContext constructor or something like this. – ˈvɔlə Aug 21 '17 at 16:06
  • When you do not want to have your changes tracked by the software itself and your application is very much in control of its own CRUD process, you should turn tracking off. https://stackoverflow.com/questions/12211680/what-difference-does-asnotracking-make – Amit Kumar Singh Aug 21 '17 at 16:07
  • Since the Database entities are transformed to View Models (and I assume after editing transformed back) EF can't - and shouldn't Track the Changes. If you do have a global context instance (which I strongly discourage), you'll have to remove the old entry and add the new one, which is prone to errors of all kinds. Otherwise EF can't track the Changes anyway. If this is the case in all your database access cases, you can safely disable ChangeTracking globally, either by setting AutoDetectChangedEnabled to false or by using .AsNoTracking() on each read operation. – DevilSuichiro Aug 21 '17 at 16:16
  • The DbContext is added in the Startup.cs class `services.AddDbContext()` so is managed by the container. I think I need to use no tracking and manually re-attach the entities after editing. – Stephen Wilson Aug 22 '17 at 07:40

1 Answers1

1

It makes sense if you are returning entities from the API as simply, your context will never have a chance to track anything.

However,r if you are updating or deleting any data, it is better to keep it on

Haitham Shaddad
  • 4,336
  • 2
  • 14
  • 19