2016-06-10 14 views
2

我想與where子句這樣的字符串運行動態LINQ子句:C#DynamicLinq其中任何具有()

query = db.Customers.Where("Categories.Any(Code == 'Retail')"); 

客戶實體有類別的集合

class Customer 
{ 
    public List<Category> Categories {get;set;} 
    ... 
} 

class Category 
{ 
    public Guid Id {get;set;} 
    public string Code {get;set;} 
} 

誰能告訴我是否有可能做這樣的事情?

PS:我需要where子句是字符串。 where子句將在運行時生成,因此我無法使用Linq查詢表達式。

我正在使用Telerik DataAccess。

+0

什麼是動態條款的可能的變化,你的意思是不固定的代碼或全部條件?你能舉出更多不同的例子嗎? – user3185569

+1

您可以使用['Expression'](https://msdn.microsoft.com/en-us/library/ms173144.aspx)進行此操作。可能需要一些構建器才能將表達式樹的字符串查詢生成。 –

+0

您正在使用的EF版本是什麼? – Hamed

回答

3

它儘快可能你按照Expression Language規則。

例如,字符串必須用雙引號:

query = db.Customers.Where("Categories.Any(Code == \"Retail\")"); 
1

它不應該像下面那樣嗎?

refinedCustomerList = db.Customers.Where(customer => customer.Categories.Any(Code == 'Retail')); 

以上列表將包含所有,其類別爲 '零售'

1

你需要像這樣的客戶:

query = db.Customers.Where(x => x.Categories.Where(y => y.Code == "Retail").Any()); 
+0

我需要where子句是string。 – Daler

+0

@Daler是什麼原因? – Sherlock

+0

因爲它沒有預定義,子句將在運行時生成。 – Daler

2

你可以建立自己的運行時Expression

Expression<Func<Customer, bool>> myRuntimeExpression = null; 

if(condition1) 
{ 
    myRuntimeExpression = cust => cust.Categories.Any(cat => cat.Code == "Retial"); // or some local variable 
} 
else if(condition2) 
{ 
    myRuntimeExpression = cust => cust.Categories.Any(cat => cat.Id = someId) == false; 
} 
else if(condition3) 
{ 

} 

var query = DB.Customers.Where(myRuntimeExpression); 

但是,如果您需要構建更復雜的查詢,請查看Dynamic Queries in Linq Using Expressions

1

linq extention method were接受型System.Func<TSource, Int32, Boolean>

  • 的參數在你的情況下,Func是臨危一個Customer作爲參數,返回真/假。
    Where函數的結果將是CustomersFunc返回true

"Categories.Any(Code == 'Retail')"是一個字符串,而不是一個Func,因此不能作爲一個參數傳遞給Where方法傳遞。

你正在尋找也許是什麼,如果你想保留查詢靈活一些事情,如:

Public Customer[] QueryCustomers(Func<Customer,bool> predicate) 
{ 
    var result = db.Customers.Where(c=> predicate(c)).ToArray(); 
    return result; 
} 

用法:

var retailCustomers = 
     QueryCustomers(customer => customer.Categories.Any(Code == 'Retail')) 

或者你可能在運行構成任何其他查詢/編譯時間:

var customersWithNoCategories = 
     QueryCustomers(customer => customer.Categories.Count == 0) 
相關問題