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.
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;