I need to write dynamic LINQ where I know nothing about the input table - data provider (which is why I'm using LINQ to SQL), no table name, nothing. I want to be able to query the data given user-selected fields and given values, something like the following:
Having a String
TheTableName
, and System.Data.Linq.DataContext
TheContext
:
IEnumerable<object> GetQuery(List<string> theWhereFields, List<string> theWhereValues)
{
// for doing dynamically ala http://stackoverflow.com/a/25859319/3661120
var baseTable = (ITable)TheContext.GetType()
.GetProperty(TheTableName).GetValue(TheContext, null); // http://stackoverflow.com/a/1924966/3661120
IEnumerable<object> query = (IEnumerable<object>) baseTable;
for (int i = 0; i < theWhereFields.Count; i++)
{
var whereField = theWhereFields[i];
var whereValue = theWhereValues[i];
query = query.Where(whereField + "=" + whereValue); // possible due to System.Linq.Dynamic
}
return query;
}
Is it correct to cast the ITable
to an IEnumerable<object>
as I've done here?
Note ITable
is from System.Data.Linq
, https://msdn.microsoft.com/en-us/library/system.data.linq.itable(v=vs.110).aspx