簡體   English   中英

如何為LINQ查詢構建動態FROM子句?

[英]How to build a dynamic FROM clause for a LINQ query?

我有一個標准的LINQ查詢:

var list = from x in SomeDataContext.ViewName
           where //Rest of where clause
           select x;

我想知道是否可以構建動態LINQ查詢,以便我可以在運行時更改SomeDataContext.ViewName

我有大約5個不同的視圖,都具有執行where子句所需的基本列,但每個其他視圖都有一些不同的列名。

那么是否可以構建查詢以便在需要時可以在運行時使用不同的上下文?

例:

public void SomeMethod()
{
    var listA = GetList("DataContext.ViewA");
    var listB = GetList("DataContext.ViewB");
    var listC = GetList("DataContext.ViewC");
}

public List<EntityObject> GetList(string dataContextName)
{
    return (from x in /*HERE I WANT TO USE THE dataContextName*/
           where //Rest of where clause
           select x).ToList();
}

您可以使用表達式樹來構建動態LINQ查詢。 這是一個例子: http//msdn.microsoft.com/en-us/library/bb882637.aspx

另一種方法是使用動態LINQ庫: http//weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

這兩種方法都在這里說明: http//www.codeproject.com/Articles/231706/Dynamic-query-with-Linq

此示例中的Predicate Builder使用表達式樹方法。

通常,Dynamic LINQ更容易實現,但Expression Tree更加類型安全。

只需添加另一層間接:

public void SomeMethod()
{
    var listA = GetList("DataContext.ViewA");
    var listB = GetList("DataContext.ViewB");
    var listC = GetList("DataContext.ViewC");
}

public List<EntityObject> GetList(string dataContextName)
{
    return (from x in GetSpecificSource(dataContextName)
           where //Rest of where clause
           select x).ToList();
}

public IEnumerable<MyType> GetSpecificSource(string dataContextName)
// Or: public IQueryable<MyType> GetSpecificSource(string dataContextName)
{
    // ToDo: Return the correct source depending on the name. E.g.:
    switch(dataContextName)
    {
        case "DataContext.ViewA":
            return DataContext.ViewA;
        case "DataContext.ViewB":
            return DataContext.ViewB;
        case "DataContext.ViewC":
            return DataContext.ViewC;
    }
}

更新如何使用反射

從具有所需名稱的字段中檢索值:

var fieldName = "ViewA";
var fieldFound = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

if(fieldFound != null)
{
    return fieldFound.GetValue(instance);
}

從具有所需名稱的屬性中檢索值:

var propertyName = "ViewA";
var propertyFound = type.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

if(propertyFound != null)
{
    return propertyFound.GetValue(instance, null);
}

從具有所需名稱的方法中檢索值:

var methodName = "ViewA";
var methodFound = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

if(methodFound != null)
   && methodFound.GetParameters().Length == 0)
{
    return methodFound.Invoke(instance, null);
}

到目前為止,這些只是一些簡單的例子。 反思開啟了一整套問題和問題。 只需從上面的例子開始,檢查它是否符合您的願望。 否則只需回來一個新問題。 ;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM