EF supports addition, deletion, query, and modification, and ef supports addition and deletion.

Source: Internet
Author: User
Tags actionlink

EF supports addition, deletion, query, and modification, and ef supports addition and deletion.

In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server LocalDB. in this tutorial you'll review and customize the CRUD (create, read, update, delete) code that the MVC scaffolding automatically creates for you in controllers and views.

In the previous course, you used Ef and SQL Server LocalDB to create an MVC program that can store and display data. In this series of courses, you will review and customize the MVC code.

NoteIt's a common practice to implement the repository pattern in order to create an Authorization Action layer between your controller and the data access layer. to keep these tutorials simple and focused on teaching how to use the Entity Framework itself, they don't use repositories. for information about how to implement repositories, see the ASP. NET Data Access Content Map.

Currently, it is common to implement the warehousing mode to create an abstraction layer between your controller and the data access layer. To ensure that this series of courses is as simple as possible, and focus on teaching how to use EF, here we do not use the warehouse mode. To learn how to implement the warehouse mode, please refer to the article at the link.

Create a Details Page

The scaffolded code for the StudentsIndex Page left outEnrollmentsProperty, because that property holds a collection. InDetailsPage you'll display the contents of the collection in an HTML table.

The Base Frame ignores the Enrollments attribute on the Student list page, because this attribute contains a set. On the details page, you will display the content of this set in an HTML table.

 1   public ActionResult Details(int? id) 2         { 3             if (id == null) 4             { 5                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 6             } 7             Student student = db.Students.Find(id); 8             if (student == null) 9             {10                 return HttpNotFound();11             }12             return View(student);13         }

AfterEnrollmentDateField and immediately before the closing</dl>Tag, add the highlighted code to display a list of enrollments, as shown in the following example: After the Enrollmentdate field, add the following highlighted code:

 1 @model ContosoUniversity.Models.Student 2  3 @{ 4     ViewBag.Title = "Details"; 5     Layout = "~/Views/Shared/_Layout.cshtml"; 6 } 7  8 

TIPS: Ctrl + K + D, code indent

Now, run the project and click the details list:

Update the Create Page

InControllers \ StudentController. cs, ReplaceHttpPost CreateAction method with the following code to addtry-catchBlock and removeIDFrom the Bind attribute for the scaffolded method:

Open the Student controller and use the following code to update it:

1 // POST: Students/Create 2 // to prevent "too many releases" attacks, enable specific properties to bind, for 3 // details, see http://go.microsoft.com/fwlink? LinkId = 317598. 4 [HttpPost] 5 [ValidateAntiForgeryToken] 6 public ActionResult Create ([Bind (Include = "LastName, FirstMidName, EnrollmentDate")] Student student) 7 {8 try 9 {10 if (ModelState. isValid) 11 {12 db. students. add (student); 13 db. saveChanges (); 14 return RedirectToAction ("Index"); 15} 16 17} 18 catch (DataException/* dex */) 19 {20 // Log the error (uncomment dex variable name and add a line here to write a log.21 ModelState. addModelError ("", "Unable to save changes. try again, and if the problem persists see your system administrator. "); 22} 23 24 25 return View (student); 26}

This code addsStudentEntity created by the ASP. net mvc model binder toStudentsEntity set and then saves the changes to the database .(Model binderRefers to the ASP. net mvc functionality that makes it easier for you to work with data submitted by a form; a model binder converts posted form values to CLR types and passes them to the action method in parameters. in this case, the model binder instantiatesStudentEntity for you using property values fromFormCollection .)

You removedIDFrom the Bind attribute becauseIDIs the primary key value which SQL Server will set automatically when the row is inserted. Input from the user does not setIDValue.

 

Security Note:TheValidateAntiForgeryTokenAttribute helps prevent cross-site request forgery attacks. It requires a correspondingHtml.AntiForgeryToken()Statement in the view, which you'll see later.

The ValidateAntiForgeryToken attribute helps block cross-site request attacks. It needs to write the Html. AntiForgeryToken () Statement in the view. You will see it later.

TheBindAttribute is one way to protect againstOver-postingIn create scenarios. For example, supposeStudentEntity includesSecretProperty that you don't want this web page to set.

Even if you don't haveSecretField on the web page, a hacker cocould use a tool such asfiddler, or write some JavaScript, to postSecretForm value. Without the Bind attribute limiting the fields that the model binder uses when it createsStudentInstance,The model binder wocould pick up thatSecretForm value and use it to createStudentEntity instance. Then whatever value the hacker specified forSecretForm field wocould be updated in your database. The following image shows the fiddler tool addingSecret Field (with the value "OverPost") to the posted form values. In short, without the Bind attribute, hackers will Post the data to your database. (PS: the translation has been completed, and the result is hand-disabled. If you press the wrong button, you are too lazy to translate it again .)

You can prevent overposting in edit scenarios is by reading the entity from the database first and then callingTryUpdateModel, Passing in an explicit allowed properties list. That is the method used in these tutorials.

An alternative way to prevent overposting that is preferrred by using developers is to use view models rather than entity classes with model binding. include only the properties you want to update in the view model. once the MVC model binder has finished, copy the view model properties to the entity instance, optionally using a tool such as AutoMapper. use db. entry on the entity instance to set its state to Unchanged, and then set Property ("PropertyName "). isModified to true on each entity property that is stored in the view model. this method works in both edit and create scenarios.

(PS: Now I have time to complete the course series)

 

Other thanBindAttribute,try-catchBlock is the only change you 've made to the scaffolded code. if an exception that derives from DataException is caught while the changes are being saved, a generic error message is displayed. dataException exceptions are sometimes caused by something external to the application rather than a programming error, so the user is advised to try again. although not implemented in this sample, a production quality application wocould log the exception. for more information, seeLog for insightSection in Monitoring and Telemetry (Building Real-World Cloud Apps with Azure ).

(PS: Now I have time to complete the course series)

The code inViews \ Student \ Create. cshtmlIs similar to what you saw inDetails. cshtml, Doesn't thatEditorForAndValidationMessageForHelpers are used for each field insteadDisplayFor. Here is the relevant code:

(PS: Now I have time to complete the course series)

 

Update the Edit HttpPost Method

InControllers \ StudentController. cs,HttpGet EditMethod (the one withoutHttpPostAttribute) usesFindMethod to retrieve the selectedStudentEntity, as you saw inDetailsMethod. You don't need to change this method.

However, replaceHttpPost EditAction method with the following code:

1 [HttpPost, ActionName ("Edit")] 2 [ValidateAntiForgeryToken] 3 public ActionResult EditPost (int? Id) 4 {5 if (id = null) 6 {7 return new HttpStatusCodeResult (HttpStatusCode. badRequest); 8} 9 var studentTOUpdate = db. students. find (id); 10 if (TryUpdateModel (studentTOUpdate, "", new string [] {"LastName", "FirstName", "EnrollmentDate "})) 11 {12 13 try14 {15 db. saveChanges (); 16 return RedirectToAction ("Index"); 17} 18 catch (DataException/* dex */) 19 {20 ModelState. addModelError ("", "cannot be saved, please try again"); 21} 22} 23 return View (studentTOUpdate); 24}

These changes implement a security best practice to prevent overposting, The scaffolder generatedBindAttribute and added the entity created by the model binder to the entity set with a Modified flag. That code is no longer recommended becauseBindAttribute clears out any pre-existing data in fields not listed inIncludeParameter. In the future, the MVC controller scaffolder will be updated so that it doesn't generateBindAttributes for Edit methods.

 

The new code reads the existing entity and calltryupdatemodel to update fields from user input in the posted form data. the Entity Framework's automatic change tracking sets the Modified flag on the entity. when the SaveChangesmethod is called,ModifiedFlag causes the Entity Framework to create SQL statements to update the database row. concurrency conflicts are ignored, and all columns of the database row are updated, including those that the user didn't change. (A later tutorial shows how to handle concurrency conflicts, and if you only want individual fields to be updated in the database, you can set the entity to Unchanged and set individual fields to Modified .)

 

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.