gpt4 book ai didi

entity-framework - 从 IQueryable 生成缓存键以缓存 EF Code First 查询的结果

转载 作者:行者123 更新时间:2023-12-04 07:23:06 25 4
gpt4 key购买 nike

我正在尝试为我的 EF 存储库实现一个缓存方案,类似于博客 here .正如作者和评论者所报告的那样,限制是 key 生成方法无法生成随给定查询参数而变化的缓存 key 。这是缓存 key 生成方法:

private static string GetKey<T>(IQueryable<T> query)
{
string key = string.Concat(query.ToString(), "\n\r",
typeof(T).AssemblyQualifiedName);
return key;
}

因此,以下查询将产生相同的缓存键:
var isActive = true;
var query = context.Products
.OrderBy(one => one.ProductNumber)
.Where(one => one.IsActive == isActive).AsCacheable();


var isActive = false;
var query = context.Products
.OrderBy(one => one.ProductNumber)
.Where(one => one.IsActive == isActive).AsCacheable();

请注意,唯一的区别是 isActive = true在第一个查询和 isActive = false 中在第二。

任何关于有效生成缓存键的建议/见解,因 IQueryable 而异参数将不胜感激。

感谢 Sergey Barskiy 分享 EF CodeFirst 缓存方案。

更新

我自己采用了遍历 IQueryable 的表达式树的方法,目的是解析查询中使用的参数的值。与 maxlego's建议,我扩展了 System.Linq.Expressions.ExpressionVisitor类来访问我们感兴趣的表达式节点 - 在本例中,是 MemberExpression .更新 GetKey方法看起来像这样:
public static string GetKey<T>(IQueryable<T> query)
{
var keyBuilder = new StringBuilder(query.ToString());
var queryParamVisitor = new QueryParameterVisitor(keyBuilder);
queryParamVisitor.GetQueryParameters(query.Expression);
keyBuilder.Append("\n\r");
keyBuilder.Append(typeof (T).AssemblyQualifiedName);

return keyBuilder.ToString();
}

QueryParameterVisitor类,其灵感来自 Bryan Watts 的答案和 Marc Gravell到此 question ,看起来像这样:
/// <summary>
/// <see cref="ExpressionVisitor"/> subclass which encapsulates logic to
/// traverse an expression tree and resolve all the query parameter values
/// </summary>
internal class QueryParameterVisitor : ExpressionVisitor
{
public QueryParameterVisitor(StringBuilder sb)
{
QueryParamBuilder = sb;
Visited = new Dictionary<int, bool>();
}

protected StringBuilder QueryParamBuilder { get; set; }
protected Dictionary<int, bool> Visited { get; set; }

public StringBuilder GetQueryParameters(Expression expression)
{
Visit(expression);
return QueryParamBuilder;
}

private static object GetMemberValue(MemberExpression memberExpression, Dictionary<int, bool> visited)
{
object value;
if (!TryGetMemberValue(memberExpression, out value, visited))
{
UnaryExpression objectMember = Expression.Convert(memberExpression, typeof (object));
Expression<Func<object>> getterLambda = Expression.Lambda<Func<object>>(objectMember);
Func<object> getter = null;
try
{
getter = getterLambda.Compile();
}
catch (InvalidOperationException)
{
}
if (getter != null) value = getter();
}
return value;
}

private static bool TryGetMemberValue(Expression expression, out object value, Dictionary<int, bool> visited)
{
if (expression == null)
{
// used for static fields, etc
value = null;
return true;
}
// Mark this node as visited (processed)
int expressionHash = expression.GetHashCode();
if (!visited.ContainsKey(expressionHash))
{
visited.Add(expressionHash, true);
}
// Get Member Value, recurse if necessary
switch (expression.NodeType)
{
case ExpressionType.Constant:
value = ((ConstantExpression) expression).Value;
return true;
case ExpressionType.MemberAccess:
var me = (MemberExpression) expression;
object target;
if (TryGetMemberValue(me.Expression, out target, visited))
{
// instance target
switch (me.Member.MemberType)
{
case MemberTypes.Field:
value = ((FieldInfo) me.Member).GetValue(target);
return true;
case MemberTypes.Property:
value = ((PropertyInfo) me.Member).GetValue(target, null);
return true;
}
}
break;
}
// Could not retrieve value
value = null;
return false;
}

protected override Expression VisitMember(MemberExpression node)
{
// Only process nodes that haven't been processed before, this could happen because our traversal
// is depth-first and will "visit" the nodes in the subtree before this method (VisitMember) does
if (!Visited.ContainsKey(node.GetHashCode()))
{
object value = GetMemberValue(node, Visited);
if (value != null)
{
QueryParamBuilder.Append("\n\r");
QueryParamBuilder.Append(value.ToString());
}
}

return base.VisitMember(node);
}
}

我仍在对缓存 key 生成进行一些性能分析,并希望它不会太昂贵(一旦我得到结果,我将用结果更新问题)。如果有人对如何优化此过程有建议或建议使用更有效的方法来生成随查询参数而变化的缓存键,我将把问题保持开放。虽然这种方法产生了所需的输出,但它绝不是最佳的。

最佳答案

关于entity-framework - 从 IQueryable 生成缓存键以缓存 EF Code First 查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8275881/

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