Database Reference
In-Depth Information
Figure 8-6. A model for donors and their donations
This model represents donations and donors. Because some donations are anonymous, the relationship between
donor and donation is 0..1 to * .
We want to make changes to our entities, such as moving a donation from one donor to another, and have Entity
Framework and the object state manager notified of these changes. In addition, we want Entity Framework to leverage
this notification to fix up any relationships that are affected by such changes. In our case, if we change the Donor on
a Donation, we want Entity Framework to fix up both sides of the relationship. The code in Listing 8-8 demonstrates
how to do this.
The key part of Listing 8-8 is that we marked each property as virtual and each collection a type of
ICollection<T> . This allows Entity Framework to create proxies for our POCO entities that enable change tracking.
When creating instances of POCO entity types, Entity Framework often creates instances of a dynamically generated
derived type that acts as a proxy for the entity. This proxy overrides some virtual properties of the entity that inserts
hooks for performing actions automatically when the property is accessed. This mechanism is used to support lazy
loading of relationships and change tracking of objects. Note that Entity Framework will not create proxies for types
where there is nothing for the proxy to do. This means that you can also avoid proxies by having types that are sealed
and/or have no virtual properties.
Listing 8-8. By Marking Each Property as virtual and Each Collection a Type of ICollection<T> , We Get Proxies
That Enable Change Tracking
class Program
{
static void Main(string[] args)
{
RunExample();
}
static void RunExample()
{
using (var context = new EFRecipesEntities())
{
var donation = context.Donations.Create();
donation.Amount = 5000M;
var donor1 = context.Donors.Create();
donor1.Name = "Jill Rosenberg";
var donor2 = context.Donors.Create();
donor2.Name = "Robert Hewitt";
 
Search WWH ::




Custom Search