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.
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.