Entity Framework, Load multiple entities by primary key in a single query while still using caching

.net c# entity-framework entity-framework-6

Question

I have a list of primary key ids for a table whose entities I want to pull into EF memory, modify, and then save.

With a single id you would do something like

var entity = dbContext.Entity.Find(id);

entity.SomeColumn = "something";

dbContext.SaveChanges()

Currently I'm doing something like this to pull all the entities to be modified in one RTT.

int[] ids = new int[] { 1, 2, 3, 4 };

Entity[] entities = dbContext.Entity
  .Where(c => ids.Contains(c.PrimaryKey))
  .ToArray();

Question being, is EF smart enough to know to check caching before going against my db? For instance, if entities 1-4 had already been attached to the context, there should be no db query made.

1
1
4/15/2016 12:06:58 AM

Accepted Answer

Not implicitly.

Where() will always query the database. To explicit query the cache you need to use .Local:

dbContext.Entity.Local.Where(...

This will not hit the database but it will only return entities that have been cached/loaded before.

Good to know: to view the queries define a Log function like this:

dbContext.Database.Log = Console.WriteLine;

3
4/15/2016 2:48:49 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow