Dave Stringer
Dave Stringer

Reputation: 359

How do I buid a WCF Query on the fly?

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.....

Upvotes: 0

Views: 607

Answers (2)

Giles Smith
Giles Smith

Reputation: 1972

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

Upvotes: 0

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158369

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.

Upvotes: 1

Related Questions