簡體   English   中英

如何創建動態的where子句?

[英]How to create a dynamic where clause?

在下面的代碼中

string cluase = string.Empty;
string whereValue = string.Empty;

foreach (var i in whereCluaseItems)
{
    if (cluase != "")
    {
        cluase += " and " + i.Name;
    }
    else
    {
        cluase = i.Name;
    }
    if (whereValue != "")
    {
        whereValue += "," + i.Value;
    }
    else
    {
        whereValue = i.Value;
    }
}

var result = context.vCatalogItemsDetails
                    .Where(cluase, whereValue) 
// since where syntax has to be like this : where("@landuageID=@0,categoryid=@1", 1,1)
.OrderBy("itemID")
.Skip((pageN - 1) * 10).Take(10);

cluase是一個字符串,其中包含"languageId=@0, categoryid=@1"

whereValue也是一個字符串,它包含"1,1"

我需要刪除那些引號。 我該怎么做?

對於這種“動態” where子句,通常無需使用基於表達式的功能。 您只需要意識到可以組成多個Where調用。

例如:

public static IEnumerable<Person> Filter(this IEnumerable<Person> source, 
    string firstname, string lastname)
{
    if (firstname != null)
    {
        source = from person in source
                 where person.Firstname.Contains(firstname)
                 select person;
    }

    if (lastname != null)
    {
        source = from person in source
                 where person.Lastname.Contains(lastname)
                 select person;
    }

    return source;
}

同樣的技術也適用於IQueryable<T>

借助Dynamic LINQ庫可以做到這一點,它就這么簡單:

var result = context.vCatalogItemsDetails
                    .Where(cluase, whereValue) 
                    .Where("landuageID=1 AND categoryid=1")
                    .OrderBy("itemID")
                    .Skip((pageN - 1) * 10).Take(10);

暫無
暫無

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

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