在实体框架查询的选择子句使用函数 [英] Using Function in Select Clause of Entity Framework Query

查看:113
本文介绍了在实体框架查询的选择子句使用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现对实体框架下面的逻辑。

I would like to implement the following logic against Entity Frameworks.

var items = from item in myContext
            select new {
                Value1 = TweakValue(item.Value1),
                Value2 = TweakValue(item.Value2)
            };

protected int TweakValue(int value)
{
    // Custom processing here
    return value;
}

这不会因为调用的工作TweakValue()选择子句。据我所知,查询转换为SQL,而问题是, TweakValue()不能转换为SQL。我的问题是什么,是落实这一最经济的方式。我是否需要第二个循环的值转换?

This won't work because of the call to TweakValue() in the select clause. I understand that the query is converted to SQL, and that the problem is that TweakValue() cannot be converted to SQL. My question is what is the most economical way to implement this. Do I need a second loop to convert the values?

我还在试图获得舒适的使用LINQ表达式。

I'm still trying to get comfortable with LINQ expressions.

推荐答案

最简单的方法可能是只是动的执行到客户端执行转换。在这种情况下,你只需使用:

The simplest way is probably to just "move" the execution to the client to perform the transformation. In this case you'd just use:

var items = myContext.Select(item => new { item.Value1, item.Value2 })
                     .AsEnumerable()
                     .Select(item => new {
                                 Value1 = TweakValue(item.Value1),
                                 Value2 = TweakValue(item.Value2)
                             });

请注意,你不的有无的重用为<$名称C $ C>值1 和值2 - 它只是最容易做到这一点。

Note that you don't have to reuse the names for Value1 and Value2 - it's just easiest to do so.

。如果你真的想使用的查询表达式:

If you really want to use query expressions:

var query = from item in myContext
            select new { item.Value1, item.Value2 };

var items = from item in query.AsEnumerable()
            select new {
                Value1 = TweakValue(item.Value1),
                Value2 = TweakValue(item.Value2)
            };

如果您想先执行过滤,你可以得到的的发生在通过将过滤,排序等调用前AsEnumerable数据库()。例如:

If you want to perform filtering first, you can get that to occur in the database by putting the filtering, ordering etc before the call to AsEnumerable(). For example:

var query = from item in myContext
            where item.Foo == bar
            orderby item.Something
            select new { item.Value1, item.Value2 };

var items = from item in query.AsEnumerable()
            select new {
                Value1 = TweakValue(item.Value1),
                Value2 = TweakValue(item.Value2)
            };

这篇关于在实体框架查询的选择子句使用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆