简体   繁体   中英

Cast ITable to IEnuerable<object> - Dynamic LINQ to SQL Query with no DataTable information

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

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM