Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DBContext DBSet query and the no tracking option

Based on other posts such as Entity Framework and DbContext - Object Tracking it would appear the simplified DBContext interface doesnt expose the to set No tracking on basic queries. A little blog showing how with Object context http://blogs.microsoft.co.il/blogs/gilf/archive/2009/02/20/disabling-change-tracking-in-entity-framework.aspx

What is a good approach to loading results via the DbContext as not tracked? How are the performance conscious doing this if using Dbcontext ? ie have base GetList method I would like to improve for performance reasons.

public DbSet<T> EntityDbSet { get { return _context.Set<T>(); } }
public virtual IQueryable<T> GetList(Expression<Func<T, bool>> predicate)
    {
         return EntityDbSet.Where(predicate);
    }
like image 690
phil soady Avatar asked Oct 16 '12 17:10

phil soady


People also ask

Is DbSet part of DbContext?

The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views. Adds the given entity to the context with the Added state.

How do you get entities back from a query without getting tracked by the context?

No-Tracking query using AsNoTracking() extention method The AsNoTracking() extension method returns a new query and returned entities do not track by the context. It means that EF does not perform any additional task to store the retrieve entities for tracking.

What is the difference between DbSet and DbContext?

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.

What is as no tracking in EF?

No tracking queries are useful when the results are used in a read-only scenario. They're quicker to execute because there's no need to set up the change tracking information. If you don't need to update the entities retrieved from the database, then a no-tracking query should be used.


1 Answers

The AsNoTracking is an extension on IQueryable.

You can update your function above with:

public virtual IQueryable<T> GetList(Expression<Func<T, bool>> predicate)
    {
         return EntityDbSet.Where(predicate).AsNoTracking();
    }
like image 180
Mark Oreta Avatar answered Nov 15 '22 07:11

Mark Oreta