Entity Framework and ObjectContext Thread Safety

Suppose we have an ObjectContext object (via the Entity Framework EDMX) with some objects. Objects fully loaded from the database from a single stream. Only after the objects have been loaded, we start some threads that will read data only from the objects, and there are no queries to the DataBase. Is this thread safe work?

+4
source share
1 answer

Yes, you can also consider using .AsNoTracking () on your object sets to remove any EF hooks from your Context to ensure that you are performing read operations as you mentioned. An added bonus to using .AsNoTracking () is that it will also add a very slight performance boost.

Here is 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;
        }
    }
+4
source

All Articles