1

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();
Ashley Kilgour
  • 1,110
  • 2
  • 15
  • 33
  • 1
    Please show your DI startup code (expecially the part that registers your `DBContext`) and indicate what type of application this is (console, WPF, ASP.NET MVC, etc). – NightOwl888 Feb 23 '18 at 21:01
  • You'd better redesign your service according https://stackoverflow.com/questions/10777630/questions-about-entity-framework-context-lifetime – Horosho Feb 27 '18 at 13:59

2 Answers2

10

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;
Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
0
yourContext.Entry(yourEntity).Reload();

from this answer.

yu yang Jian
  • 6,680
  • 7
  • 55
  • 80