5

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?

Gattaka
  • 147
  • 1
  • 9
  • If you ensure it is all pre-loaded and you really are *only* doing reads of the entities... sure. – Luaan Aug 06 '14 at 15:27

1 Answers1

5

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;
        }
    }
Jon Gear
  • 1,008
  • 1
  • 11
  • 22