MVC5 Entity Framework Learning async and stored procedures

Source: Internet
Author: User
Tags rowcount actionlink

In the previous article, you learned how to use the synchronous programming model to read and update data, and in this section you will learn how to implement the asynchronous programming model. Asynchronous can make application execution more efficient, because it can use server resources more efficiently.

Also in this section you will learn how to use stored procedures for INSERT, UPDATE, and delete operations on entities.

Finally, deploy the application to Windows Azure.

The following is the finished page




Why do you use asynchronous code

The available threads for a Web server are limited, and all available threads may be in use under high load conditions. When this occurs, the server will not be able to process the new request until the thread is freed. With synchronous code, a large number of threads will be locked, but in fact they are not doing anything but waiting for IO to complete. With asynchronous code, when a process is waiting for the IO to complete, its threads are freed by the server and processed by other requests. As a result, asynchronous code can use server resources more efficiently and can handle more traffic without delay.

In earlier versions of. NET, writing and testing asynchronous code was complex, error-prone, and difficult to debug. But in. Net 4.5, it's so easy to write, test, and debug asynchronous code, so you should always use asynchronous code. Asynchronous code costs less, and the impact on performance is negligible in low-traffic situations, but with high traffic, the potential performance gains are enormous.

Creating a Department controller

Create a Department controller, select the Use Async Controller actions check box


To view the async code added in the index method

Public async task<actionresult> Index () {    var departments = db. Departments.include (d = d.administrator);    Return View (await departments. Tolistasync ());}
There are changes around to let the Entity Framework use asynchronous execution of database queries:

    • Method uses the Async keyword, which tells the compiler to generate a callback method for the method body and automatically creates the returned Task<actionresult> object.
    • Changing the return type from ActionResult to task<actionresult>,task<t> type indicates that the work in progress returns the result of type T.
    • The await keyword is used for Web service calls, and when the compiler sees the keyword, the method is divided into two parts: the first part ends at the beginning of the asynchronous operation, the second part is put into a callback method, and is called when the operation is complete.
    • The asynchronous version of the ToList extension method is called.

Why only departments has been modified. ToList statement instead of Departments= db. Departments statement? This is because only queries or commands sent to the database use asynchronous execution. Departments=db. The Departments statement generates 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 method and the HttpGet edit and Delete methods, only the Find method sends the query to the database for execution, so the method is 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 Create,httppost Edit and Deleteconfirmed methods, invoking the SaveChanges method causes the execution of the command, like DB. The Department.add (Department) method simply modifies the entity in memory.

Public async task<actionresult> Create (Department Department) {    if (modelstate.isvalid)    {        db. Departments.add (department);    Await DB. Savechangesasync ();        Return redirecttoaction ("Index");    }
Open views\department\index.cshtml and replace it with the following code

@model ienumerable<contosouniversity.models.department>@{viewbag.title = "departments";} 

The above code changes the title from index to departments, moves the administrator name to the right, and provides the full name of the administrator.

In the Create, Delete,,details, and edit views, modify the title of the Instructorid field to administrator

Use the following code in the Create and edit views

<label class= "Control-label col-md-2" for= "Instructorid" >Administrator</label>
Use the following code in the delete and details views

<dt>    administrator</dt>
Run the project, click the Departments tab


The program runs fine, but in this controller, all SQL queries are executed asynchronously.

When you use the Entity Framework for asynchronous programming, be aware that:

    • Async code is not thread-safe. In other words, do not use the same context instance to perform multiple operations in parallel.
    • If you want to be able to take advantage of the performance benefits of asynchronous code, make sure that all of the library packages you are using, such as paging, also use asynchronous execution when calling any Entity Framework method and sending the query to the database.

using stored procedures in INSERT, UPDATE, and delete operations

Some developers and DBAs prefer to use stored procedures for database access. In earlier versions of the Entity Framework, you could use stored procedures to retrieve data from raw SQL queries, but you cannot use stored procedures in update operations. In Entity Framework 6, you can configure code first to use stored procedures.

1. Open Dal\schoolcontext.cs and add the following code to the Onmodelcreating method

protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) {    modelbuilder.conventions.remove< Pluralizingtablenameconvention> ();    Modelbuilder.entity<course> ()        . Hasmany (c = c.instructors). Withmany (i = i.courses)        . Map (t = = T.mapleftkey ("CourseID")            . Maprightkey ("Instructorid")            . ToTable ("Courseinstructor"));    Modelbuilder.entity<department> (). Maptostoredprocedures ();}
The code above specifies that the Entity Framework uses stored procedures for insert,update and delete operations of department entities.

2. Enter the following command in the package Manage console

Add-migration DEPARTMENTSP
Open Migrations\<timestamp>_departmentsp.cs to view the INSERT, update, and delete stored procedures created in the UP method

public override void Up () {createstoredprocedure ("dbo").  Department_insert ", p = = new {Name = P.string (maxlength:50), Budget = P.decimal (precision:19, Scale:4, Storetype: "Money"), StartDate = P.datetime (), Instructo RID = P.int (),}, Body: @ "INSERT [dbo]. [Department]              ([Name], [Budget], [StartDate], [Instructorid]) VALUES (@Name, @Budget, @StartDate, @InstructorID) DECLARE @DepartmentID int Selec T @DepartmentID = [DepartmentID] from [dbo].              [Department] WHERE @ @ROWCOUNT > 0 and [DepartmentID] = scope_identity () SELECT t0.              [DepartmentID] from [dbo]. [Department] As t0 WHERE @ @ROWCOUNT > 0 and T0.                [DepartmentID] = @DepartmentID "); Createstoredprocedure ("dbo.          Department_update ", p = new  {DepartmentID = P.int (), Name = P.string (maxlength:50), Budget = P.decima L (precision:19, Scale:4, Storetype: "Money"), StartDate = P.datetime (), Instructorid = p.i NT (),}, Body: @ "UPDATE [dbo]."              [Department] SET [Name] = @Name, [Budget] = @Budget, [StartDate] = @StartDate, [Instructorid] = @InstructorID WHERE ([Depa                Rtmentid] = @DepartmentID) "); Createstoredprocedure ("dbo.            Department_delete ", p = = new {DepartmentID = P.int (),}, Body: @ "DELETE [dbo].              [Department]    WHERE ([DepartmentID] = @DepartmentID) "); }
3. Enter the following command in the package Manage console

Update-database
4. Run the project, click the Departments tab, and then click Create New

5. Enter the data and click Create



6. In Visual Studio, the output window can see that a stored procedure was used to insert a department row


Code first creates a stored procedure with the default name. If you are using an existing database, you may need to customize the name of the stored procedure to use the stored procedures that are defined in the database.

If you want to customize the stored procedure, you can edit the skeleton code of the stored procedure created in the UP method. When the migration occurs, the changes you make are displayed, and when the migration is automatically run in the production environment after the deployment, the changes you make are applied to the production environment database.

If you want to modify a stored procedure created in a previous migration, you can use the add-migration command to generate an empty migration and then manually write code to call the Alterstoredprocedure method.

deploy to Windows Azure

This section requires you to complete the MVC5 Entity Framework Learning Code First migration and deployment tutorial in the Deploy application to Windows Azure Chapter, if an error occurs in the migration, you need to remove the local database to resolve it.

1. In the Solution Explorer in Visual Studio, right-click the project and select Publish

2. Click Publish,visual Studio to deploy the application to Windows Azure and open the program in the browser

3. Test the application to verify that it is working properly

When you run the application for the first time and access the database, the Entity framework performs all the up methods in the migration to ensure consistency of the data model.

Original: Async and Stored procedures with the Entity Framework in an ASP. NET MVC Application

Welcome reprint, please indicate the source of the article: http://blog.csdn.net/johnsonblog/article/details/39272637
Also everyone a healthy network environment, from you and I start

The END

MVC5 Entity Framework Learning async and stored procedures

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.