In this Tip I want to describe about differences between
First() method and
TryGetObjectByKey() in projects that use EF and linq. and Why we shouldn't use
How .First() Method Works?
Easiest way to retrieve a single element is to call
First() Method in Your LINQ Query, each time it goes to database and read the data from that.
What could happen else? isn't this way?
answer is no! because you are using a big technologies name entity Framework!
the EF have a thing name
if you want to know what is state manger you have to go deep inside this technology but here I call this A thing that make the world a better place to live!
Every time you call the
first() method its doesn't have any work with that thing!
and here is My lovely method:
How TryGetObjectByKey() Method Works?
this Method do the same, it means it search for an element by its key but! wait! yes there is a difference! this method goes to state manger before going to database!
TryGetObjectByKey() ask state manager: " is an entity of that type with the given key exists in memory? " . if state manager says " yes!! " the query returns in-memory entity without going to database! and if the answer is "no!" it queries the database and put it in state manager.
Code in C#:
var c = (customer)ctx.TryGetObjectByKey(new EntityKey("myentity.customer" , "Customer_ID" , "ALFKI"));
var c2 = (customer)ctx.TryGetObjectByKey(new EntityKey("myentity.customer" , "Customer_ID" , "ALFKI"));
code in VB:
Dim c = DirectCast(ctx.TryGetObjectByKey(new EntityKey("myentity.customer" , "Customer_ID" , "ALFKI")),Customer );
Dim c2 = DirectCast(ctx.TryGetObjectByKey(new EntityKey("myentity.customer" , "Customer_ID" ,"ALFKI")),Customer );
This Method has 3parameter: first is the entity name, second is the key column and the third is its key value!
first query for
c go to database, but for
c2 use in-memory entity!
But What happen if the data modifed at the same time when query use in-memory entity?
EF have a mechanism call " change Tracker ". but as i say if you want to know more about EF you have to read books and go deep inside it!
Taha has started programming at the age of 16 and he has taken an avid interest in Microsoft technologies. He professionally works on ASP.NET and C#. Mainly, He lives for getting the world into codes and follows this aspiration in a third world country with lack of facility and support. He never gives up seeking success and competence.