实体框架和嵌套 Lambda 表达式
我刚刚开始使用 Lambda 表达式,并且非常喜欢这种快捷方式。我还喜欢这样一个事实:我在包含方法的 lambda 内具有范围。我遇到麻烦的一件事是嵌套 lambda。这是我想要做的:
public void DoSomeWork()
{
MyContext context = new MyDomainContext();
context.GetDocumentTypeCount(ci.CustomerId, io =>
{
if (io.HasError)
{
// Handle error
}
// Do some work here
// ...
// make DB call to get data
EntityQuery<AppliedGlobalFilter> query =
from a in context.GetAppliedGlobalFiltersQuery()
where a.CustomerId == ci.CustomerId && a.FilterId == 1
select a;
context.Load<AppliedGlobalFilter>(query, lo =>
{
if (lo.HasError)
{
}
**// Do more work in this nested lambda.
// Get compile time error here**
}
}, null);
}, null);
}
第二个 lambda 是我收到以下编译时错误的地方:
无法将 Lambda 表达式转换为类型“System.ServiceModel.DomainService.Client.LoadBehavior”,因为它不是委托类型
编译器正在选择即使我使用与上一个 Lambda 中相同的覆盖,Load 方法的重载也是错误的。
这是因为我想筑巢吗?或者我还有什么问题吗?
谢谢,
-斯科特
I've just started using Lambda expressions, and really like the shortcut. I also like the fact that I have scope within the lambda of the encompassing method. One thing I am having trouble with is nesting lambdas. Here is what I am trying to do:
public void DoSomeWork()
{
MyContext context = new MyDomainContext();
context.GetDocumentTypeCount(ci.CustomerId, io =>
{
if (io.HasError)
{
// Handle error
}
// Do some work here
// ...
// make DB call to get data
EntityQuery<AppliedGlobalFilter> query =
from a in context.GetAppliedGlobalFiltersQuery()
where a.CustomerId == ci.CustomerId && a.FilterId == 1
select a;
context.Load<AppliedGlobalFilter>(query, lo =>
{
if (lo.HasError)
{
}
**// Do more work in this nested lambda.
// Get compile time error here**
}
}, null);
}, null);
}
The second lambda is where I get the following compile time error:
Cannot convert Lambda expression to type 'System.ServiceModel.DomainService.Client.LoadBehavior' because it is not a delegate type
The compiler is choosing the wrong overload for the Load method even though I am using the same override I did in the previous Lambda.
Is this because I am trying to nest? Or do I have something else wrong?
Thanks,
-Scott
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
发现了我上面评论中描述的问题。我现在就回去工作了——脸红了……
Found the problem as described in my comment above. I'll head back to work now - red face and all....
我意识到这不是您想要的答案,但我建议谨慎对待冗长和/或嵌套的 lambda。它们有效,但通常会使代码更难被其他开发人员阅读/维护。我尝试将 lambda 的长度限制为三个语句,并且没有嵌套。
I realize this is not the answer you want, but I suggest caution about lengthy and/or nested lambdas. They work, but they often make code harder to read / maintain by other developers. I try to limit my lambdas in length to three statements, with no nesting.