避免在Linq Select方法中重复代码 [英] Avoiding duplicate code in Linq Select method
问题描述
我有些愚蠢的情况,无法为烦人的问题找到简单而优雅的解决方案.
I have some stupid situation where I can't find simple and elegant solution for annoying problem.
我编写具有简单UI的asp.net应用程序,用于根据用户选择查询数据库.为了使用实体框架查询DB I.
I writing asp.net application with simple UI for querying database based on user choices. For querying DB I using Entity Framework.
在我的情况下,可选用户选择之一是自由文本,为此,我使用SQL Server FTS功能(使用
In my scenario, one of the optional user choices is a free text, and for that I using SQL Server FTS capabilities (using CONTAINSTABLE function, since I need to order results by relevance).
现在,我遇到以下情况:
Now, I have the following situation:
如果用户没有提供了自由文本条件,我将创建一个简单的Linq查询,其结果类型为IQueriable<Result>
(其中"Result"是具有表中数据的实体)
If user did not provided free text criteria, I creating simple Linq query with result of type IQueriable<Result>
(where 'Result' is an entity with data from table)
但是,如果用户 did 提供了自由文本条件,我将使用CONTAINSTABLE创建查询,其类型为IQueriable<ResultWithRank>
(其中"ResultWithRank"是一个包含两个实体的对象:"Result"和排名",因为CONTAINSTABLE会导致内部联接.
But, if user did provided free text criteria, I creating query with CONTAINSTABLE, and its type is IQueriable<ResultWithRank>
(where 'ResultWithRank' is a object contains two entities: 'Result' and 'Rank', since CONTAINSTABLE results in inner join).
在此阶段,构建可查询对象后,需要在其上执行选择"方法,以将其转换为有用的东西.
At this stage, after I built my queriable, I need to execute 'Select' method on it, in order to convert it to something useful.
问题出在这里
在第一种情况下,我的select语句如下:
In first case, my select statement looks like this:
var result = queryable.Select(entity => /*.. about 20 lines of reshapying code .. */
在第二种情况下,它看起来像这样:
In second case, it looks like this:
var result = queryable.Select(entity.Result => /*.. about 20 lines of exactly the same reshapying code .. */
我想避免重复选择"代码,因为这两种情况都相同.我试图将其移至外部方法,但这未能执行,因为Linq试图将我的方法转换为SQL并显然失败了.
I want to avoid duplication of "select" code, because it identical for both cases. I tried to move it to external method, but this was failing to execute, since Linq was trying to convert my method to SQL and obviously failed.
如何在不重复选择"代码的情况下以一种优雅的方式解决此问题?
How I can resolve this problem in some elegant way, without duplicating 'select' code?
推荐答案
我会使用:
Expression<Func<Result, Foo>> conversion = result => { ... };
第一种情况:
var result = queryable.Select(conversion);
第二种情况:
var result = queryable.Select(entity => entity.Result)
.Select(conversion);
基本上可以同时执行两个投影,因此您的第一个投影(在第二种情况下)会使您陷入已经解决的情况.
Basically use the fact that you can perform two projections together, so that your first projection (in the second case) gets you into a situation you've already tackled.
这篇关于避免在Linq Select方法中重复代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!