GetObjectbyKey in E.F. vs. Querying for a single entity

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.

  • If MergeOption is AppendOnly (this is the default) then the newly retrieved entity will disappear into the ether.
  • If it is OverwriteChanges, then the values from the server will replace the current values of the entity in the cache.
  • If it is PreserveChanges, the values from the server will replace the original values of the entity in the cache. The current values won't be touched.
  • MergeOption can also be set to NoTracking. That's an interesting scenario because it will create a second instance of this object. I'm not sure how I feel about that yet. However, if you already have an entity in memory but not in the cache, GetObjectbyKey will have the same effect. It won't find the entity in the cache and will go get one and put it into the cache - result is two instances of the entity.

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.

posted on 2010-09-06 12:39  xqiwei  阅读(299)  评论(0编辑  收藏  举报