Database Reference
In-Depth Information
7-7. Working with Dependent Entities in an Identifying
Relationship
Problem
You want to insert, update, and delete a dependent entity in an identifying relationship.
Solution
Suppose that you have a model like the one shown in Figure 7-8 . The LineItem's entity key is a composite key
comprised of InvoiceNumber and ItemNumber. InvoiceNumber is also a foreign key to the Invoice entity.
Figure 7-8. Invoice and LineItem in an identifying relationship because of the composite entity key in the LineItem entity
When one of the properties of an entity key is both the primary key and the foreign key, the entity is said to be
participating in an identifying relationship . In our model, LineItem's entity key, its identity, is also a foreign key to the
Invoice entity. The LineItem entity is referred to as the dependent entity , while Invoice is the principal entity .
There is a subtle difference in how Entity Framework handles the deletion of dependent entities in an identifying
relationship. Because the dependent entity cannot exist without participating in the relationship, simply removing
the dependent entity from the principal's collection will result in Entity Framework marking the dependent entity for
deletion. Additionally, deleting the principal entity will also mark the dependent for deletion. This is reminiscent of
the cascading deletes common in database systems. Of course, Entity Framework allows you to delete the dependent
entity explicitly. The code in Listing 7-5 demonstrates all three of these scenarios.
Listing 7-5. Deleting the Dependent Entity
static void Main(string[] args)
{
RunExample();
}
static void RunExample()
{
using (var context = new EF6RecipesContext())
{
var invoice1 = new Invoice { BilledTo = "Julie Kerns",
InvoiceDate = DateTime.Parse("9/19/2013") };
 
Search WWH ::




Custom Search