Cast ITable to IEnuerable - Dynamic LINQ to SQL Query with no DataTable information c# dynamic-linq linq linq-to-sql

Question

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

1
0
2/19/2017 7:57:12 PM

Accepted Answer

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); 
1
2/19/2017 7:54:24 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow