具有多个 DataLoadOptions 的 Linq2SQl 急切加载
- 作者: 旺旺旺旺_
- 来源: 51数据库
- 2022-12-13
问题描述
我喜欢使用 Linq2SQL 快速加载获取数据.代码类似于:
I like to fetch the data with eager-loading using Linq2SQL. The code is similar as :
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Product>(c => c.ProductCompanies);
options.LoadWith<Product>(c => c.OrderDetails);
db.LoadOptions = options;
IEnumerable<Product> products = db.Products.ToList<Product>();
我检查它生成了超过 1 个 SQL 查询,正如我预期的那样.实际上它只对 Product 和 OrderDetails 进行预先加载,并且对 ProductCompany 进行一一查询.我在这里做错了什么吗?还是 Linq2SQL 的问题?我们有什么解决方法吗?
I check it generated more than 1 SQL query as I expected. Actually it only do eager-loading with Product and OrderDetails, and the ProductCompany is queried one by one. Did I do anything wrong here? Or it is a Linq2SQL issue? Do we have any workaround?
非常感谢!
更新:我从 SQL Profiler 检查 sql.我发现 Leppie 和 Ian 都是正确的.它们被限制在一笔交易中.但是当我把它设置为延迟加载时,它打开了多个连接.
Update: I check the sql from SQL Profiler. I found both Leppie and Ian are correct. They are bounded in one transaction. But when I set it as lazy load, it opened multiple connection.
推荐答案
不,您没有做错任何事,Linq2SQL 在单个事务中批处理所有内容,但可能会为所需结果执行无限数量的查询.DataLoadOptions 通常仅在 DataContext 不可用于结果使用的整个上下文时使用.如果您可以在执行期间保持 DataContext 活动,最好依赖延迟执行(这是默认设置).
No, you didn't do anything wrong, Linq2SQL batches everything in a single transaction, but might execute an unbounded number of queries for the required result. DataLoadOptions is normally only used when the DataContext is not available for the entire context of the resulting usage. If you can keep the DataContext alive during execution, it is best to rely on deferred execution (that is default).
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
