c# 中延迟加载(执行)导致的error

今天在热修生产环境的bug,测试环境没问题。然后根据报错信息,研究了一会,导致走了一些弯路。
我们在使用orm进行数据查询时,经常配合linq中的一些方法使用。尤其Where使用频率极高。

Error Info:

A second operation started on this context before a previous operation completed.
 This is usually caused by different threads using the same instance of DbContext,
 however instance members are not guaranteed to be thread safe. 
 This could also be caused by a nested query being evaluated on the client,
 if this is the case rewrite the query avoiding nested invocations.

常规导致的原因,目前项目都是处理好的。
注意:
只要返回的是IEnumerable对象的都有延迟执行特性
Select、Distinct、SelectMany

具体原因:就是使用where()等延迟加载的方法,默认是延迟执行–>查询的数据未加载到内存中,
所以使用其数据对应的变量,就没法进行任何相关操作.
解决方案:
转换为立即执行 ---->常用的方法:
FirstOrDefault、First、Single、ToDictionary、ToHashSet、ToList

参考的博客:
Linq Error A second operation started on this context before a previous operation completed

How to avoid not-safe context operations in EF Core?

Linq之延迟执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值