简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM