gpt4 book ai didi

c# - sql查询中的load和include有什么区别

转载 作者:太空宇宙 更新时间:2023-11-03 15:12:32 25 4
gpt4 key购买 nike

我有一个看起来像这样的查询

         var query = db.Customer
.Include(c => c.Address)
.Where(c => c.Address.Id > 10)
.ToList();

当我这样做的时候

        var query = db.Customer
.Where(c => c.Address.Id > 10)
.ToList();

db.Address
.Where(a => a.Id > 10)
.Load();

据我所知,我得到了相同的结果。

我的问题是:这两个查询返回的内容之间有什么区别,一个比另一个更受欢迎吗?

最佳答案

var query = db.Customer
.Include(c => c.Address)
.Where(c => c.Address.Id > 10)
.ToList();

在上面的查询中,它使用单个数据库行程带来了所有相关数据。

 var query = db.Customer
.Where(c => c.Address.Id > 10)
.ToList();

db.Address
.Where(a => a.Id > 10)
.Load();

这里它使用 2 次数据库访问来获取数据。

Load :

There are several scenarios where you may want to load entities from the database into the context without immediately doing anything with those entities. A good example of this is loading entities for data binding as described in Local Data. One common way to do this is to write a LINQ query and then call ToList on it, only to immediately discard the created list. The Load extension method works just like ToList except that it avoids the creation of the list altogether.

注意:我们不能说哪个更好。大多数时候我们使用预加载方法(Include)。它很好也很简单。但有时它是慢。所以你需要根据你的数据大小等决定使用哪个。

关于c# - sql查询中的load和include有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40463412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com