我有这段代码。
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内存?
答案 0 :(得分:2)
您可以阅读documentation:
DbSet<TEntity>.Find:
查找具有给定主键值的实体。 如果上下文中存在具有给定主键值的实体,则会立即返回该实体而不向商店发出请求。否则,将向具有给定主要实体的实体发出请求键值和此实体(如果找到)将附加到上下文并返回。如果在上下文或商店中找不到实体,则返回null。
根据这一点,如果在使用Find
方法之前将记录加载到内存中,Find
方法将从缓存中返回记录,否则它将向db发送查询。您也可以使用Sql Profiler
轻松测试。在你调用Find
方法的行上设一个断点,然后看看会发生什么。
答案 1 :(得分:0)
查找首先查看stateManager ... (上下文),如果找不到,则在商店中查找...
用resharper点击2次。与代码一致的文档; - )
public TEntity Find(params object[] keyValues)
{
this.InternalContext.ObjectContext.AsyncMonitor.EnsureNotEntered();
this.InternalContext.DetectChanges(false);
WrappedEntityKey key = new WrappedEntityKey(this.EntitySet, this.EntitySetName, keyValues, "keyValues");
object obj = this.FindInStateManager(key) ?? this.FindInStore(key, "keyValues");
if (obj != null && !(obj is TEntity))
throw Error.DbSet_WrongEntityTypeFound((object) obj.GetType().Name, (object) typeof (TEntity).Name);
else
return (TEntity) obj;
}
/// <summary>
/// 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.
///
/// </summary>
///
/// <remarks>
/// The ordering of composite key values is as defined in the EDM, which is in turn as defined in
/// the designer, by the Code First fluent API, or by the DataMember attribute.
///
/// </remarks>
/// <param name="keyValues">The values of the primary key for the entity to be found. </param>
/// <returns>
/// The entity found, or null.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">Thrown if multiple entities exist in the context with the primary key values given.</exception><exception cref="T:System.InvalidOperationException">Thrown if the type of entity is not part of the data model for this context.</exception><exception cref="T:System.InvalidOperationException">Thrown if the types of the key values do not match the types of the key values for the entity type to be found.</exception><exception cref="T:System.InvalidOperationException">Thrown if the context has been disposed.</exception>
public virtual TEntity Find(params object[] keyValues)
{
return this.GetInternalSetWithCheck("Find").Find(keyValues);
}