“带有语句体的 lambda 表达式不能转换为表达式树" [英] "A lambda expression with a statement body cannot be converted to an expression tree"

查看:42
本文介绍了“带有语句体的 lambda 表达式不能转换为表达式树"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 EntityFramework 时,我在尝试编译以下代码时收到错误带有语句主体的 lambda 表达式无法转换为表达式树":

In using the EntityFramework, I get the error "A lambda expression with a statement body cannot be converted to an expression tree" when trying to compile the following code:

Obj[] myArray = objects.Select(o =>
{
    var someLocalVar = o.someVar;

    return new Obj() { 
    Var1 = someLocalVar,
    Var2 = o.var2 };
}).ToArray();

我不知道错误意味着什么,最重要的是如何修复它.有什么帮助吗?

I don't know what the error means and most of all how to fix it. Any help?

推荐答案

objects 是 Linq-To-SQL 数据库上下文吗?在这种情况下,您只能使用 => 运算符右侧的简单表达式.原因是,这些表达式并没有被执行,而是被转换为 SQL 以对数据库执行.试试这个

Is objects a Linq-To-SQL database context? In which case, you can only use simple expressions to the right of the => operator. The reason is, these expressions are not executed, but are converted to SQL to be executed against the database. Try this

Arr[] myArray = objects.Select(o => new Obj() { 
    Var1 = o.someVar,
    Var2 = o.var2 
}).ToArray();

这篇关于“带有语句体的 lambda 表达式不能转换为表达式树"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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