0

I have base controller which calls database table and get data through ado.net entity framework. When I call every controller base controller is called. When ever base controller is called it data from sql db and pulls my table information.

I read that entity framework caches data. so in this case will it hit db every time for each controller call or it hit once and cache the data?

    public class BaseController : Controller
    {

    MyEntities db= new MyEntities(); 
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
      {
             var details = db.mytables.tolist();
      }
    }

All my controllers inherit base controller

public class MyController : BaseController
{
    //my code
}
Kurkula
  • 6,386
  • 27
  • 127
  • 202
  • 1
    Where did you read that EF caches? It can make the call to SQL in a way that SQL caches but EF does not cache. – Alex Krupka Mar 16 '17 at 18:37
  • EF does track entities but not in asp.net as you create a new context with every request. Furthermore you do not want to reuse an EF context between requests, that is dangerous. – Igor Mar 16 '17 at 18:37
  • You'll need to implement your own caching. – Grant H. Mar 16 '17 at 18:37
  • 1
    EF doesn't cache data, it does track entities but not between instances of your context. – DavidG Mar 16 '17 at 18:37
  • It takes a single Google query to find the claim you mention: [_"EF will only check the cache when you use the .Find method on DbSet [\on the same DbContext instance\\]"_](http://stackoverflow.com/questions/21707970/why-does-entity-framework-6-x-not-cache-results). You're calling `.ToList()` on a new instance every time, so the premise is false to begin with. – CodeCaster Mar 16 '17 at 18:39

1 Answers1

1

"I read that entity framework caches data"

I highly doubt it. If the entry was modified how does entity framework know without asking the database?

The bank would be super upset if you made multiple withdraws when you only have enough for one withdraw, but they got thru because the cache says you have enough.

Here is an easy way to test it without any 3rd party tool.

Run the application once so it got pass the line

var details = db.mytables.tolist();

then put a break point on the line and turn off database service

Now let the execution continue, it should throw sql connection fail exception since its trying to connect to the DB

Steve
  • 11,696
  • 7
  • 43
  • 81
  • [`Find()` utilizes caching](http://stackoverflow.com/questions/17042697/does-ef-caches-entities-between-different-instances-of-dbcontext). – CodeCaster Mar 16 '17 at 18:43
  • @CodeCaster if I read it correctly it doe not cache the data, only caches the instance – Steve Mar 16 '17 at 18:48
  • It will cache instances of entities by their table's primary key, i.e. caching. To say that EF does not cache at all because that would make a bank upset is an oversimplification. – CodeCaster Mar 16 '17 at 18:59