Gattaka
Gattaka

Reputation: 147

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?

Upvotes: 5

Views: 815

Answers (1)

Jon Gear
Jon Gear

Reputation: 1018

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;
        }
    }

Upvotes: 5

Related Questions