【发布时间】:2020-05-06 11:32:05
【问题描述】:
鉴于此示例伪代码:
var student = from s in ctx.Students
where s.StudentName == "Bill"
let code = GetCode(s.Id)
select new
{
Name = s.StudentName,
Code = code.Code
};
private Code GetCode(int id)
{
return ctx.Codes.FirstOrDefault(x => x.Id == id);
}
我收到此错误消息:
"第二个操作在前一个上下文之前开始 操作完成。这通常是由不同的线程使用 DbContext 的相同实例,但实例成员不是 保证是线程安全的。这也可能是由嵌套引起的 在客户端上评估的查询,如果是这种情况,请重写 查询避免嵌套调用。”
但如果我在 let 子句中明确地编写查询,它就可以正常工作:
var student = from s in ctx.Students
where s.StudentName == "Bill"
let ctx.Codes.FirstOrDefault(x => x.Id == s.Id)
select new
{
Name = s.StudentName,
Code = code.Code
};
有没有一种方法可以调用 GetCode 方法而不会出现任何错误?
【问题讨论】:
-
扔掉
GetCode而使用join效率更高。 -
更改方法签名:
Code GetCode(YourContext ctx, int id). -
@Dennis 这是一个示例代码 - 我的查询要复杂得多
-
@AlexanderPetrov 我试过了,我得到了同样的错误
-
@user441365:查询复杂性如何阻止您使用联接?您的第二个示例有效,但会导致子查询。从数据库的角度来看,这是非常低效的。
标签: c# linq asp.net-core