views:

27

answers:

2

I'd like to build some linq or alternatively, build a query string on the fly and pass it to a WCF Data Service (with Entity Framework data model).

Something like this:

 public List<DocumentInformationRecord> SearchClientDocs(string clientCode,
            string clientName, string contactName, string groupCode, string groupName,
            string filename, string createdby, DateTime dateFrom, DateTime dateTo)
 {
   List<DocumentInformationRecord> results = new List<DocumentInformationRecord>();
   if(!string.IsNullOrEmpty(clientCode)) 
   //Add the client code clause...

etc..

var qry = from c in context.DocumentInformationRecord.where(dynamicQuery);

            //Etc......

Any ideas? I tried the predicate builder (http://www.albahari.com/nutshell/predicatebuilder.aspx) but got some invalid operation exceptions.....

+1  A: 

I am not sure I entirely understand your question, but I have sometimes written code to build up LINQ queries with different parts depending on input. Typically that goes something like this:

var qry = from item in someList
          select item;

if (nameFilter != null)
{
    qry = qry.Where(item => item.Name == nameFilter);
}

if (someOtherFilter != null)
{
    qry = qry.Where(item => item.SomeOtherStuff == someOtherFilter);
}
// and so on

That way you can build the query step by step. You can do this because of deferred execution; the query will not be executed against the data source until you start iterating over the result.

Fredrik Mörk
This works well but not if the resulting query has to be a long combination of and's and or's that have to be built up at runtime.
Dave Stringer
A: 

Not sure if it will suit your situation, but you can use expression trees to build dynamic queries. There is a good tutorial here

Giles
I went down the route of building the Dataservice query with a built up string and the qry.AddQueryOption("$filter") method instead. But expression trees are the best way, just for now it seemed quicker to go down the $filter option.
Dave Stringer