Database Reference
In-Depth Information
How It Works
This recipe has the cascade delete rule both in the database and in the model. In the model, the rule is represented
both at the conceptual layer and in the store layer. To keep the object context in sync with the database, we defined
the cascade delete in both the database and in the model.
Best Practice
Now you may be asking, “Why do we need this rule in both the model and in the database? Wouldn't it suffice to have
the rule either in the database, or in the model?”
The reason cascade delete exists at the conceptual layer is to keep the objects loaded in the object context in
sync with the cascade delete changes made by the database. For example, if we have classes and enrollments for a
given course loaded in the object context and we mark the course for deletion, Entity Framework would also mark
the course's classes and their enrollments for deletion. All of this happens before anything is sent to the database. At
the model layer, cascade delete means to mark related entities for deletion. Ultimately, Entity Framework will issue
redundant deletes for these entities.
Thus if Entity Framework will issue redundant deletes, why not just have the rules in the model and not in the
database? Here's why: For Entity Framework to mark entities for deletion, they must be loaded into the DbContext.
Imagine that we have a course in the DbContext, but we haven't loaded the related classes or the related enrollments.
If we delete the course, the related classes and enrollments can't be marked for deletion because they are not in the
DbContext. No commands will be sent to the database to delete these related rows. However, if we have the cascade
delete rules in place in the database, the database will take care of deleting the rows.
The best practice here is to have the cascade delete rules both in the model and in the database.
If you have added a cascade delete rule to a model, Entity Framework will not overwrite it if you update the
model from the database. Unfortunately, if you don't have a cascade delete rule in the model and you update the
model from the database while the database has a newly created cascade delete rule, Entity Framework will not add a
cascade delete rule in the conceptual layer. You will have to add it manually.
12-6. Deleting All Related Entities
Problem
You want to delete all of the related entities in the most generic way possible.
Solution
We want to delete all of the related entities in a generic way; that is, in a way that will work across all entities without
specific reference to any particular entity type. To do this, we will create a method that uses the Relationship Manager
to get all of the related ends. With these, we can use CreateSourceQuery() to retrieve the entities and delete them.
The code in Listing 12-6 demonstrates this method using the model in Figure 12-8 . In this model, we have recipes
with related ingredients and steps.
 
Search WWH ::




Custom Search