Cache Results are inconvenient in some cases

Aug 23, 2014 at 12:07 AM
In some cases it is necessary to see a change made directly in the database or by other program and is not reflected in the Repository queries. Apparently EF manages a cache when you make a query. How could we force EF to go again to the table and read the fresh data again?

Thank you.
Sep 12, 2014 at 11:16 PM
You can easily add a method to IUnitOfWork, UnitOfWork to call Refresh on the DataContext.
Marked as answer by lelong37 on 9/12/2014 at 3:16 PM
Sep 17, 2014 at 8:45 PM
I finally solve:

Add two net methods to IRepository and Repository:

        void Refresh(TEntity entity);
        void Refresh(IEnumerable<TEntity> entities);
        public virtual void Refresh(TEntity entity)
            ObjectContext objectContext = ((IObjectContextAdapter)_context).ObjectContext;
            objectContext.Refresh(RefreshMode.StoreWins, entity);

        public virtual void Refresh(IEnumerable<TEntity> entities)
            ObjectContext objectContext = ((IObjectContextAdapter)_context).ObjectContext;
            objectContext.Refresh(RefreshMode.StoreWins, entities);
Code example:
        public Account GetAccountByAgentIdAndType(long agentId, int type)
            var accounts = _myRepository.Repository<Account>()
                .Query(q => q.AgentId == agentId && q.Type == type)

            _myRepository.Repository<Account>().Refresh(accounts); // Refresh cache level 1 for entity Account

            return accounts.FirstOrDefault();