Database Reference
In-Depth Information
The next line of code re-queries the database for the exact same Star City Club. Note that, even though this entity
object already exists in the context, the default behavior of the DbContext is to re-query the database for the record. In
profiler, we see the exact same SQL query generated. What's more, since the Star City entity is already loaded in the context,
the DbContext does not overwrite the current values with updated values from the database, as shown in Figure 5-6 .
Figure 5-6. SQL query returning the Star City Club
In the next line of code we once again search for the Star City Club. This time, however, we leverage the Find()
method that is exposed by the DbSet Class. Since the Club entity is a DbSet class, we simply call the Find() method on
it and pass in the primary key of the entity as an argument to Find() , which in this case is the value of 80.
Find() first searches the context object in memory for Star City, finds the object, and returns a reference to it. The
key point is that Find() only queries the database if it cannot find the requested object in the context object. Note in
Figure 5-7 how a SQL query was not generated.
Figure 5-7. The Find() method locates the object in the context, and it never generates a query to the database
Next we again use the Find() method to retrieve the entity for the Desert Sun Club. This Find() does not locate
the target entity in the context object, and it next queries the underlying data store to return the information. Note in
Figure 5-8 the SQL query that is generated to retrieve the data.
Figure 5-8. SQL query generated to return the Desert Sun Club
In the next query, we retrieve entity information for the Palm Tree Club, but pay particular attention to the LINQ
query. Note the AsNoTracking() clause that has been appended to Clubs. The NoTracking option disables object state
tracking for the specific entity. With NoTracking , Entity Framework will not track changes to the Palm Tree object, nor
will it load it into the underlying context object.
When we issue a subsequent request to obtain the Palm Tree club entity object, Find() generates a SQL query
to retrieve the entity from the data store, as shown in Figure 5-9 . The round trip to the database is necessary as we
instructed Entity Framework not to track the object in the context object with the AsNoTracking() clause. Keep in
mind that Find() requires the entity object to be tracked in the context in order to avoid a call to the database.
 
Search WWH ::




Custom Search