Database Reference
In-Depth Information
5-3. Finding Single Entities Quickly
Problem
You want to load a single entity, but you do not want to make another trip to the database if the entity is already loaded in
the context. Additionally, you want to implement the Code-First approach for Entity Framework 6 to manage data access.
Solution
Let's say that you have a model like the one shown in Figure 5-4 .
Figure 5-4. A simple model that represents Club entity objects
In this model, we have a Club entity that we can query to obtain information about various clubs.
Start by adding a console application project to Visual Studio entitled Recipe3 . Be certain to reference the Entity
Framework 6 libraries. Leveraging the NuGet Package Manager does this best. Right-click on Reference, and select
Manage NuGet Packages. From the Online tab, locate and install the Entity Framework 6 package. Doing so will
download, install, and configure the Entity Framework 6 libraries in your project.
To create the club entity, create a class entitled Club and copy the properties into it from Listing 5-4.
Listing 5-4. Club Entity Class
public class Club
{
public int ClubId { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
Next create a class entitled Recipe3Context and add the code from Listing 5-5 to it, ensuring the class derives
from the Entity Framework DbContext class.
Listing 5-5. Context Class
public class Recipe3Context : DbContext
{
public Recipe3Context()
: base("Recipe3ConnectionString")
 
Search WWH ::




Custom Search