score:6
following some other links , i found a couple of options. one would be to dynamically create the expression tree which became a quagmire rather quickly, the other is to build the $filter manually. however and add it with .addqueryoption() . however if there are already other where clauses in the query this breaks since the resulting url now has two $filter entries.. so what i do is take my original query, and then grab the url and the querystring and grab the $filter , and then if it exists add my own dynamic stuff and run a new query. here is a demo (running in linqpad)
//grab original query as a dataservicequery
dataservicequery<networkdevice> originalquery = (dataservicequery<networkdevice>)
(from x in networkdevices
where
x.type == "switch"
select x);
//get the http querystring
var querystr = (originalquery).requesturi.query;
var filter = system.web.httputility.parsequerystring(querystr)["$filter"];
/* create our own dynamic filter equivilant to
x.name == "x" ||
x.name == "y"
*/
string[] names = { "device1", "device2" };
stringbuilder sb = new stringbuilder();
sb.append("(");
foreach (string s in names)
{
sb.append(string.format("name eq '{0}'",s));
sb.append(" or ");
}
sb.remove(sb.length - 4, 4);
sb.append(")");
var dynamicfilter = sb.tostring();
// if there was an original filter we'll add the dynamic one with and , otherwise we'll just use the dynamicone
var newfilter = dynamicfilter;
if ( filter != null && filter.trim() != string.empty )
{
newfilter = filter + " and " + newfilter;
}
newfilter.dump();
var finalquery =
(from x in networkdevices.addqueryoption("$filter",newfilter)
select x).take(50);
finalquery.dump();
score:0
here's an example of an expressionvistor which i used to convert a contains into an orelse:
public class wherecontainstreemodifier : expressionvisitor
{
private expression translatecontains(lambdaexpression lambda)
{
var methodcall = lambda.body as methodcallexpression;
var member = methodcall.object as memberexpression;
var objectmember = expression.convert(member, typeof(object));
var getterlambda = expression.lambda<func<object>>(objectmember);
var getter = getterlambda.compile();
var list = (ienumerable)getter();
expression result = null;
foreach (object item in list)
{
var equal = expression.equal(methodcall.arguments[0], expression.constant(item));
if (result == null)
result = equal;
else
result = expression.orelse(result, equal);
}
result = expression.lambda(lambda.type, result, lambda.parameters);
return result;
}
protected override expression visitlambda<t>(expression<t> node)
{
if ((node.body as methodcallexpression).method.name == "contains")
return translatecontains(node);
else
return node;
}
}
Source: stackoverflow.com
Related Query
- How to dynamic add filters to a LINQ query against an Odata Source in C#
- How to create a dynamic 'contains or LIKE' Expression to be used with Linq against OData service
- How to effectively do dynamic query using LINQ against a Azure Cosmos Document DB SQL API?
- How to add multiple dynamic conditions or filters into LINQ query.?
- How to add single quotes for string value of dynamic query string and use it in linq
- How do I add ROW_NUMBER to a LINQ query or Entity?
- How do you add dynamic 'where' clauses to a linq query?
- How do I write a linq query against a ListCollectionView?
- How can I build Linq query with dynamic OR statements?
- How to write this Linq SQL as a Dynamic Query (using strings)?
- How to cast a Linq Dynamic Query result as a custom class?
- How can I create a dynamic LINQ query in C# with possible multiple group by clauses?
- Dynamic Linq query - how do I build the select clause?
- How to add empty groups to a Linq query result set?
- linq - how do you do a query for items in one query source that are not in another one?
- How can I write the following code more elegantly using LINQ query syntax?
- How to build a nested query with the dynamic LINQ library
- How to get SQL query into LINQ form in C# code
- How to add left outer join to grouped and summed LINQ query
- How can I code a Linq query to do an upward Include?
- How to do a "join" in a LINQ query against the Entity Framework
- how to add days to datetime by selecting in linq query
- How does nesting an OrderBy in a Dynamic Linq query work?
- Creating dynamic linq expression tree against nested OData
- How to add LINQ to SQL query results to Observable Collection?
- How to utilize EF and LINQ to add filters and specify tables, columns, filters and order by dynamically
- How to add conditional condition to LINQ query based on a previously returned value
- How do you write a LINQ query that filters a sub table to a specific time period and sums the results of the sub table?
- how to create dynamic linq query based on search criterias
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
More Query from same tag
- exception( Input string wasn't in the correct format )
- ASP.NET GridView DataSource with LINQ and Joins
- Linq query assigning count= zero to list object in mvc
- How can I create SQL that does a Left Outer Join and also a count from another table?
- Operator '==' cannot be applied to operands of type 'method group' and 'string'
- group List<T> and create new list with count
- Concatanating a new object
- While loop to linq
- CLRSQL Aggregate function. LINQ Code works within CLR Function but cannot be deploy within Aggregate
- Using Linq to query repository returning invalid results
- how to compare dates in linq
- Linq XDocument return a list of elements based on 2 attribute values
- LINQ right join and left join
- Passing in Func<T, bool> to LINQ Where
- LinqToXml: parsing and formatting
- How to fix: linq query returns @p_linq_0 instead of variable
- c# Dapper - using linq on QueryAsync method
- Descendants() with a parameter returns empty result
- Linq recursive search nodes
- LINQ + join with nested foreach razor output writing out title lines from groupby
- Linq select objects in list where exists IN (A,B,C)
- C#, dynamic linq error No applicable method 'Contains' exists in type 'String'
- Can/Should I Linqify this foreach/if/foreach/if/invoke code?
- Import txt to sql database via linq
- Select a single object from Entity IQueryable List of object
- siaqodb query: ArgumentException: The field handle and the type handle are incompatible
- C# LINQ optimization
- convert Dictionary<int, Enumerable> to Dictionary<int, Enumerable> inverting content
- foreach iteration after Select
- Entity Framework Core Linq Where NULL does not work