8

I've encountered what seems to be a common problem: I am updating values in my database, but EF is using its original in-memory copy of the object and these changed values are not reflected in the displayed data. I understand why this is, but I can't figure out a way around it.

The most common solution seems to be to set MergeOptions.NoTracking to turn off change tracking completely (or use the AsNoTracking() extension method when querying) and force a refresh every time the object is accessed, which is fine for my purposes.

I've got a generic base repository which my other repositories inherit from:

public abstract class RepositoryBase<T> where T : class
{
    private readonly IDbSet<T> _dbset;
    private readonly IUnitOfWork _unitOfWork;

    protected RepositoryBase(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
        _dbset = _unitOfWork.Database.Set<T>();
    }

    public virtual IQueryable<T> All()
    {
        return _dbset;
    }

    // Some other IQueryable methods here (Query, GetByProductCode etc)

    public virtual T Get(long id)
    {
        return _dbset.Find(id);
    }
}    

And a DbContext like this:

public class Db : DbContext
{
    private IDbSet<Product> _products;

    public IDbSet<Product> Products
    {
        get { return _products ?? (_products = DbSet<Product>()); }
    }

    public virtual IDbSet<T> DbSet<T>() where T : class
    {
        return Set<T>();
    }

    public virtual void Commit()
    {
        base.SaveChanges();
    }
}

If I change the All() method of my repository thus:

public virtual IQueryable<T> All()
{
    return _dbset.AsNoTracking();
}

I get the desired result - an update in the database is reflected when the page displaying the products is refreshed. However, I can't do this in the Get() method, as that extension method only works on an IQueryable.

Ideally I'd like to turn this off at the DbContext level as I will never need change tracking, but there doesn't seem to be an obvious way to do this, and there is pretty much zero documentation on the subject (unless someone can point me to some? Please!).

I tried adding a constructor to the DbContext with these configuration options disabled:

public Db()
{
    base.Configuration.ProxyCreationEnabled = false;
    base.Configuration.AutoDetectChangesEnabled = false;
}

But I must admit I'm only guessing as to what they really do (I only found them through looking at the source code), and they don't seem to have any effect anyway.

Any help would be greatly appreciated. If more info/code would help, please let me know.

Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
Mark Bell
  • 27,184
  • 22
  • 109
  • 138

1 Answers1

6

If you want to force context to get fresh data each time you don't want to use Find method. Find method always query internal storage first. Use this instead:

public virtual T Get(long id)
{
    return All().SingleOrDefault(e => e.Id == id);
}

But I don't understand what do you need this? What do you mean by:

an update in the database is reflected when the page displaying the products is refreshed

Context is unit of work. It should be used as unit of work - in web application or web service it means creating new context instance per request. In winforms / wpf application it means using context per logical block (per presenter etc). Because of that you should need this only in very specific scenarios but you want it globally. Your description seems like you are reusing context among requests which is completely bad solution. There are no performance costs in recreating context for each request.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
  • Thanks for the answer. I thought I *was* creating a new context per request, but because of what you've pointed out here, I suspect I might have something set up wrong in my Ninject configuration... I'll check it tomorrow and report back! – Mark Bell Mar 31 '11 at 20:20
  • It seems this is the problem. I am not creating a new DbContext per request—or rather, Ninject isn't, even though I have specified `InRequestScope()` in the injection. I think that is now a separate question, but thanks for your help getting this far. – Mark Bell Apr 01 '11 at 09:17
  • I've accepted this answer even though it doesn't *directly* answer the question, because it did lead me to a solution. – Mark Bell Apr 01 '11 at 09:38
  • 1
    @Mark Bell I think I might be having a similar issue. What was the solution you found for this? – user441365 Nov 02 '12 at 10:18
  • @MarkBell What was the solution you found? I'm stuck with the same issue – TankorSmash Jan 17 '13 at 20:48
  • In my case it was a bug of my own making; I wasn't returning a new `DbContext` instance per request from a factory class further down the app stack. It was very specific to my code, which is why I didn't post it here. Basically, you just need to check that whatever is giving you your `DbContext` instances isn't holding on to those instances between requests, – Mark Bell Jan 18 '13 at 06:52