gpt4 book ai didi

c# - 如何提高 EF 中执行查询的速度

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:14 25 4
gpt4 key购买 nike

方法 FindByQueryAsNoTracking() 实现如下:

public IEnumerable<T> FindByAsNoTracking(Expression<Func<T, bool» predicate)
{
IQueryable<T> query = Dbset.Where(predicate).AsNoTracking().AsQueryable();
return query;
}

如果我们使用下面实现的FindByAsQuery:

public IQueryable<T> FindByQuery(Expression<Func<T, bool» predicate)
{
IQueryable<T> query = Dbset.Where(predicate).AsQueryable();
return query;
}

速度会变好??

最佳答案

AsNoTracking(IQueryable)

返回一个新查询,其中返回的实体将不缓存在 DbContext 或 ObjectContext 中。此方法通过调用基础查询对象的 AsNoTracking 方法来工作。如果底层查询对象没有 AsNoTracking 方法,则调用此方法将无效。

No Tracking Queries

5.1 Disabling change tracking to reduce state management overhead If you are in a read-only scenario and want to avoid the overhead of loading the objects into the ObjectStateManager, you can issue "No Tracking" queries. Change tracking can be disabled at the query level.

Note though that by disabling change tracking you are effectively turning off the object cache. When you query for an entity, we can't skip materialization by pulling the previously-materialized query results from the ObjectStateManager. If you are repeatedly querying for the same entities on the same context, you might actually see a performance benefit from enabling change tracking.

When querying using ObjectContext, ObjectQuery and ObjectSet instances will remember a MergeOption once it is set, and queries that are composed on them will inherit the effective MergeOption of the parent query. When using DbContext, tracking can be disabled by calling the AsNoTracking() modifier on the DbSet.

简而言之,是的,通过使用 AsNoTracking,您可以获得更好的性能,尤其是当您要加载大量数据行时,但不要忘记它不会影响 SQL 生成的查询,它只会提高 .NET 的性能。

AsNoTracking vs Tracking

enter image description here

附言:图表取自 StaticVoid blog .

关于c# - 如何提高 EF 中执行查询的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56310780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com