Reputation: 5477
I have the following method in my code;
Invoice GetInvoice()
{
return entities.Invoices.First(i => i.InvoiceNo == invoiceData.InvoiceId);
}
I have read about first level caching but I'm not sure what happens inside EF6 if I do something like this;
Scenario 1: Get the invoice and hold a local reference;
var invoice = GetInvoice();
invoice.UpdatedBy = "Pete"
invoice.UpdatedTime = DateTime.Now;
Scenario 2: Call GetInvoice every time I want to update the invoice;
GetInvoice().UpdatedBy = "Pete"
GetInvoice().UpdatedTime = DateTime.Now;
In the second scenario does the entity framework query the database a second time or does it just return a cached instance of the invoice (checking for cached instances first and only querying the database if it finds none)?
Upvotes: 1
Views: 663
Reputation: 8273
Using
.Single
,.First
,.Where
, etc will not cache the results unless you are using second-level caching.
There will be multiple data calls to the database when you invoke your GetInvoice();
The performance consideration of EF here
if you indent to have caching read more about second-level caching out here
Upvotes: 1
Reputation: 101473
It will both query database second time AND return you a cached instance. When you query your invoice second time, it will execute new query but then discard all results and return you already existing instance, because context already contains mapped entity of the same type with the same primary key. If for example your invoice would be externally modified between first and second call - you won't see that changes, despite that second database call was made.
Upvotes: 1