Entity Framework 6 Recipes 2nd Edition (12-1), entityrecipes

Source: Internet
Author: User

Entity Framework 6 Recipes 2nd Edition (12-1), entityrecipes

The12ChapterCustomizationEF

In this section, you can customize entity objects and some features of EF processing. these sections cover a lot of "behind-the-scenes" things, allowing your code to solve things in a more unified manner. For example, you can use a business rule center to perform verification for entities in a unified manner.

This section describes how to execute your own code when SaveChanges () is called in your application. this section is useful for customizing business rules in your applications.

In other sections, we will demonstrate how to track database connections, how to automatically report changes to collections, how to implement cascading deletion, how to set default values, and how to use them with strong XML attributes. all these customizations share the same thing: the extended object and EF processing process make your code more flexible, unified, and maintainability.

12-1. Run your code when SaveChanges () is called

Problem

You want to execute your code when SaveChanges () is called in data context.

Solution

Suppose you have a model about the applicant (as shown in Figure 12-1 ). the Applicant document is part of the model and you want to delete the document together When Applicant is deleted. you may find that you need to delete the document in every location where your application deletes Applicant, and you want to process it in a unified way.

Listing 12-1.Overriding SaveChanges () to Delete the Resume File When the Applicant Is Deleted

To ensure that the document is deleted along with applicant, we need to first browse the entities in DbContext to find the Applicant to be deleted in the override SavingChanges () method of DbContext, then call the real SaveChanges () method. finally, delete the file for each deleted Applicant. The code is shown in Listing 12-1:

Listing 12-1.Overriding SaveChanges () to Delete the Resume File When the Applicant Is Deleted

Class Program

{

Static void Main (string [] args)

{

Using (var context = new EFRecipesEntities ())

{

Var path1 = "AlexJones.txt ";

File. AppendAllText (path1, "Alex Jones \ nResume \ n ...");

Var path2 = "JanisRogers.txt ";

File. AppendAllText (path2, "Janis Rodgers \ nResume \ n ...");

Var app1 = new Applicant

{

Name = "Alex Jones ",

ResumePath = path1

};

Var app2 = new Applicant

{

Name = "Janis Rogers ",

ResumePath = path2

};

Context. Applicants. Add (app1 );

Context. Applicants. Add (app2 );

Context. SaveChanges ();

 

// Delete Alex Jones

Context. Applicants. Remove (app1 );

Context. SaveChanges ();

}

}

}

 

Public partial class EFRecipesEntities

{

Public override int SaveChanges ()

{

Console. WriteLine ("Saving Changes ...");

Var applicants = this. ChangeTracker. Entries (). Where (e => e. State = System. Data. Entity. EntityState. Deleted)

. Select (e => e. Entity). OfType <Applicant> (). ToList ();

Int changes = base. SaveChanges ();

 

Console. WriteLine ("\ n {0} applicants deleted", applicants. Count (). ToString ());

 

Foreach (var app in applicants)

{

File. Delete (app. ResumePath );

 

Console. WriteLine ("\ n {0}'s resume at {1} deleted", app. Name, app. ResumePath );

}

Return changes;

}

}

The output result of the above Listing 12-1 code is as follows:

Saving Changes...

0 applicants deleted

Saving Changes...

1 applicants deleted

Alex Jones's resume at AlexJones.txt deleted

Principle

For the code in Listing 12-1, insert two applicant files to create their own documents at the same time. our goal is to use a unified method. When applicant is deleted, their documents are also deleted. we use the override SaveChanges () method. in our SaveChanges () method, first collect all the Applicant instances to be deleted, and then call

SaveChanges () method, delete them from the database, traverse the instances we first collected, and delete their respective documents in the traversal. because the object will be deleted from the database in the context, we can no longer find the deleted native in the context through the query, so the ToList () method is used in the first step, first, save the object to be deleted to another object.

EF has no entity insert, update, or modify events, but many things you want to handle in these events can be implemented in the same way as we do here through the override SaveChanges () method.

 

Appendix: script file of the database used in the Creation example

 

 

Related Article

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.