Database Reference
In-Depth Information
{
// Disable Entity Framework Model Compatibility
Database.SetInitializer<Recipe2Context>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// map AccessionNumber as primary key to table
modelBuilder.Entity<Painting>().HasKey(x => x.AccessionNumber);
modelBuilder.Entity<Painting>().ToTable("Chapter13.Painting");
}
public DbSet<Painting> Paintings { get; set; }
Next add an App.Config class to the project, and add to it the code from Listing 13-4, under the
ConnectionStrings section.
Listing 13-4. Connection String
<connectionStrings>
<add name="Recipe2ConnectionString"
connectionString="Data Source=.;
Initial Catalog=EFRecipes;
Integrated Security=True;
MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
In Listing 13-5, we load data and demonstrate both fetching an entity with a LINQ query and then with the
Find() method.
Listing 13-5. Retrieving an Entity with the Find() Method
private static void RunExample()
{
using (var context = new Recipe2Context())
{
context.Paintings.Add(new Painting
{
AccessionNumber = "PN001",
Name = "Sunflowers",
Artist = "Rosemary Golden",
LastSalePrice = 1250M
});
}
using (var context = new Recipe2Context())
{
// LINQ query always fetches entity from database, even if it already exists in context
var paintingFromDatabase =
context.Paintings.FirstOrDefault(x => x.AccessionNumber == "PN001");
 
Search WWH ::




Custom Search