title: Check if entity is loaded using AsNoTracking
body: <p>Is there a way to check if the entity was loaded using <strong>AsNoTracking()</strong> or not?</p>
  
  <p>As you know, the following code will <strong>not</strong> work for entity loaded using <strong>AsNoTracking()</strong>.</p>
  
  <pre><code>ef.Entry(db).Collection(p =&gt; p.tblProducts).Load();
  ef.Entry(db).Collection(p =&gt; p.tblOrders).Load();
  ...
  ...
  ...
  </code></pre>
  
  <p>Therefore, if the entity "<strong>db</strong>" was loaded using <strong>AsNoTracking()</strong> then I will do the following for loading its children.</p>
  
  <pre><code>db.tblProducts = ef.tblProducts.AsNoTracking().Where(x =&gt; x.WarehouseId == db.WarehouseId).ToList();
  db.tblOrders = ef.tblOrders.AsNoTracking().Where(x =&gt; x.WarehouseId == db.WarehouseId).ToList();
  ...
  ...
  ...
  </code></pre>
  
  <p>I know it may not be a good approach, but if entity "<strong>db</strong>" was loaded using <strong>AsNoTracking()</strong>, then I know that its children do not need to be tracked too.</p>
  
  <p>The question is, how to find out if the entity (that passed in the function) was loaded using <strong>AsNoTracking()</strong> or not.</p>
  
  <p><strong>POSSIBLE SOLUTION</strong></p>
  
  <p>I found this post here <a href="https://stackoverflow.com/questions/10027493/entityframework-code-first-check-if-entity-is-attached">EntityFramework Code First - Check if Entity is attached</a>, someone post the answer like this</p>
  
  <pre><code>public bool Exists&lt;T&gt;(T entity) where T : class
  {
      return this.Set&lt;T&gt;().Local.Any(e =&gt; e == entity);
  }
  </code></pre>
  
  <p>So, can I use</p>
  
  <pre><code>if (Exists(db))
  {
      ef.Entry(db).Collection(p =&gt; p.tblProducts).Load();
      ef.Entry(db).Collection(p =&gt; p.tblOrders).Load();
      ...
      ...
      ...
  }
  else
  {
      db.tblProducts = ef.tblProducts.AsNoTracking().Where(x =&gt; x.WarehouseId == db.WarehouseId).ToList();
      db.tblOrders = ef.tblOrders.AsNoTracking().Where(x =&gt; x.WarehouseId == db.WarehouseId).ToList();
      ...
      ...
      ...
  }
  </code></pre>
  
  <p>What do you think?</p>
  
  <p>Thanks!</p>