Creating a common predicate function

前端 未结 5 1295
南方客
南方客 2020-12-14 01:17

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.

So I am working with Linq to S

5条回答
  •  旧巷少年郎
    2020-12-14 01:58

    To the best of my knowledge there are two possible ways to do this.

    The quick-n-easy way to is filter your results after the SQL executes, with something like this:

    var users = DataContext.Users.Where(x => x.Criteria1 == "something");
        .ToEnumerable()
        .Where(x => CheckForFlags(x));
    

    However this is very poor in terms of performance. It will return ALL rows from the database matching only the first criteria, and then filter the results in memory on the client. Functional, but far from optimal.

    The second, much more performant option is to create a UDF on the database itself and call it from LINQ. See for example this question. The obvious downside is that it moves code into the database, which no one likes to do (for lots of valid reasons).

    There may very well be other viable solutions, but those are the only two I know of.

提交回复
热议问题