Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine Find() and AsNoTracking()?

How to combine Find() with AsNoTracking() when making queries to an EF context to prevent the returned object from being tracked. This is what I can't do

 _context.Set<Entity>().AsNoTracking().Find(id); 

How can I do that? I am using EF version 6.

Note: I do not want to use SingleOrDefault(), or Where. I just can't because the parameter Id is generic and it's a struct and I can not apply operator == for generics in that case.

like image 469
Nean Der Thal Avatar asked Jan 23 '16 18:01

Nean Der Thal


People also ask

What difference does AsNoTracking () make?

AsNoTracking() . This optimisation allows you to tell Entity Framework not to track the results of a query. This means that Entity Framework performs no additional processing or storage of the entities which are returned by the query.

When should I use AsNoTracking?

The AsNoTracking method can save both execution times and memory usage. Applying this option really becomes important when we retrieve a large amount of data from the database.

How can we find entities in the DbSet find () method?

The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.

What is the use of AsNoTracking in Entity Framework?

AsNoTracking(IQueryable)Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object.


1 Answers

So instead of using AsNoTracking() what you can do is Find() and then detach it from the context. I believe that this gives you the same result as AsNoTracking() besides the additional overhead of getting the entity tracked. See EntityState for more information.

var entity = Context.Set<T>().Find(id); Context.Entry(entity).State = EntityState.Detached; return entity; 

Edit: This has some potential issues, if the context hasn't loaded some relationships, then those navigation properties will not work and you will be confused and frustrated why everything is returning null! See https://stackoverflow.com/a/10343174/2558743 for more info. For now on those repositories I'm overriding the FindNoTracking() methods in my repositories that I need that in.

like image 106
Derked Avatar answered Oct 09 '22 01:10

Derked