Database Reference
In-Depth Information
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Donation> Donations { get; set; }
public DbSet<Donor> Donors { get; set; }
}
The following is the output of the code in Listing 8-8:
Jill Rosenberg has given 0 donation(s)
Robert Hewitt has given 1 donation(s)
Original Donor Id: 1
Current Donor Id: 2
How It Works
By default, Entity Framework uses a snapshot-based approach for detecting changes made to POCO entities. If you
make some minor code changes to your POCO entities, Entity Framework can create change-tracking proxies that
keep the DbContext synchronized with the runtime changes in your POCO entities.
There are two important benefits that come with change-tracking proxies. First, the DbContext stays informed
of the changes, and it can keep the entity object graph state information synchronized with your POCO entities.
This means that no time need be spent detecting changes using the snapshot-based approach.
Additionally, when the DbContext is notified of changes on one side of a relationship, it can mirror the change on
the other side of the relationship if necessary. In Listing 8-8, when we moved a Donation from one Donor to another,
Entity Framework also fixed up the Donations collections of both Donors.
For the Entity Framework to create the change-tracking proxies for your POCO classes, the following conditions
must be met.
The class must be public, nonabstract, and nonsealed.
The class must implement virtual getters and setters for all properties that are persisted.
ICollection<T> .
They cannot be a concrete implementation or another interface that derives from ICollection<T> .
Once your POCO classes have met these requirements, Entity Framework will return instances of the proxies
for your POCO classes. If you need to create instances, as we have in Listing 8-8, you will need to use the Create()
method on the DbContext. This method creates the instance of the proxy for your POCO entity, and it initializes all of
the collections as instances of EntityCollection. It is this initialization of your POCO class's collections as instances of
EntityCollection that enables fixing up relationships.
You must declare collection-based relationships navigation properties as
8-6. Retrieving the Original (POCO) Object
Problem
You are using POCO, and you want to retrieve the original object from a database.
Solution
Let's say that you are using a model like the one in Figure 8-7 , and you are working in a disconnected scenario.
You want to use a Where clause with FirstOrDefault() to retrieve the original object from the database before you
apply changes received from a client.
 
 
Search WWH ::




Custom Search