I am trying to make a library where I can specify query parameters and operators in an xml file and at runtime i can generate linq expressions based on an xml file. I have it working only on building the “where” expressions so simple queries such as select * from table where table.id = 1. Here is an example of a simple query in the xml file:
<query name="latest">
<PropertyValue PropertyName="TimeStamp" OperatorName="GreaterThanOrEqual" ParamName="lastUpdated" />
</query>
The TimeStamp property name is the name of the Property in the C# class to use. The ParamName is a url parameter coming in from a http request in my asp.net application.
In the code i can build the linq expression out of this and make the following where clause:
(IQueryable<DataObject>)dataObjects.Where(expression);
where expression is:
TimeStamp >= "2011-09-21T11:54:24"
But i have a new type of query that i need to be able to handle:
select * from theTable t where Id=(select top 1 Id from theTable
where Source=t.Source order by Id desc)
This query runs on a table that has an Id field and a Source field. The query returns the newest entry per each Source. So it groups by source and orders it in descending order and returns the first entry for each source. Then the outer select returns all the columns for each of the results in the inner select. Example:
Table:
id source field3 field4
1 Device1 test test
2 Device2 test2 test2
3 Device1 test3 test3
4 Device2 test4 test4
Results of the query:
id source field3 field4
3 Device1 test3 test3
4 Device2 test4 test4
So now i need to dynamically generate a nested query in the where clause. I guess my first question is can that string query be converted to a linq query? Then i need to be able to dynamically build that nested query somehow.. Sorry if it doesn’t make a lot of sense…
Maybe the PredicateBuilder is what you’re looking for?