0

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

dashnick
  • 2,020
  • 19
  • 34

1 Answers1

1

Short Answer

NO.

Long Answer

ITable has this signature:

public interface ITable : IQueryable, IEnumerable

If you have an instance of a type which implements that, like below:

public class MyTable : System.Data.Linq.ITable
{
    // Implementation ...
}

And you do this:

var myTable = new MyTable();
var iterator = myTable as IEnumerable<Object>;

It will return null because MyTable implements ITable and both of them do not implement IEnumerable<T> interface.

However, this will work:

var iterator = myTable as IEnumerable; // or IQueryable

So depending on what you mean by Is it correct to cast the ITable to an IEnumerable<object> as I've done here. It will not throw exception, but it will never result in anything until you use it and it will blow up with a null reference exception on this line:

query = query.Where(whereField + "=" + whereValue); 
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64