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.
Coordinator
Sep 12, 2014 at 11:16 PM
You can easily add a method to IUnitOfWork, UnitOfWork to call Refresh on the DataContext.

http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.refresh(v=vs.110).aspx
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:

IRepository.cs
        void Refresh(TEntity entity);
        void Refresh(IEnumerable<TEntity> entities);
Repository.cs
        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)
                .Select();

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

            return accounts.FirstOrDefault();
        }