public static Expression Parameterize(Type type, object value) { // () => new LinqParameterContainer(constant).Property // instead of returning a constant expression node, wrap that constant in a class the way compiler // does a closure, so that EF can parameterize the constant (resulting in better performance due to expression translation caching). LinqParameterContainer containedValue = LinqParameterContainer.Create(type, value); return(Expression.Property(Expression.Constant(containedValue), "TypedProperty")); }
// Extract the constant that would have been encapsulated into LinqParameterContainer if this // expression represents it else return null. internal static object ExtractParameterizedConstant(Expression expression) { if (expression.NodeType == ExpressionType.MemberAccess) { MemberExpression memberAccess = expression as MemberExpression; Contract.Assert(memberAccess != null); if (memberAccess.Expression.NodeType == ExpressionType.Constant) { ConstantExpression constant = memberAccess.Expression as ConstantExpression; Contract.Assert(constant != null); Contract.Assert(constant.Value != null); LinqParameterContainer value = constant.Value as LinqParameterContainer; Contract.Assert(value != null, "Constants are already embedded into LinqParameterContainer"); return(value.Property); } } return(null); }