运行Linq语句的超时异常

Cha*_*ris 3 c# sql linq entity-framework sql-server-2008

这才刚刚开始发生.这个声明已经工作了几个月,现在我只是继续得到下面的超时错误.当我直接在SSMS上执行相同的语句时,它会在一秒钟内返回.该表有44k记录,并且是5列状态的索引,其中一列是其中之一.

select distinct(state) from [ZipCodeDatabase]
Run Code Online (Sandbox Code Playgroud)

我正在运行以下linq语句

states = ZipCodeRepository.Get(orderBy: z => z.OrderBy(o => o.State)).Select(z => z.State).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)

当我运行这个linq语句时,我不断得到一个超时错误并且不知道y因为它之前正常工作.

我包含了Get()一个通用的repo函数函数,但也许我在那里遗漏了一些东西,这导致了延迟.

获取功能:

public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "") //params Expression<Func<TEntity, object>>[] includes
{
    IQueryable<TEntity> query = dbSet;
    if (filter != null)
    {
        query = query.Where(filter);
    }
    foreach (var includeProperty in includeProperties.Split
        (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
    {
        query = query.Include(includeProperty);
    }

    if (orderBy != null)
    {
        return orderBy(query).ToList();
    }
    else
    {
        return query.ToList();
    }
}
Run Code Online (Sandbox Code Playgroud)

超时错误:

System.Data.SqlClient.SqlException(0x80131904):超时已过期.操作完成之前经过的超时时间或服务器没有响应.---> System.ComponentModel.Win32Exception(0x80004005):在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning上的System.Data.SqlClient.SqlConnection.OnError(SqlException异常,Boolean breakConnection,Action 1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)中等待操作超时( TdsParserStateObject stateObj,布尔callerHasConnectionLock,布尔asyncClose)在System.Data.SqlClient.TdsParser.TryRun(runBehavior runBehavior,SqlCommand的cmdHandler,SqlDataReader的数据流,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,布尔逻辑dataReady)在System.Data.SqlClient.SqlDataReader.TryCloseInternal(布尔System.Data.Scom上的System.Data.SqlClient.SqlDataReader.Close()处的System.Data.SqlClient.SqlDataReader.Close()处于System.Data.Com上的System.Data.Comm.Reprator.Dispose(.) .Shaper 1.SimpleEnumerator.Dispose 1.Finally() at System.Data.Common.Internal.Materialization.Shaper()在System.Collections.Generic.List 1..ctor(IEnumerable1集合中)在System.Linq.Enumerable.ToList [TSource](IEnumerable 1 source) at ClientsToProfitsKendoUI.DAL.GenericRepository1.Get(Expression 1 filter, Func2 ord)erBy,String includeProperties)

jes*_*ing 5

您的get方法始终调用ToList,这会在该点实现查询.这意味着它会在进行任何过滤之前从数据库中获取所有44k记录.

在实际选择任何数据之前,您还要按状态进行排序,这对于排序任意数据是一种无用的练习.

从您的Get方法,删除ToList调用.并通过首先选择State,然后调用Distinct然后订购来优化您的查询.这允许数据库以最佳方式完成任务.

如果您需要完全具体化的列表,请ToList在最后调用.但在此之前,请继续使用IQueryable查询返回的内容.这样,您可以让Entity Framework尽可能多地卸载到数据库中.