Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework and Thread safety of ObjectContext

Suppose that we have an ObjectContext (via Entity Framework EDMX) with some entities. Entities fully loaded from DataBase from one single thread. Only after the entities was loaded we start some threads which will only read data from entities and there is no queries to DataBase. Is it thread safe operation?

like image 505
Gattaka Avatar asked Aug 06 '14 15:08

Gattaka


1 Answers

Yes, you may want to also consider using .AsNoTracking() on your ObjectSets to remove any EF hooks from your Context to ensure that you are purely doing read operations as you alluded to. An added bonus to using .AsNoTracking() is that it will also add a very minor performance increase

Here's an example of how to do this within a provider:

    public class Provider<TEntity> where TEntity : class
    {
        protected IObjectSet<TEntity> _dbSet;
        protected ObjectContext _context;

        public Provider(ObjectContext context)
        {
            _context = context;
            _dbSet = context.CreateObjectSet<TEntity>();
        }

        public virtual IEnumerable<TEntity> FindReadOnly(Expression<Func<TEntity, bool>> whereClause= null)
        {
            IQueryable<TEntity> dbSet = _dbSet.AsNoTracking();

            if (whereClause!= null) 
                dbSet = dbSet.AsExpandable().Where(whereClause);

            return dbSet;
        }
    }
like image 193
Jon Gear Avatar answered Oct 29 '22 15:10

Jon Gear