StudentHelper.cs
我有一个名为StudentHelper的帮助程序类,在其中它调用存储库类以获取所有学生详细信息。下面是获取学生详细信息的代码。
model = await _repo.FilterAsync<StudentRbCasesLink>(s =>
containsTest(options, list, s, countyId) && s.student.Deleted = false && s.student.studentId !=0,
s=> s.student,
s => s.studentRbCase,
s=> s.studentRbCase.CurrentCounty,
s=> s.studentRbCase.Abawdtype);
dto => _mapper.Map<IEnumerable<Objects.DTO.StudentRbCases>>(model);
containsTest是一种基于输入参数进行所有过滤的方法。此方法根据所应用的过滤器返回布尔值,并将该布尔值发送到存储库类。
private bool containsTest(string options, Dictionary<string,string> list,
StudentRbCasesLink s,int countyId){
if(options.contains("FirstName")){
firstName = list["FirstName"].ToLower().ToString();
predicate = firstName != "&county" ?
(s.student.FirstName.ToLower().contains(firstName)).Tostring() :
"false";
}
if(options.contains("LastName")){
lastName = ............................
}
........................
return convert.ToBoolean(predicate);
}
下面是repo类中的实际FilterAsync方法。 RepositoryClass.cs
public async Task<IQueryable<T>> FilterAsync<T>(Expression<Func<T,bool>> predicate, params Expression<Func<T,object>>[] includes) where T : class
{
return await Task.Run(()=> {
var query = _context.Set<T>().where(predicate).AsQueryable();
return includes.Aggregate(query, (current, includeProperty)
=> current.Include(includeProperty).asQueryable());
});
}
让我清楚地描述问题。我在这里按参数搜索功能。 Studenthelper类一旦获取所有参数,就会在Studenthelper中击中filterasync,而后者又会在Repository类中击中实际方法filterasync。因此,当我看到转换后的SQL的SQL配置文件时,它显示的是带有filterasync包含中包含的所有联接的SQL查询,但达到条件时,它仅在SQL中应用s.student!= 0条件使查询非常慢(未在使条件变慢的位置应用所有条件/过滤器)。生成SQL时,它不应用containsTest方法中提到的任何条件,但是一旦光标到达下一个Auto-mapper(用于将模型转换为dtos)行,光标便会到达containsTest方法并进行所有过滤。在幕后,SQL会获取所有记录,并将它们放入内存中,并在单击“自动映射器”时应用过滤器。
我看过其他人建议将Expression>谓词代替Func谓词的帖子。但是,我的代码已经有了Expression。谁能帮助我如何编写containsTest方法,以便在将条件转换为SQL查询时应用条件。请注意,使用的EF是EntityFrameworkcore(1.1.2)。感谢您的帮助。
答案 0 :(得分:0)
这是我解决此问题的方法: 首先,按照上述建议,我删除了containsTest方法,并使用相同的方法编写了所有内容。
var predicate = PredicateBuilder.True<StudentRbcasesLink>();
if (options.Contains("FirstName"))
{
firstName = list["FirstName"].ToLower().ToString();
Expression<Func<StudentRBbasesLink, bool>> expressionFirstName = x =>
x.Student.FirstName.StartsWith(firstName);
if (firstName != "&county") {
predicate = predicate.And(x => x.Student.FirstName.StartsWith(firstName));
}
}
if (options.Contains("LastName"))
{
lastName = list["LastName"].ToLower().ToString();
Expression<Func<StudenRbcasesLink, bool>> expressionLastName = x =>
x.Student.LastName.StartsWith(lastName);
predicate = !string.IsNullOrEmpty(firstName) ? predicate.And(x =>
x.Participant.LastName.StartsWith(lastName)) : expressionLastName;
...........
}
...............................
最大的问题是,如何动态执行表达式的逻辑与,逻辑或运算。下面是使之成为可能的代码。( PredicateBuilder 是用于动态执行逻辑运算的类在表达谓词上)。
public static class PredicateBuilder
{
/// <summary>
/// Creates a predicate that evaluates to true.
/// </summary>
public static Expression<Func<T, bool>> True<T>() { return param => true; }
/// <summary>
/// Creates a predicate that evaluates to false.
/// </summary>
public static Expression<Func<T, bool>> False<T>() { return param => false; }
/// <summary>
/// Creates a predicate expression from the specified lambda expression.
/// </summary>
public static Expression<Func<T, bool>> Create<T>(Expression<Func<T, bool>> predicate) { return predicate; }
/// <summary>
/// Combines the first predicate with the second using the logical "and".
/// </summary>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.AndAlso);
}
/// <summary>
/// Combines the first predicate with the second using the logical "or".
/// </summary>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.OrElse);
}
/// <summary>
/// Negates the predicate.
/// </summary>
public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expression)
{
var negated = Expression.Not(expression.Body);
return Expression.Lambda<Func<T, bool>>(negated, expression.Parameters);
}
/// <summary>
/// Combines the first expression with the second using the specified merge function.
/// </summary>
static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
// zip parameters (map from parameters of second to parameters of first)
var map = first.Parameters
.Select((f, i) => new { f, s = second.Parameters[i] })
.ToDictionary(p => p.s, p => p.f);
// replace parameters in the second lambda expression with the parameters in the first
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
// create a merged lambda expression with parameters from the first expression
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
}
class ParameterRebinder : ExpressionVisitor
{
readonly Dictionary<ParameterExpression, ParameterExpression> map;
ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}
以前的问题是,我在布尔值而不是表达式上执行逻辑运算。而且只能通过上述prediateBuilder类实现对表达式的逻辑运算。
下面是FilterAsync的代码
model = await _repo.FilterAsync<StudentRbCasesLink>(
predicate
s => s.student.studentId !=0,
s => s.student,
s => s.studentRbCase,
s => s.studentRbCase.CurrentCounty,
s => s.studentRbCase.Abawdtype);
dto => _mapper.Map<IEnumerable<Objects.DTO.StudentRbCases>>(model);
更改代码后,我进入了SQL Server Profiler,并测试了查询的形成方式。它具有所有必要的连接以及where子句,前提是where子句会根据搜索动态变化。
此后,如果给出组合(每次2或3场),搜索将在3秒钟内暂停。注意:以前,搜索过去需要1到2分钟。为必要的列创建一些索引和统计信息可以将其减少到少于1秒。