Entity Framework 6 Recipes 2nd Edition (12-5) Auto-delete associated entities

Source: Internet
Author: User

12-5. Automatically delete associated entities

Problem

When an entity is deleted, you want to automatically delete its associated entities

Solution Solutions

Suppose you have a table structure consisting of a course (subject), course classes (course), as well as enrollment (enroll students in elective classes) as shown in Figure 12-5:.

Figure 12-5. the Course, Class, and enrollment tables in our database

A model is generated from the table above, as shown in Figure 12-6:.

Figure 12-6. A model with the Course, Class, and enrollment entities and their associations

When a course is deleted from the database, you want to delete all relevant classes, and the enrollments associated with these classes are also deleted. To achieve this goal, we set up a cascade delete in the Database manager for this association, in the database manager , select the association and select Cascade Delete under INSERT and update specifications in the Properties window.

When these tables are imported into the model, this cascade delete rule is also imported and you can

Select a one-to-many relationship between course and class and see the cascade delete rule in the Properties window, as shown in Figure 12-7.

Figure 12-7. The Cascade delete rule from the database were imported into the model, and it's shown in the properties for the Assoc Iation

The cascade delete rule as shown in Figure 12-7 is at the conceptual level. There is also a type of rule in the storage layer. When an object is deleted, the EF rule and the Cascade delete rule in the database, both of which are necessary to keep object context and the database in sync.

Listing 12-5 code shows cascading deletions

Listing 12-5. Using the underlying Cascade delete Rules to delete the related Objects

Class Program

{

static void Main (string[] args)

{

Runexample ();

}

static void Runexample ()

{

using (var context = new Efrecipesentities ())

{

var course1 = new Course {coursename = "CS 301"};

var course2 = new Course {coursename = "Math 455"};

var en1 = new Enrollment {Student = "James Folk"};

var en2 = new Enrollment {Student = "Scott Shores"};

var en3 = new Enrollment {Student = "Jill Glass"};

var en4 = new Enrollment {Student = "Robin Rosen"};

var Class1 = new Class {instructor = "Bill Meyers"};

var class2 = new Class {instructor = "Norma Hall"};

Class1. Course = Course1;

Class2. Course = Course2;

Class1. Enrollments.add (EN1);

Class1. Enrollments.add (EN2);

Class2. Enrollments.add (EN3);

Class2. Enrollments.add (EN4);

Context. Classes.add (Class1);

Context. Classes.add (Class2);

Context. SaveChanges ();

Context. Classes.remove (Class1);

Context. SaveChanges ();

}

using (var context = new Efrecipesentities ())

{

foreach (var course in context. Courses)

{

Console.WriteLine ("Course: {0}", Course. Coursename);

foreach (var c in course. Classes)

{

Console.WriteLine ("\tclass: {0}, Instructor: {1}",

C.classid.tostring (), c.instructor);

foreach (Var en in c.enrollments)

{

Console.WriteLine ("\t\tstudent: {0}", en. Student);

}

}

}

}

Console.WriteLine ("Press any key to close ...");

Console.ReadLine ();

}

}

The above listing 12-5 code output results are as follows:

Course:cs 301

Course:math 455

Class:8, Instructor:norma Hall

Student:jill Glass

Student:robin Rosen

Principle

In this section, the database and model both define cascading delete rules. In the model, to ensure that object context synchronizes with the database. This rule also appears in the conceptual and storage tiers.

Best practices

So now you might ask, "Why do we need to define this rule in the database with the model?" cannot be defined only in the model or database? ", the cascade Delete exists in the conceptual layer to keep object context loaded objects are synchronized with the results of the cascade deletion of the database. For example, If we have already loaded the relevant course and student selection information for a subject in object context, and then we mark the subject as deleted, EF will also mark the course and student selection information as deleted. Before committing the deletion to the database, at the model level, Cascading deletes mean that only the associated entity flag is deleted, and eventually EF removes the entity. So since EF removes entities, why not cascade deletions in the model only? The reason is that EF must first load these entities in order to remove the entity flags, DbContext. If our subject has been loaded, but the relevant course is not loaded with the student selection information, we have deleted the subject, then the relevant course and student selection information is not loaded by dbcontext, so EF cannot send the related entity flag as delete, and can not be sent to the database to delete related records of the command. However, if we define cascade deletions in the database, then the database itself will do a good job of cascade deletion.

The best practice here is to define cascading delete rules in both the model and the database.

If you add a cascade delete rule to a model, EF will not overwrite this rule, even if you update the model from the database.

Unfortunately, if you do not add a cascade delete rule to the model and then you update the entity from the database, EF does not add the newly added cascade delete rule to the conceptual layer in the database, and you will have to add it manually.

Attached: Creating a script file for the database used by the sample

Original address: http://www.cnblogs.com/kid1412/p/5161890.html

Entity Framework 6 Recipes 2nd Edition (12-5), automatically delete associated entities

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.