2

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();
2
  • 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). Commented Feb 23, 2018 at 21:01
  • You'd better redesign your service according stackoverflow.com/questions/10777630/… Commented Feb 27, 2018 at 13:59

2 Answers 2

11

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;
Sign up to request clarification or add additional context in comments.

Comments

0
yourContext.Entry(yourEntity).Reload();

from this answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.