問題描述
首先,我不知道用什么術語來問這個問題,這可能是我自己搜索沒有找到答案的原因.
Firstly, I am not sure what terms to use to ask this question, which is probably why I have not found an answer from searching myself.
因此,我正在使用 Linq to SQL(C#、.Net 4),并且我想獲得符合條件的所有用戶的列表,我將執行以下操作的基礎知識:
So I am working with Linq to SQL (C#, .Net 4) and I want to get a list of all users that match a criteria, the basics of which I would do something like this:
var users = DataContext.Users.Where(x => x.Criteria1 == "something");
但在這種情況下,我想匹配一些字段,問題是這些特定字段是一個常見的檢查,我希望能夠創建一個專用函數,我可以在我的任何用戶查詢中使用它檢查這個匹配.
but in this case there are a few fields I want to match, the thing is these particular fields are a common check and I would like to be able to create a dedicating function that I can use within any of my user queries to check for this match.
為了更好地解釋這一點,讓我們舉一個例子:假設一個用戶有 5 個標志,我想要一個共同的檢查來查看是否設置了任何這些標志.所以我可以這樣寫我的查詢:
To try and explain that a bit better lets give an example: Lets say a user has 5 flags, and I want a common check to see if any of those flags are set. So I could write my query like so:
var users = DataContext.Users.Where(x => x.Flag1 || x.Flag2 || x.Flag3 || x.Flag4 || x.Flag5);
但是我想做的是將5 標志檢查"分開,這樣我也可以在其他查??詢中使用它,最終我想使用類似的東西:
But what I would like to do is seperate out that "5 flag check" so I can use it in other queries too, ultimately I would like to use something like:
var users = DataContext.Users.Where(x => x.Criteria1 == "something" && CheckForFlags(x));
我已經嘗試過使用這樣的函數:
I have tried this by having a function like this:
static bool CheckForFlags(User user)
{
return user.Flag1 || user.Flag2 || user.Flag3 || user.Flag4 || user.Flag5;
}
但我收到一個錯誤:
"方法 'Boolean CheckForFlags(User)' 不支持轉換為SQL."
"Method 'Boolean CheckForFlags(User)' has no supported translation to SQL."
...這是有道理的,但我可以做些什么來使這項工作按照我想要的方式工作?或者這是一個限制,因為我使用的是 Linq to SQL 而實際上它可以與 Linq to Objects 一起使用?
...which makes sense, but it there something I can do to make this work the way I want it to? Or is this a restriction because I am using Linq to SQL and is in fact something that would work with Linq to Objects?
推薦答案
關于 LINQ to SQL 如何處理表達式的巧妙之處在于,您實際上可以在代碼的其他地方構建表達式并在查詢中引用它們.你為什么不嘗試這樣的事情:
The neat thing about how LINQ to SQL handles expressions is that you can actually build out expressions elsewhere in your code and reference them in your queries. Why don't you try something like this:
public static class Predicates
{
public static Expression<Func<User, bool>> CheckForFlags()
{
return (user => user.Flag1 || user.Flag2 || user.Flag3 ||
user.Flag4 || user.Flag5);
}
public static Expression<Func<User, bool>> CheckForCriteria(string value)
{
return (user => user.Criteria1 == value);
}
}
一旦定義了謂詞,就可以很容易地在查詢中使用它們.
Once you have your predicates defined, it's very easy to use them in a query.
var users = DataContext.Users
.Where(Predicates.CheckForFlags())
.Where(Predicates.CheckForCriteria("something"));
這篇關于創建通用謂詞函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!