我想知道下面的代码如何工作,性能如何。我基本上对第4行感兴趣。 linq和属性信息将如何协同工作?
换句话说,(int)prop.GetValue(a)
和a.SomeId
的工作方式相同,还是反射需要在检查值之前将所有内容都保存到内存中?
var prop = type.GetProperty("SomeId");
if (prop != null)
{
DbSet<T> dbSet = _dbContext.Set<T>();
return dbSet.Where(a => (int)prop.GetValue(a) == 1);
}
换言之
(int)prop.GetValue(a)
和a.SomeId
的工作方式相同
编号
取决于后备存储,上下文可能无法将该表达式((int)prop.GetValue(a)
)转换为基础查询语法,在大多数情况下将是SQL。
您可以考虑使用属性信息手动构建有效的表达式。
例如
//Assuming
Type type = typeof(T);
PropertyInfo prop = type.GetProperty("SomeId");
if (prop != null) {
//need to build a => a.SomeId == 1
// a =>
ParameterExpression parameter = Expression.Parameter(type, "a");
// a => a.SomeId
MemberExpression property = Expression.Property(parameter, prop);
// a => a.SomeId == 1
BinaryExpression body = Expression.Equal(property, Expression.Constant(1));
Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(body, parameter);
DbSet<T> dbSet = _dbContext.Set<T>();
return dbSet.Where(expression);
}