Dynamic query using LINQ to SQL

前端 未结 5 1277
我在风中等你
我在风中等你 2021-01-12 02:21

I need to figure out if it is possible to dynamically build a query with LINQ, dynamically selecting the table in which to perform the query.

This is an example of w

5条回答
  •  不知归路
    2021-01-12 02:46

    I've found a way to do it, but I'm not sure if I'd use this code. If you have a DataContext that contains two tables:

    PrimaryTable 
        ID,
        FirstValue,
        SecondValue
    
    SecondaryTable
        ID,
        FirstSecondaryValue
    

    You could use the following DataHelper class:

    class DataHelper
    {
        public MyDatabaseDataContext db = new MyDatabaseDataContext();
    
        List GetDynamicList() where T : class
        {
            System.Data.Linq.Table table = db.GetTable();
    
            var result = from a in table select a;
    
            return result.ToList();
        }
    
        public List GetWhatIWant(string tableName)
        {
            Type myClass = Type.GetType("DynamicLinqToSql." + tableName);
            MethodInfo method = typeof(DataHelper).GetMethod("GetDynamicList", BindingFlags.NonPublic | BindingFlags.Instance);
            method = method.MakeGenericMethod(myClass);
            return (List)method.Invoke(this, null);
        }
    }
    

    Then you can create an instance of your DataHelper and call the GetWhatIWant method, passing in the table name.

    var dataHelper = new DataHelper();
    
    List myFirstList = dataHelper.GetWhatIWant("PrimaryTable");
    
    for (int i = 0; i < 5 && i < myFirstList.Count; i++)
    {
        System.Console.WriteLine(String.Format("{0} - {1}", myFirstList[i].FirstValue.ToString(),  myFirstList[i].SecondValue.ToString()));
    }
    
    List mySecondList = dataHelper.GetWhatIWant("SecondaryTable");
    
    for (int i = 0; i < 5 && i < mySecondList.Count; i++)
    {
        System.Console.WriteLine(mySecondList[i].FirstSecondaryValue.ToString());
    }
    
    System.Console.ReadKey();
    

提交回复
热议问题