dynamically add join clause in LINQ RRS feed

  • Question

  • how do i crate a dynamically join clause in LINQ? which tables that are going to be used wil be based on the users' selections.
    Monday, September 7, 2009 1:05 AM


  • Hi ronald_yoh,

    Welcome to MSDN Forums!

    Based on your scenario, you can consider the following steps:

    1.      Create the .dbml (LINQ to SQL Classes file) for the database and data tables you want to query. 

    2.      Use .NET Reflection to get the Type object of the certain data class based on the table name selected by the user.

    3.      Call DataContext.GetTable(Type) to retrieve the data table information dynamically.

    private void DynamicQueryDataTable(string tableName)
        Assembly assembly = Assembly.GetExecutingAssembly();
        string ns = "Application Namespace";
        Type t = assembly.GetType(ns + "." + tableName);
        MyDataContext db = new MyDataContext();
        var query = db.GetTable(t).Where("ID >= @0", 1);

    Here I also used the LINQ dynamic query library discussed in this blog,

    This library can help you build the LINQ to SQL query more dynamically. 

    Have a nice day!

    Best Regards,
    Lingzhi Sun

    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    • Marked as answer by Yichun_Feng Monday, September 14, 2009 1:28 AM
    Tuesday, September 8, 2009 7:28 AM