本文介绍了如何结合使用Find()和AsNoTracking()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对EF上下文进行查询以防止返回时如何将 Find() 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);

我该怎么做?我正在使用EF版本6。

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

注意:我不想使用 SingleOrDefault()哪里。我只是不能,因为参数 Id 是通用的,并且是 struct ,因此我无法应用运算符 == 表示泛型。

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.

推荐答案

所以不要使用 AsNoTracking()您可以做的是 Find(),然后将其与上下文分离。我相信,除了获得跟踪实体的额外开销外,这给您与 AsNoTracking()相同的结果。有关更多信息,请参见

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;

编辑:这有一些潜在的问题,如果上下文尚未加载某些关系,则这些导航属性将不起作用,您会感到困惑和沮丧,为什么一切都返回null!有关更多信息,请参见。现在,在这些存储库中,我将覆盖需要存储库中的 FindNoTracking()方法。

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.

这篇关于如何结合使用Find()和AsNoTracking()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 09:14