Dynamically building queries - c#

Hi and thanks for taking the time to answer my question.
After a year and a half of working with Java, I've decided to switch back to .NET. I must say that I feel at home in VS2012.
While working with Java I came across an implementation of hibernate that enabled for creating dynamic queries easily.
Imagine I had a form with 5 fields of which only one, any one, must be populated in order for me to filter the results by.
is there a way I can do the following in C#:
if(txtMunicipality.text.length > 0){
(x => x.municipality == txtMunicipality.text)
}
if(chkboxIsFinished){
(x => x.isfinished == true)
}
etc..
So I ccheck for every field and if the value has been populated then add that criteria to the query.. and after i'm done with the checks i execute the query. Is there a way to do this in C#?

The simplest way to do this is to compose two queries, i.e.
IQueryable<Foo> query = ... // or possibly IEnumerable<Foo>
if(!string.IsNullOrEmpty(txtMunicipality.text)) {
query = query.Where(x => x.municipality == txtMunicipality.text);
}
if(chkboxIsFinished) {
query = query.Where(x.isfinished);
}
You can also directly compose expression-trees and delegates; if you need that, please indicate which you have: an expression-tree vs a delegate.
Edit: here's how you would do that composing expressions rather than queries:
static class Program
{
static void Main()
{
Expression<Func<int, bool>> exp1 = x => x > 4;
Expression<Func<int, bool>> exp2 = x => x < 10;
Expression<Func<int, bool>> exp3 = x => x == 36;
var combined = (exp1.AndAlso(exp2)).OrElse(exp3);
// ^^^ equiv to x => (x > 4 && x < 10) || x == 36
}
static Expression<Func<T, bool>> OrElse<T>(this Expression<Func<T, bool>> x, Expression<Func<T, bool>> y)
{ // trivial cases
if (x == null) return y;
if (y == null) return x;
// rewrite using the parameter from x throughout
return Expression.Lambda<Func<T, bool>>(
Expression.OrElse(
x.Body,
SwapVisitor.Replace(y.Body, y.Parameters[0], x.Parameters[0])
), x.Parameters);
}
static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> x, Expression<Func<T, bool>> y)
{ // trivial cases
if (x == null) return y;
if (y == null) return x;
// rewrite using the parameter from x throughout
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(
x.Body,
SwapVisitor.Replace(y.Body, y.Parameters[0], x.Parameters[0])
), x.Parameters);
}
class SwapVisitor : ExpressionVisitor
{
public static Expression Replace(Expression body, Expression from, Expression to)
{
return new SwapVisitor(from, to).Visit(body);
}
private readonly Expression from, to;
private SwapVisitor(Expression from, Expression to)
{
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node)
{
return node == from ? to : base.Visit(node);
}
}
}

Yes, it is possible. The simplest way is with delegates, especially the anonymous ones.
For example:
Func<YourEntity, bool> filter = (_ => true); // Default value.
if (txtMunicipality.text.length > 0)
{
filter = (x => x.municipality == txtMunicipality.text);
}
else if (chkboxIsFinished)
{
filter = (x => x.isfinished == true);
}
Then you can use the filter delegate in a query, for example in a Where statement (which I suppose was your intent - if not, the example is still relevant, just not directly applicable)
/ LINQ syntax.
var entities = from e in context
where filter(e)
select e;
// Method syntax.
var entities = context.Where(x => filter(x));
// Or simply:
var entities = context.Where(filter);

In this article you can find some useful extension methods that allows you to combine predicates (it should work for NHibernate as well):
LINQ to Entities: Combining Predicates
You can then build a lambda expression like this:
Expression<Func<MyObject, bool>> predicate = x => true;
if(txtMunicipality.text.length > 0){
predicate = predicate.And(x => x.municipality == txtMunicipality.text);
}
if(chkboxIsFinished){
predicate = predicate.And(x => x.isfinished == true);
}

Related

How to generalize a part of a LINQ to SQL query

I have the following snippet that is repeated through my code for different fields:
if (filters.NameIsLike)
query = query.Where (x => EF.Functions.Like (x.Name, $"%{filters.Name}%"));
else
query = query.Where (x => x.Name.ToLower () == filters.Name.ToLower ());
How can I create an extension method that generalizes what the snippet does?
Something like:
public static IQueryable<T> EqualsOrLike (this IQueryable<T> query, ??? field, bool isLike, string filter)
{
if (isLike)
return query.Where (x => EF.Functions.Like (field.ToLower (), $"%{filter.ToLower ()}%"));
else
return query.Where (x => field.ToLower () == filter.ToLower ());
}
Thanks in advance!
UPDATE:
This is how the initial snippet is used (as an example):
In this case the class is Company, but it could be something different... Therefore I don't know the class nor the field.
And the comment explain how I would use the EqualsOrLike function:
protected override IQueryable<Company> _QueryAsync (IQueryable<Company> query, QueryFilterBase filter)
{
CompanyQueryFilter filters = (CompanyQueryFilter)filter;
if (!string.IsNullOrEmpty (filters.Name))
{
if (filters.NameIsLike)
query = query.Where (x => EF.Functions.Like (x.Name.ToLower (), $"%{filters.Name.ToLower ()}%"));
else
query = query.Where (x => x.Name.ToLower () == filters.Name.ToLower ());
//query = EqualsOrLike (query, x => x.Name, filters.NameIsLike, filters.Name);
}
if (!string.IsNullOrEmpty (filters.AtecoCode))
query = query.Where (x => EF.Functions.Like (x.AtecoCode, $"%{filters.AtecoCode}%"));
if (!string.IsNullOrEmpty (filters.VatNumber))
{
if (filters.VatNumberIsLike)
query = query.Where (x => EF.Functions.Like (x.VatNumber, $"%{filters.VatNumber}%"));
else
query = query.Where (x => x.VatNumber.ToLower () == filters.VatNumber.ToLower ());
//query = EqualsOrLike (query, x => x.VatNumber, filters.VatNumberIsLike, filters.VatNumber);
}
return query;
}
Since you don't know the property to compare, you need to build your expression by hand.
Option 1, you can construct the entire expression explicitly. As a first step, I find it useful to see how C# compiles an expression by using a decompiler;
Expression<Func<C,bool>> expr = x => x.Name.ToLower () == filter;
Cleaning that up a little would give you the following;
private class LambdaCaptures
{
public string filter;
}
var locals = new LambdaCaptures();
locals.filter = "";
ParameterExpression parameterExpression =
Expression.Parameter(typeof(C), "x");
var expr =
Expression.Lambda<Func<C, bool>>(
Expression.Equal(
Expression.Call(
Expression.MakeMemberAccess(
parameterExpression,
typeof(C).GetProperty(nameof(C.Name))
),
typeof(string).GetMethod(nameof(string.ToLower), new Type[] { }),
Array.Empty<Expression>()
),
Expression.Field(
Expression.Constant(locals, typeof(LambdaCaptures)),
typeof(C).GetField(nameof(LambdaCaptures.filter))
)
),
parameterExpression);
Which you can now tweak to replace the incoming type and property name.
Note that you'll want to keep the captured lambda so that EF binds this value as a parameter. Otherwise EF and Sql server will need to recompile the query every time.
Option 2, you can use an ExpressionVisitor to tweak a template expression. For example, if you had an expression for both the field you wish to compare, and the comparison you wish to perform. You can replace the parameter from one expression with the body of the other.
Giving a complete solution that would look something like;
public static Expression<Func<T, bool>> BuildExpr<T, V>(Expression<Func<V, bool>> operation, Expression<Func<T, V>> value)
=> Expression.Lambda<Func<T, bool>>(
ReplacingExpressionVisitor.Replace(
operation.Parameters.Single(),
value.Body,
operation.Body
),
value.Parameters.Single());
public static IQueryable<T> EqualsOrLike<T>(this IQueryable<T> query, Expression<Func<T, string>> value, bool isLike, string filter)
{
if (string.IsNullOrEmpty(filter))
return query;
if (isLike)
{
filter = $"%{filter.ToLower()}%";
var expr = BuildExpr(x => EF.Functions.Like(x, filter), value);
return query.Where(expr);
}
else
{
filter = filter.ToLower();
var expr = BuildExpr(x => x.ToLower() == filter, value);
return query.Where(expr);
}
}
query = query.EqualsOrLike(d => d.Name, filters.NameIsLike, filters.NameValue);
Since this type of replacement is a fairly common operation, you can re-use EF Core's ReplacingExpressionVisitor instead of writing your own.
You can use a Func to select the field from the result:
public static IQueryable<T> EqualsOrLike<T>(this IQueryable<T> query, Func<T, string> fieldSelector, bool isLike, string filter)
{
if (isLike)
return query.Where(x => EF.Functions.Like(fieldSelector(x).ToLower(), $"%{filter.ToLower ()}%"));
else
return query.Where(x => fieldSelector(x).ToLower() == filter.ToLower ());
}
You would then call it like so:
var results = someQueryable.EqualsOrLike(x => x.Name, false, "Robert");

How to use multiple 'Where' expressions and chain them together with AND and OR using C#/.NET?

I am trying to make a filtering system in my web app. The problem is I don't know how many filters will be requested from my client to API. I've build it so the array of the filters comes from a single string like this: ?sizeFilters=big,small,medium
Then I use a string[] names = sizeFilters.Split(','); to get single expression like Where(x => x.listOfSizes.contains(names[index]));
I need also to make the chain of the expression using AND and OR because I am gonna use another filter for example: '?typeFilters=normal,extra,spicy'
So I need to make it that the whole expressions looks like this but it might be few times longer, it needs to work with different size of arrays:
return items Where size is big OR small OR medium AND Where type is normal OR extra OR spicy
Where(x => x.Sizes == "Small" || x => x.Sizes == "Medium" || x => x.Sizes == "Big" &&
x => x.Types == "normal" || x => x.Types == "extra" || x => x.Types == "Spicy")
The simplest option would be, as others have noted, to build your ORs using Enumerable.Contains within an expression; and to build your ANDs by calling Where multiple times.
// using these values as an example
string[] sizeTerms = /* initialize */;
string[] typeTerms = /* initialize */;
IQueryable<Item> items = /* initialize */
if (sizeTerms.Any()) {
items = items.Where(x => sizeTerms.Contains(x.Size));
}
if (typeTerms.Any()) {
items = items.Where(x => typeTerms.Contains(x.Type));
}
If you want, you could wrap this logic into an extension method that takes an expression to filter against, and an IEnumerable<string> for the filter values; and constructs and applies the Contains method:
// using System.Reflection
// using static System.Linq.Expressions.Expression
private static MethodInfo containsMethod = typeof(List<>).GetMethod("Contains");
public static IQueryable<TElement> WhereValues<TElement, TFilterTarget>(
this IQueryable<TElement> qry,
Expression<Func<TElement, TFilterTarget>> targetExpr,
IEnumerable<string> values
) {
var lst = values.ToList();
if (!lst.Any()) { return qry; }
return qry.Where(
Lambda<Expression<Func<TElement, bool>>>(
Call(
Constant(lst),
containsMethod.MakeGenericMethod(typeof(T)),
targetExpr.Body
),
targetExpr.Parameters.ToArray()
)
);
}
and can be called like this:
qry = qry
.WhereValues(x => x.Size, sizeTerms)
.WhereValues(x => x.Type, typeTerms);
One caveat: the query will be built based on the values passed into the method; if they are later changed, the query won't reflect those changes. If this is an issue:
get the appropriate overload of Enumerable.Contains, instead of List.Contains, and
use the overload of Expression.Call which produces a static method call, instead of an instance method call.
I think following should work
var query = _context.Set<[Entity]>();
if (sizeFilterPresent)
{
query = query.Where(r => sizes.Contains(r.Size));
}
if(typesFilterPresent)
{
query = query.Where(r => types.Contains(r.Type));
}
var results = query.ToList();
You can try this,
var result = data.Where(p => sizeFilters.Contains(p.Size) && typeFilters.Contains(p.Type));
You can simply call .Where multiple times to AND expressions together. Dynamically OR-ing expressions together is much more difficult. You'll need to rebuild the Expression graph to include the OrElse operator, and ensure that all expressions are based on the same ParameterExpression.
public class Replacer : ExpressionVisitor
{
private readonly Dictionary<Expression, Expression> _replacements;
public Replacer(IEnumerable<Expression> before, IEnumerable<Expression> after)
{
_replacements = new Dictionary<Expression, Expression>(before.Zip(after, (a, b) => KeyValuePair.Create(a, b)));
}
public override Expression Visit(Expression node)
{
if (node != null && _replacements.TryGetValue(node, out var replace))
return base.Visit(replace);
return base.Visit(node);
}
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
if (expr1 == null)
return expr2;
if (expr2 == null)
return expr1;
return Expression.Lambda<Func<T, bool>>(
Expression.OrElse(
expr1.Body,
new Replacer(expr2.Parameters, expr1.Parameters).Visit(expr2.Body)
),
expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
if (expr1 == null)
return expr2;
if (expr2 == null)
return expr1;
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(
expr1.Body,
new Replacer(expr2.Parameters, expr1.Parameters).Visit(expr2.Body)
),
expr1.Parameters);
}
// Usage
Expression<Func<TableObject, bool>> where = null;
if (...)
where = where.Or(x => sizeFilters.Contains(x.Size));
if (...)
where = where.Or(x => typeFilters.Contains(x.Type));
if (where!=null)
query = query.Where(where);
To make it look neat, my advice would be to create and extension method. This way you can use it as any other LINQ method. See extension methods demystified
Assuming your source is an IQuertyable<TSource>.
public static IQueryable<TSource> WhereAnd<TSource>(
this IQueryable<TSource> source,
IEnumerable<Expression<Func<TSource,bool>>> filterPredicates)
{
// TODO: handle null source, expressions;
IQueryable<TSource> filteredSource = source;
foreach (var predicate in filterPredicates)
{
filteredSource = filteredSource.Where(predicate);
}
}
Usage:
var predicates = new List<Expression<Func<TSource,bool>>>()
{
customer => customer.BirthDay.Year <= 1950,
customer => customer.CityId == GetCityId("New York"),
customer => customer.Gender == Gender.Male,
}
var oldNewYorkMaleCustomers = dbContext.Customers.WhereAnd(predicates).ToList();
Note: an empty collection of filterpredicates will filter by no predicate: you get the original data:
var emptyFilter = Queryable.Empty<Expression<Func<Customer, bool>>>();
var allCustomers = dbContext.Customers.WhereAnd(emptyFilter);

How to add another condition to an expression?

I have an expression like this:
Expression<Func<int, bool>> exp = i => i<15 && i>10;
I want to add a condition to exp after this line. How can I do this?
Simply with this:
Expression<Func<int, bool>> exp = i => i < 15 && i > 10;
var compiled = exp.Compile();
exp = i => compiled(i) && i % 2 == 0; //example additional condition
Note that you can't do it like this:
exp = i => exp.Compile()(i) && i % 2 == 0; //example additional condition
because exp will be added to the closure by reference and as a result, calling it will cause a StackOverflowException.
You have two options. The first one is the version of BartoszKP, to blackbox the first expression and use it afterwards. However, while this has a great syntax support, it also means that systems like the Entity Framework cannot really use the expression, because it is blackboxed. If this expression was used in a database query, the EF could not check this predicate on the server, but has to retrieve all the data to the client, if it works at all.
Thus, if you want to use the expression e.g. for a database query, you have to use the Expression API, i.e.
Expression<Func<int, bool>> exp = i => i<15 && i>10;
exp = Expression.Lambda<Func<int, bool>>(Expression.AndAlso(exp.Body, ...), exp.Parameters[0]);
The three dots indicate the expression that you want to insert as second part. You could use another expression created by the compiler, but you would then have to replace the parameters.
I found the answer from https://entityframework.net/ for .Net Framework 6.0
which also worked for me with .net core
class Program
{
static void Main(string[] args)
{
Expression<Func<int, bool>> exprA = a => a == 3;
Expression<Func<int, bool>> exprB = b => b == 4;
Expression<Func<int, bool>> exprC =
Expression.Lambda<Func<int, bool>>(
Expression.OrElse(
exprA.Body,
new ExpressionParameterReplacer(exprB.Parameters, exprA.Parameters).Visit(exprB.Body)),
exprA.Parameters);
Console.WriteLine(exprA.ToString());
Console.WriteLine(exprB.ToString());
Console.WriteLine(exprC.ToString());
Func<int, bool> funcA = exprA.Compile();
Func<int, bool> funcB = exprB.Compile();
Func<int, bool> funcC = exprC.Compile();
Debug.Assert(funcA(3) && !funcA(4) && !funcA(5));
Debug.Assert(!funcB(3) && funcB(4) && !funcB(5));
Debug.Assert(funcC(3) && funcC(4) && !funcC(5));
}
}
Note that: ExpressionParameterReplacer is a helper class that you should put it in your helpers or anywhere accessible, and does not exists in standard packages.
public class ExpressionParameterReplacer : ExpressionVisitor
{
public ExpressionParameterReplacer(IList<ParameterExpression> fromParameters, IList<ParameterExpression> toParameters)
{
ParameterReplacements = new Dictionary<ParameterExpression, ParameterExpression>();
for (int i = 0; i != fromParameters.Count && i != toParameters.Count; i++)
ParameterReplacements.Add(fromParameters[i], toParameters[i]);
}
private IDictionary<ParameterExpression, ParameterExpression> ParameterReplacements
{
get;
set;
}
protected override Expression VisitParameter(ParameterExpression node)
{
ParameterExpression replacement;
if (ParameterReplacements.TryGetValue(node, out replacement))
node = replacement;
return base.VisitParameter(node);
}
}
Sample in my own scenario
My normal usage of this was to add multiple conditions together in one of my services, which I do not have direct access to the Query so I cannot use multiple .Where() functions:
Expression<Func<Order, bool>> filter = w => ...;
// Extra complex filters which I do not feed to my request models
Expression<Func<Order, bool>> filter2 = null;
switch (model.PredefinedFilter)
{
case OrderPredefinedFilterEnum.SupportPending:
filter2 = w => (((w.Cart.CartFlow == CartFlowEnum.Buyer_First_Order_Request &&
w.Cart.CartStatus == CartStatusEnum.PaidByBuyer)
|| (w.Cart.CartFlow == CartFlowEnum.Seller_First_Suggestion &&
w.Cart.CartStatus ==
CartStatusEnum.WaitingForPaymentConfirmByBuyer)) &&
w.Cart.CartSupportStatus == CartSupportStatusEnum.Waiting);
break;
...
}
if(filter2 != null)
filter = Expression.Lambda<Func<Order, bool>>(Expression.AndAlso(filter.Body,
new ExpressionParameterReplacer(filter2.Parameters, filter.Parameters).Visit(filter2.Body)),
filter.Parameters[0]);
result = (await _orderRepository.GetAllAsNoTrackingAsync(
a => totalCount = a,
filter,
selector,
OrderBy,
take,
skip, cancellationToken: cancellationToken)).ToList();
Thanks:
#Georg answer helped me in this matter. thank you.
Also #BartoszKP asnwer is cool and simple, but doesn't work with EF and query, so I think it is a good solution for in memory data...

My ObjectSet filter doesn't get translated into SQL

I have written this filter to get only documents that match certain periods of time from the database :
The Period entity is straightforward and contains two properties : DateFrom and DateTo.
I need to build a filter from lambdas, each one for each Period that is submitted to build the filter.
The filter, when is completely built, has to look like this :
ObjectSet.Where(d =>
(d.Date >= Period1.DateFrom && d.Date <= Period1.DateTo)
|| (d.Date >= Period2.DateFrom && d.Date <= Period2.DateTo)
|| (d.Date >= Period3.DateFrom && d.Date <= Period3.DateTo));
As you can guess, I have to dynamically build this filter because the number of submitted periods to build the filter can vary.
(The following is the Expression I use to combine the lambdas (each one for each period of time that have been submitted to build the filter)
private Expression<Func<T, bool>> CombineWithOr<T>(
Expression<Func<T, bool>> firstExpression,
Expression<Func<T, bool>> secondExpression)
{
var parameter = Expression.Parameter(typeof(T), "x");
var resultBody = Expression.Or(
Expression.Invoke(firstExpression, parameter),
Expression.Invoke(secondExpression, parameter));
return Expression.Lambda<Func<T, bool>>(resultBody, parameter);
}
Here is where I combine each lambda for each period there is to add to the document filter :
public IList<Document> GetDocuments(IList<Periods> periods)
{
Expression<Func<Document, bool>> resultExpression = n => false;
foreach (var submittedPeriod in periods)
{
var period = submittedPeriod;
Expression<Func<Document, bool>> expression =
d => (d.Date >= period.DateFrom && d.Date <= period.DateTo);
resultExpression = this.CombineWithOr(resultExpression, expression);
}
var query = this.ObjectSet.Where(resultExpression.Compile());
}
The problem is, when I launch deferred execution of the query ...
var documents = query.ToList();
... and I look at the resulting SQL, nothing is added to the SELECT statement.
If I execute the query without compiling the resulting Expression like this :
var query = this.ObjectSet.Where(resultExpression);
I get this exception :
The LINQ expression node type 'Invoke' is not supported in LINQ to
Entities.
That means that the Linq-To-Entities query provider doesn't know how to translate my filter into SQL code.
What is bugging me right now is how such a simple DateTime comparison from entities (Document and Period) that are both part of my Entity schema can mess up the provider ?
Any ideas how I can achieve such a filtering ?
try .AsExpandable() before the query. More information is here
The problem is with your combining function. SQL to Entities doesn't really like Invoke. Here's a combining function that worked for me:
public static class ExpressionCombiner
{
public static Expression<Func<T, bool>> Or<T>(Expression<Func<T, bool>> a, Expression<Func<T, bool>> b)
{
var parameter = Expression.Parameter(typeof(T), "x");
var substituter = new SubstituteParameter(parameter, p => true);
var resultBody = Expression.Or(
substituter.Visit(a.Body),
substituter.Visit(b.Body));
Expression<Func<T, bool>> combined = Expression.Lambda<Func<T, bool>>(resultBody, parameter);
return combined;
}
}
public class SubstituteParameter : ExpressionVisitor
{
private ParameterExpression toReplace;
private Func<ParameterExpression, bool> isReplacementRequiredFunc;
public SubstituteParameter(ParameterExpression toReplace, Func<ParameterExpression, bool> isReplacementRequiredFunc)
{
this.toReplace = toReplace;
this.isReplacementRequiredFunc = isReplacementRequiredFunc;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return isReplacementRequiredFunc(node) ? toReplace : node;
}
}

Replace parameter value in Expression Tree

After having searched for quite a while, I am still not finding the answer I am looking for. I have found answers about adding and removing parameters from a tree, but not anything about replacing specific parameters.
My first method is working as I would like it to, I need to replace the partitionKey value with the Uri escaped value and then return the results un-escaped.
public override IList<T> GetRowEntityList(string partitionKey)
{
IList<T> rowEntities = base.GetRowEntityList(Uri.EscapeDataString(partitionKey));
return rowEntities.Select(UnEscapeRowEntity).ToList();
}
The problem I am having is overriding this method to behave the same way. I already know that type T has the properties PartitionKey and RowKey but can also have any other number of properties.
For a sample predicate:
x => x.RowKey == "foo/bar" && x.SomeValue == "test"
I would expect it to become
x => x.RowKey == Uri.EscapeDataString("foo/bar") && x.SomeValue == "test"
Is there a way to do this?
My base class uses this predicate to do a table lookup on a table containing entities of type T using a Where(predicate) call
public override IList<T> GetRowEntityList(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
//modify predicate value here
return base.GetRowEntityList(predicate);
}
You need to implement an ExpressionVisitor:
class MyVisitor : ExpressionVisitor
{
protected override Expression VisitBinary(BinaryExpression node)
{
if(CheckForMatch(node.Left))
return Expression.Equal(node.Left, Rewrite(node.Right));
if(CheckForMatch(node.Right))
return Expression.Equal(Rewrite(node.Left), node.Right);
return Expression.MakeBinary(node.NodeType, Visit(node.Left), Visit(node.Right));
}
private bool CheckForMatch(Expression e)
{
MemberExpression me = e as MemberExpression;
if(me == null)
return false;
if(me.Member.Name == "RowKey" || me.Member.Name == "PartitionKey")
return true;
else
return false;
}
private Expression Rewrite(Expression e)
{
MethodInfo mi = typeof(Uri).GetMethod("EscapeDataString");
return Expression.Call(mi, e);
}
}
I think that's right. It's a bit hard to test. Please note this will only work for the limited case of (x => x.RowKey == "some string"). It won't work for (x => x.RowKey.Equals("somestring"). It also won't work for (x => x.RowKey() == "some string").
You then use the implemented visitor to re-write the predicate:
Expression<Func<T, bool>> predicate = (s => s.RowKey == "1 2");
ExpressionVisitor v = new MyVisitor();
Expression<Func<T, bool>> rewrittenPredicate = v.Visit(predicate);
//rewrittenPredicate then tests if s.RowKey == "1%202"

Categories

Resources