c# – ToList和Find实现

我有这个代码.

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方法的行上放一个断点然后看看会发生什么.

点赞