Database Reference
In-Depth Information
Figure 13-7. A model with an Account entity and a related Payment
To start, this example leverages the Code-First approach for Entity Framework. In Listing 13-16, we create
two entity classes: Account and Payment. To achieve the best change-tracking performance, we need to allow
Entity Framework to wrap our entity classes automatically with change-tracking proxy classes, which immediately
notify the underlying change-tracking mechanism any time that the value of a property changes. With proxies,
Entity Framework knows the state your entities at all times. When creating the proxy, notification events are added
to the setter method of each property, which are processed by the Object State Manager. Entity Framework will
automatically create a proxy class when two requirements are met: (1) all properties in an entity must be marked
as virtual , and (2) any navigation property referencing a collection must be of type ICollection<T> . Meeting these
requirements allows Entity Framework to override the class and add the necessary change-tracking plumbing.
Both of our Account and Payment entity classes meet these requirements, as seen in Listing 13-16.
Listing 13-16. Our Entity Classes with Properties Marked as virtual and the Navigation Properties Are of Type
ICollection<T>
public class Account
{
public virtual int AccountId { get; set; }
public virtual string Name { get; set; }
public virtual decimal Balance { get; set; }
public virtual ICollection<Payment> Payments { get; set; }
}
public class Payment
{
public virtual int PaymentId { get; set; }
public virtual string PaidTo { get; set; }
public virtual decimal Paid { get; set; }
public virtual int AccountId { get; set; }
}
Next, in Listing 13-17, we create the DbContext object, which is our gateway into Entity Framework functionality
when leveraging the Code-First approach.
Search WWH ::




Custom Search