Database Reference
In-Depth Information
{
// Disable Entity Framework Model Compatibility
Database.SetInitializer<Recipe3Context>(null);
}
public DbSet<Club> Clubs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Club>().ToTable("Chapter5.Club");
}
}
Next add an App.Config class to the project, and add the code from Listing 5-6 to it under the ConnectionStrings
section.
Listing 5-6. Connection String
<connectionStrings>
<add name="Recipe3ConnectionString"
connectionString="Data Source=.;
Initial Catalog=EFRecipes;
Integrated Security=True;
MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
If we are searching for an entity by a key value, a common operation, we can leverage the Find() method first
to search the in-memory context object for a requested entity before attempting to fetch it from the database. Keep
in mind that the default behavior of Entity Framework is to query the database each time you issue an operation to
retrieve data, even if that data has already been loaded into memory in the context object.
The Find() method is a member of the DbSet class, which we use to register each entity class in the underlying
DbContext object. The pattern is demonstrated in Listing 5-7.
Listing 5-7. Leveraging the Find() Method in Entity Framework to Avoid Fetching Data That Has Already Been
Loaded into the Context
using (var context = new Recipe3Context())
{
var starCity = new Club {Name = "Star City Chess Club", City = "New York"};
var desertSun = new Club {Name = "Desert Sun Chess Club", City = "Phoenix"};
var palmTree = new Club {Name = "Palm Tree Chess Club", City = "San Diego"};
context.Clubs.Add(starCity);
context.Clubs.Add(desertSun);
context.Clubs.Add(palmTree);
context.SaveChanges();
// SaveChanges() returns newly created Id value for each club
starCityId = starCity.ClubId;
desertSunId = desertSun.ClubId;
palmTreeId = palmTree.ClubId;
}
 
Search WWH ::




Custom Search