Database Reference
In-Depth Information
// Find() method fetches entity from context object
var paintingFromContext = context.Paintings.Find("PN001");
}
Console.WriteLine("Press <enter> to continue...");
Console.ReadLine();
}
How It Works
When issuing a LINQ query, a round trip will always be made to the database to retrieve the requested data, even if
that data has already been loaded into the context object in memory. When the query completes, entity objects that
do not exist in the context are added and then tracked. By default, if the entity object is already present in the context,
it is not overwritten with the more recent database values.
However, the DbSet object, which wraps each of our entity objects, exposes a Find() method. Specifically, Find()
expects a single argument that represents the primary key of the entity object. If necessary, an array of values can be
passed into Find() to support a composite key. Find() is very efficient, as it will first search the underlying context for
the target object. If found, Find() returns the entity directly from the context object. If not found, then it automatically
queries the underlying data store. If still not found, Find() simply returns NULL to the caller. Additionally, Find()
will return entities that have been added to the context (think of having a state of “Added”), but not yet saved to the
underlying database. Fortunately, the Find() method is available with any of three modeling approaches: Database-
First, Model-First, or Code-First.
In Listing 13-5, we invoke a LINQ query to retrieve a Painting. A LINQ query will always query the underlying
database, even if the entity is already loaded into the context. Figure 13-3 shows the SQL query that is generated.
Figure 13-3. SQL Query returning our painting
In the next line of code, we once again search for the same painting. This time, however, we leverage the Find()
method exposed by the DbSet Class. Since the Painting 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. Find() first searches the context object in memory for
“PN001,” finds the object, and returns a reference to it, avoiding a round trip to the database. Note in Figure 13-4 how
a SQL Query was not generated.
 
Search WWH ::




Custom Search