仅返回字段时,使用AsNoTracking()是否有所作为? [英] Does using AsNoTracking() make a difference when only returning fields?

查看:57
本文介绍了仅返回字段时,使用AsNoTracking()是否有所作为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在EF中执行查询时已经读了很多有关使用AsNoTracking()的知识,特别是如果它返回实体的话,以免如果您不进行更新就不会保留对事物的引用.

So I've read a lot about using AsNoTracking() when performing a query in EF, specifically if it returns entities, as to not keep around references to things if you will not be updating.

但是我还读到,由于EF不必将查询的每个项目都映射到映射中的实体,因此AsNoTracking本身也可以加快查询的速度.

But I've also read that AsNoTracking may also speed up the queries themselves as EF does not have to map each item queried to an entity in the map.

问题是,如果我的Linq查询只是从列/行中返回值,而不是实体类型,那么使用AsNoTracking()是否可以加快查询速度?如果不是很明显,我不应该使用它,因为它只会使代码混乱?

The question is, if my Linq query simply returns values from the columns/rows but not an entity type, does using AsNoTracking() make a difference to speed up the query? And if not obviously I shouldn't use it because it just clutters the code?

示例1(我希望使用AsNoTracking():

example 1 (I would expect to use AsNoTracking():

var result = (from p in context.Pogs
              select p).AsNoTracking();

示例2(我的问题...我认为在这里使用没有意义,但我不知道答案):

example 2 (My question... I'm thinking it doesn't make sense to use here, but I don't know the answer):

var result = (from p in context.Pogs
              select p.Name);  // assuming p.Name is a string or something

var result = (from p in context.Pogs.AsNoTracking()
              select p.Name);

推荐答案

不,这不是因为不会加载实体,这通过检查 context.Pogs.Local 可以证明,包含其属性是通过LINQ检索的实体.

No, it does not since the entities won't be loaded, as evidenced by examining context.Pogs.Local which won't contain the entities whose properties were retrieved through LINQ.

您可以检查通过 DbContext.ChangeTracker .因此,如果通过 context.ChangeTracker.Entries< Pogs>()为Pogs DbSet 检索跟踪器的条目,您将看到第一个示例中存在条目跟踪相应的实体,而在第二个示例中,没有实体.

You can check the entities being tracked through DbContext.ChangeTracker. So if you retrieve the entries of the tracker for your Pogs DbSet through context.ChangeTracker.Entries<Pogs>() you'll see that for your first example there are entries tracking the corresponding entities, while for the second example there are none.

这篇关于仅返回字段时,使用AsNoTracking()是否有所作为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆