LINQ - 如何在运行时之前不知道列名时构造查询?

时间:2010-07-15 19:34:55

标签: c# linq-to-entities

假设:

string metadata.XAxisColumn -- contains a column name (e.g., "Date")
string metadata.YAxisColumn -- contains another columnname (e.g., "Close")

当我事先知道列的名称时,我当然可以这样做:

var query = from record in myView 
    where record.Date >= startDate && record.Date <= endDate
    select record.Close

但是,直到运行时才知道列名。他们在metadata.XAxisColumnmetadata.YAxisColumn

构造一个像这样工作的查询的正确方法是什么:

var query = from record in myView 
    where record.[metadata.XAxisColumn] >= startDate && record.[metadata.XAxisColumn] <= endDate
    select record.[metadata.YAxisColumn]

3 个答案:

答案 0 :(得分:1)

您可以使用ESQL / QueryBuilder(内置于EF)或Microsoft Dynamic Query(a.k.a.动态LINQ - 通过VS Code Gallery免费)。

答案 1 :(得分:1)

您可以从“记录”对象的类型派生,并添加一个新属性:

public class MyRecord : RecordBase
{
    public XAxis
    {
        get
        {
            switch (metadata.XAxisColumn)
            {
                // for example only; this code will not compile because it depends what kind of object RecordBase is :)
            case X:
                return this.X;
            case Y:
                return this.Y;        
            }
        }
    }
}

希望有所帮助!

答案 2 :(得分:0)

您可以将Dynamic LINQ用于这些查询