问题描述
我喜欢使用 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).
这篇关于具有多个 DataLoadOptions 的 Linq2SQl 急切加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!