none
Best practice to query a linq provider based on user input ? RRS feed

  • Question

  • Hi,

    I'm starting to build an application that do a lot of query to a DB (actually a SQL CE one, but it can change in a future version).
    This queries are made through a Linq to sql context, build with sqlmetal.
    I'd like to have a navigation pane (a kind of treeview) with some queries. Queries can be "standard" builtin queries (IE, all customers, last orders, etc.), or can be user defined (IE, all customers in city XXX, orders I have to track, etc.).

    My question does not concern the UI part but the DataAccess part. Since the queries must be savec from one session to the others, I'd like to know how to correctlry handle this functionnality. The construction of the query should remain quite simple (I'm taking outlook and view configuration as a reference). The user can said "Field XXXX equals YYYY" AND "Field YYYY greater than equals ZZZZ" and so on.

    I'd like to represent my queries in a class like this :

    [Serializable] // Must be serializable for query persistance
    public class Query
    {
    public List<Criteria> Criterias { get; set;}
    public QueryType { get; set;}
    }
    
    public class Criteria
    {
    public Operator Operator { get; set ;}
    public string FieldName {get; set; }
    public object Value { get; set }
    }
    
    public enum QueryType {
    AllMustMatch, // --> AND
    OneMustMatch // --> OR
    }
    
    public enum Operator{
    Equals,
    NotEquals,
    NotEmpty
    // other operators
    }




    My queries will be interpreted by a Repository engine class
    public class Repository
    {
    public IEnumerable<Item> Execute(Query q)
    {
    // TODO: implementation
    }
    }


    Do you know how I can (should) implement my Execute method ? Is there any way to rely on Linq's expression (in this case I have to be able to create on the fly expression?) ?

    My app is only in draft by now... I can change everything if required.

    I'd appreciate any help !

    Thanks in advance,
    Steve
    Tuesday, June 2, 2009 11:14 AM

Answers

  • The Dynamic LINQ sample should help:

    http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

    Joe
    Write LINQ queries interactively - www.linqpad.net
    • Marked as answer by Steve B_ Tuesday, June 2, 2009 1:49 PM
    Tuesday, June 2, 2009 1:29 PM
    Answerer

All replies

  • The Dynamic LINQ sample should help:

    http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

    Joe
    Write LINQ queries interactively - www.linqpad.net
    • Marked as answer by Steve B_ Tuesday, June 2, 2009 1:49 PM
    Tuesday, June 2, 2009 1:29 PM
    Answerer
  • Thanks, this seems to help me to solve my problem... I'll test it !
    Tuesday, June 2, 2009 2:00 PM