c# - ToList 和 Find 实现

标签 c# entity-framework

我有这个代码。

var menucategories = db.Menus.Where(m => m.Language.lang_code == lang && m.published == 1).OrderBy(m => m.ordering).ToList();

使用这里的代码,我想获取所有可用的菜单类型并导入到 DBContext 内存中。

db.MenuTypes.ToList();

foreach (var item in menucategories)
{
    if (item.published == 1)
    {
        //Search into the DBContext memory for the MenuTypes
        var view = db.MenuTypes.Find(item.menu_type_fk_id);
         ....

在这个 foreach 循环中,我使用了 db.MenuTypes.Find(item.menu_type_fk_id) 语句。我的问题是,这个 Find 方法是往返数据库还是搜索 DBContext 内存?

最佳答案

您可以阅读 documentation :

DbSet<TEntity>.Find: Finds an entity with the given primary key values. If an entity with the given primary key values exists in the context, then it is returned immediately without making a request to the store. Otherwise, a request is made to the store for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found in the context or the store, then null is returned.

根据这个如果你在使用Find之前将记录加载到内存中方法,Find方法将从缓存中返回记录,否则它将向 db 发送查询。您还可以使用 Sql Profiler 轻松测试它.在你调用 Find 的行上放置一个断点方法然后看看会发生什么。

关于c# - ToList 和 Find 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25486376/

相关文章:

c# - 如果花费的时间太长,则取消执行命令

c# - 使用 WinNT 连接到远程计算机 ://provider and Directory Services Ignores username/password

c# - 使用 C# 的 LINQ tolookup

entity-framework - 如何在 Entity Framework 中维护有序列表?

c# - EF6 : Configure complex mapping for entities (code first)

c# - 原始查询更改未出现在实体对象 c# 中

.net - 我可以将实体的可选引用投影到投影结果类型的可选引用中吗?

c# - 支持使用 Entity Framework 6 进行 SQL Server 更改跟踪

c# - WPF 应用程序中的事件冒泡

c# - 仅在需要时将对象包装到任务<object>中