简体   繁体   English

将ITable转换为IEnuerable <object> -没有数据表信息的动态LINQ to SQL查询

[英]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. 我需要编写动态LINQ,其中我对输入表一无所知-数据提供程序(这就是为什么我使用LINQ to SQL),没有表名,一无所知。 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 : 具有一个String TheTableNameSystem.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? ITable转换为IEnumerable<object>是否正确?

Note ITable is from System.Data.Linq , https://msdn.microsoft.com/en-us/library/system.data.linq.itable(v=vs.110).aspx 注意ITable来自System.Data.Linqhttps: ITable ( v= ITable

Short Answer 简短答案

NO. 没有。

Long Answer 长答案

ITable has this signature: ITable具有以下签名:

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. 由于MyTable实现ITable并且它们都不实现IEnumerable<T>接口,因此它将返回null。

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 . 因此,根据您的意思, 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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