






















Even though I seem to have gotten it right when I wrote about this in my book (I just checked) in my own memory I have had a misconception about GetObjectbyKey.
I thought that GetObjectbyKey and TryGetObjectbyKey only searches the cache for entities that already have been created. But I realized this morning that if it doesn't find the entity in the cache, it will create a query and go look in the database also.
dim myEntity=context.GetObjectbyKey(myKey)or use one of the methods for creating an EntityKey on the fly.
Dim cust=context.GetObjectbyKey(new EntityKey("NorthWindEntities.Customers","CustomerID",3)
You can easily make this a generic method if you needed to.
Compare this to a query
Dim cust= (From c in context.Customers Where c.CustomerID=3).FirstorDefault
or
Dim cust=context.Customers.Where(Function(c) c.CustomerID=3).FirstorDefault
Using GetObjectbyKey vs. a query is not just about coding because they work very differently.
When you execute a query, EF will always go to the database first and retrieve whatever it finds. As it's loading the results into the cache, if the entity already exists in the cache, it will refresh that entity based on the MergeOptions.
So depending on your needs, GetObjectbyKEy (and TryGetOBjectbyKey) is very efficient because it won't go to the database unless it has to, however it won't refresh your data from the server as a query would.
Good to know so I can make the right choice when the time comes.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。