Getting started with EF6 Code First using MVC 5: using asynchronous and stored procedures for ASP. net mvc applications

Source: Internet
Author: User

This is the official Microsoft tutorial Getting Started with Entity Framework 6 Code First using MVC 5 Series. Here is article 7: update relevant data for ASP. net mvc applications

Original article: Async and Stored Procedures with the Entity Framework in an ASP. net mvc Application

All rights reserved. The full text is not reprinted-but you can add a link to this tutorial on your website.

In the previous tutorial, you have learned how to use the Synchronous Programming Model to read and update data. In this tutorial, you will see how to implement the asynchronous programming model. Because it can better use server resources, asynchronous code can help applications better execute.

In this tutorial, you will also see how to use stored procedures to insert, update, and delete objects.

The following illustration shows the page you want to write:

Why bother asynchronous code?

A web server has only a limited number of available threads, and in the case of high load, all threads may be in use. In this case, the server will not be able to process new requests until a thread is released. In the case of code synchronization, multiple threads may be associated, but in fact they do not do any work but only wait for IO to complete. With Asynchronous Code, when a process is waiting for IO to complete, its thread can be freed up by the server to process other requests. Therefore, asynchronous code can use server resources more efficiently, and the server can process more traffic without delay.

In earlier versions of. NET, writing and testing asynchronous code is complicated, error-prone, and difficult to debug. In. Net 4.5, writing, testing, and debugging asynchronous code becomes simple. You should always use Asynchronous code unless you have reason not to allow it. Asynchronous code will spend a small amount of time, but the performance loss is negligible in the case of low traffic. In the case of high traffic, the potential performance indicators are huge.

For more information about asynchronous programming, see Use. NET 4.5's async support to avoid blocking CILS.

Create a system controller

You can create a system controller in the same way before creating other controllers, but this time we chooseUse an asynchronous Controller.

In the following code, the highlighted part shows the differences between the Asynchronous Method and the synchronous method:

        public async Task<ActionResult> Index()        {            var departments = db.Departments.Include(d => d.Administrator);            return View(await departments.ToListAsync());        }

 

Four Changes were applied to enable the Entity Framework database to execute asynchronous queries:

  • This method uses the async keyword, which tells the compiler to generate the part of the callback method body and automatically creates the Task <ActionResult> to return the object.
  • The return type is changed from ActionResult to Task <ActionResult>. Task <T> type indicates that the ongoing Task has a result of type T.
  • The await keyword is applied to web service calls. When the compiler sees this keyword, the method is divided into two parts in the background. The first part ends with the asynchronous operation, and the second part is the callback method when the operation is complete.
  • The asynchronous version that calls the ToList extension method.

Why do I only modify the statements of orders. ToList instead of orders = db. Orders. ments? The reason is that only the query or statement executed by the sent database can be executed asynchronously. The orders statement sets a query, but the query is not executed until the ToList method is called. Therefore, only the ToList method is executed asynchronously.

In the Details and Httpget Edit and Delete methods, the Find method is used to send queries to the database for retrieval. Therefore, this method can be executed asynchronously.

        public async Task<ActionResult> Details(int? id)        {            if (id == null)            {                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);            }            Department department = await db.Departments.FindAsync(id);            if (department == null)            {                return HttpNotFound();            }            return View(department);        }

 

In the Edit and DeleteConfirmed methods of Create, HttpPost, The SaveChanges method causes command execution, while the db. Department. Add (department) method only causes entity modification in memory.

        public async Task<ActionResult> Create([Bind(Include="DepartmentID,Name,Budget,StartDate,InstructorID")] Department department)        {            if (ModelState.IsValid)            {                db.Departments.Add(department);                await db.SaveChangesAsync();                return RedirectToAction("Index");            }            ViewBag.InstructorID = new SelectList(db.Instructors, "ID", "LastName", department.InstructorID);            return View(department);        }

 

Open Views \ Department \ Index. cshtml and use the following code to replace the original one:

@model IEnumerable<ContosoUniversity.Models.Department>@{    ViewBag.Title = "Departments";}

 

The code changes the title, moves the head column to the right, and provides the name of the head.

In the CREATE, delete, detail, and edit view, change the title of the InstructorID field to "Head of the Department", as you did before changing the Department Name field to "department" in the course view.

Use the following code to create and edit a view:

   @Html.DisplayFor(model => model.Department.Name)

Use the following code to delete and View Details:

        <dt>            Administrator        </dt>

 

Run the application and click the system tab.

The program runs normally, just like other controllers. However, in this controller, all SQL queries are executed asynchronously.

When using asynchronous programming in the object framework, you must note the following:

  • Asynchronous code is not thread-safe. In other words, do not use the same context instance to execute multiple operations in parallel.
  • If you want to take advantage of the performance advantages of asynchronous code, make sure that you are using all the library software packages (such as paging ), any entity framework methods, such as database queries performed in the package, are also executed asynchronously.
Stored Procedures for insert, update, and delete

Some developers and DBAs prefer to use stored procedures to access databases. In earlier versions of the Entity Framework, you can use the original SQL query method to retrieve data to execute stored procedures, but you cannot use stored procedures for update operations. In Entity Framework 6, you can easily configure Code First to use stored procedures.

Code First uses the default name to create a stored procedure. If you are using an existing database, you may need to customize the name of the Stored procedure. For information about how to operate, see Entity Framework Code First Insert/Update/Delete Stored Procedures.

If you want to customize the stored procedure, you can edit the Up method in the scaffold code in the migration to create the stored procedure. When this method is used, your changes will be automatically made during application migration or after deployment to the production environment.

If you want to modify a stored procedure that has been created in the previous Migration, you can use the Add-Migration command to generate a blank Migration, and then manually write the code to call the AlterStoredProcedure method.

Deploy to Windows Azure

Skip this chapter ......

Summary

In this tutorial, you can see how to improve server efficiency. Insert, update, and delete operations by writing asynchronous code and using stored procedures. In the next tutorial, you will see how to prevent data loss when multiple users attempt to edit the same record.

 

Author Information

 

Tom Dykstra-Tom Dykstra is a Senior Programmer and writer of the Microsoft Web platform and tool team.

 

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.