Search code examples
c#entity-frameworkdependency-injectionautofac

Entity Framework not always get the most update values from the db


I am having a odd problem with EF caching data, and only getting the values as they were when the DB contect is created.

This is a issue as the DB context is injected on the contractor.

I have set LazyLoadingEnabled to be false.

EF has been set up as database first, this will be something that will be changed so it code first.

I am using autofac for the dependency injection.

I know the following demo is odd, but it is the simplest way to explain it.

So if i call the following code, but if i put a break point on every GetFooById I go into the SQL database and change a value in the foo table, it will not load the new changes it will load the values, as they were before I started.

var item1 = _fooService.GetFooById(1);
var item2 = _fooService.GetFooById(1);
var item2 = _fooService.GetFooById(1);

I was wondering how to make EF always get the most update values from the db. My foo service looks like this

private readonly DBEntities _dbContext;

    public FooService(DBEntities  dbContext)
    {
        _dbContext= dbContext;
    }

    public Foo GetFooById(int id)
    {
        return  _dbContext.Foo.First(x => x.Id== id);
    }

The autofac looks like

builder.RegisterAssemblyTypes(ThisAssembly)
  .Where(t => t.Name.EndsWith("Service"))
  .WithParameter("dbContext", new DBEntities())
  .AsImplementedInterfaces();

Solution

  • You can use the AsNoTracking method disable Entity Framework caching.

    public Foo GetFooById(int id)
    {
        return  _dbContext.Foo.AsNoTracking().First(x => x.Id== id);
    }
    

    See Entity Framework Cache Busting for more information on how to disable cache with Entity Framework

    With Entity Framework Core, you can also change this settings at the context level :

    context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;