[英]Linq query timeout for table which contains more than 150k records
我有很多表需要查询数据以查看某个参数(isCorrect)是否为是。 该字段存在于所有表中。 我已经使用泛型类型构建了一个动态查询。 但是我在获取数据时得到执行期超时。
这是一个小代码片段:
public bool isRecordCorrect<T>(Guid userID)
{
using (EmployeeEntities dbContext = new EmployeeEntities())
{
DbSet dbSet = dbContext.Set(typeof(T)) // T here is the table types for e.g employee, department
IQueryable<T> query = (IQueryable<T>)dbSet.AsQueryable();
var list = query
.Where(DynamicQuery<T>.FilterStatement(userID))
.FirstOrDefault();
return list == null ? false : true;
}
}
public class DynamicQuery<T>
{
public static Func<T,bool> FilterStatement(Guid userID)
{
var xParameter = Expression.Parameter(typeof(T), "o");
var prop = Expression.Property(xParameter, "IsCorrect");
var incorrect = Expression.Constant("N");
var equalIncorrect = Expression.Equal(prop,equalIncorrect);
var userIdProp = Expression.Property(xParameter, "userID");
var userId = Expression.Constant(userID);
var equaluserID = Expression.Equal(userIdProp, userId);
var andExpresion = Expression.And(equalIncorrect, equaluserId);
var lambda = Expression.Lambda<Func<T, bool>> (andExpresion, xParameter);
return lambda.Compile();
}
}
对于具有大量记录但对其他记录正常的表来说超时了。
要在服务器端翻译查询,EF Core 需要纯表达式。 Compile
并返回Func<,>
,而不是Expression<Func<,>>
强制使用Enumerable.Where
扩展,它只是在过滤之前加载 memory 中的整个表。 与UserId
上的索引(如果不存在)一起使用,简单修复应该就足够了。
public static Expression<Func<T,bool> FilterStatement(Guid userID)
{
var xParameter = Expression.Parameter(typeof(T), "o");
var prop = Expression.Property(xParameter, "IsCorrect");
var incorrect = Expression.Constant("N");
var equalIncorrect = Expression.Equal(prop,equalIncorrect);
var userIdProp = Expression.Property(xParameter, "userID");
var userId = Expression.Constant(userID);
var equaluserID = Expression.Equal(userIdProp, userId);
var andExpresion = Expression.And(equalIncorrect, equaluserId);
var lambda = Expression.Lambda<Func<T, bool>> (andExpresion, xParameter);
return lambda;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.