我有这个代码。
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/