教學課程:開始在 ASP.NET MVC Web 應用程式中使用 EF Core

资讯 2024-07-13 阅读:64 评论:0
本教學課程可讓您了解具有控制器和檢視的 ASP.NET Core MVC 和 Entity Framework Core。 Razor Pages 是替代的程式設計模型。 針對新的開發,我們建議您搭配控制器與檢視在 MVC 上使用 Raz...
美化布局示例

欧易(OKX)最新版本

【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   全球官网 大陆官网

币安(Binance)最新版本

币安交易所app【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   官网地址

火币HTX最新版本

火币老牌交易所【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   官网地址

本教學課程可讓您了解具有控制器和檢視的 ASP.NET Core MVC 和 Entity Framework Core。 Razor Pages 是替代的程式設計模型。 針對新的開發,我們建議您搭配控制器與檢視在 MVC 上使用 Razor Pages。 請參閱 Razor Pages 版的本教學課程。 每個教學課程都涵蓋其他教學課程為涵蓋的一些內容:

The course provides you with an alternative design model for ASP.NET Core MVC and Entity Framewerk Core. Razor Pages. For new developments, we recommend that you use Razor Pages with control and viewers on MVC. See some of the other courses of the course https://docs.microsoft.com/zh-TW/aspnet/core/data/ef-rp/intro?eew=aspnetre-3.0'data-kty'pey'live & peds.

此 MVC 教學課程中的一些內容具有 Razor Pages 教學課程未包含的內容:

Some of the contents of this MVC course are not included in the Razor Pages course:

  • 在資料模型中實作繼承
  • 執行原始 SQL 查詢
  • 使用動態 LINQ 來簡化程式碼

Razor Pages 教學課程中的一些內容具有此教學課程未包含的內容:

Some of the contents of the Razor Pages course are not included in the course:

  • 使用 Select 方法來載入相關資料
  • EF 的最佳做法。

Contoso 大學範例 Web 應用程式示範如何使用 Entity Framework (EF) Core 2.2 和 Visual Studio 2019 來建立 ASP.NET Core 2.2 MVC Web 應用程式。

An example of the University of Contoso is how the Web application demonstrates how to build an ASP.NET Core 2.2 MWC Web application using the Energy Framewerk (EF) Core 2.2 and Visual Studio 2019.

此教學課程尚未升級至 ASP.NET Core 3.1。 其已針對 ASP.NET Core 5.0 進行更新。

The course has not been upgraded to ASP.NET Core 3.1. It has been updated to .

這個範例應用程式是虛構的 Contoso 大學網站。 其中包括的功能有學生入學許可、課程建立、教師指派。 這是說明如何從零開始建立 Contoso 大學範例應用程式教學課程系列中的第一頁。

This example application is a fictional Contoso University website. It includes functions such as student admission, curriculum development, and teacher assignments.

如果您遭遇無法解決的問題,將您的程式碼與已完成的專案作比較,通常可以找到解答。 如需常見錯誤和如何解決這些問題的清單,請參閱 本系列最後一個教學課程中的疑難排解一節。 如果您在那裡找不到所需的資訊,可以在 StackOverflow.com 上張貼關於 ASP.NET CoreEF Core 的問題。

If you have problems that you cannot solve, compare your code with . For a list of common errors and how to solve these problems, see http://docs.microft.comat.htm"

提示

Hint

這是 10 個教學的系列課程,當中的每一個課程都是建置於先前教學課程的成果上。 成功完成每一個教學課程後,請儲存專案的複本。 如果您遇到問題,您可以從上一個教學課程來重新開始,而不需從系列的一開始從頭來過。

This is a series of 10 teaching courses, each of which is built on the results of the previous course. After successfully completing each course, save a copy of the project. If you have a problem, you can start again from the previous course instead of starting from the beginning of the series.

您在這些教學課程中會建置的應用程式為一個簡單的大學網站。

The application you will build in these classes is a simple university website.

使用者可以檢視和更新學生、課程和教師資訊。 以下是您會建立的幾個畫面。

Users can view and update information about students, courses and teachers. Here are some of the images you will create.

Students Index page

Students Edit page

  • 開啟 Visual Studio。

    Open Visual Studio.

  • 從 [檔案] 功能表選取[新增] > [專案]

    Select [new] & gt; [project] from the [file] functional list.

  • 從左側窗格中,選取 [已安裝] > [Visual C#] > [Web]

    From the left window, select [installed] & gt; [Visual C#] & gt; [Web].

  • 選取 [ASP.NET Core Web 應用程式] 專案範本。

    Select a template for the [ASP.NET Core Web application] project.

  • 輸入 ContosoUniversity 作為名稱,然後按一下 [確定]

    Enter ContosoUniversity as its name, and then press .

    New Project dialog

  • 等候 [新增 ASP.NET Core Web 應用程式] 對話方塊出現。

    Waits for [new ASP.NET Core Web application] dialogues to appear.

  • 選取 [.NET Core]、[ASP.NET Core 2.2] 和 [Web 應用程式 (Model-View-Controller)] 範本。

    Select [.NET Core] , [ASP.NET Core 2.2] , and [Web Application (Model-View-Controller)] , .

  • 確認 [驗證] 已設為 [No Authentication] (無驗證)

    Confirm [verification] has been set to (unverified) .

  • 選取確定

    Select

    New ASP.NET Core Project dialog

一些簡單的變更會設定網站的功能表、配置和首頁。

Some simple changes will set the functionality table, configuration and home page of the site.

開啟 ,然後進行下列變更:

Open, then make the following changes:

  • 將每個出現的 "ContosoUniversity" 都變更為 "Contoso University"。 共有三個發生次數。

    Change every occurrence of "ContosoUniversity" to "Contoso University". There are three occurrences.

  • 為 [About]、[Students]、[Courses]、[Instructors] 及 [Departments] 新增功能表項目,並刪除 [Privacy]Privacy 功能表項目。

    Add a new list item for [About] , [Students] , [Courses] , [Instructors] and [Departments] , and delete the [Privacy] functional list entry.

所做的變更已醒目提示。

The changes that have been made are telling.


在 中用下列程式碼取代檔案內容,以使用關於此應用程式的文字來取代關於 ASP.NET 和 MVC 的文字:

Replace file contents with the following code to replace ASP.NET and MVC text with text for this application:


按 CTRL+F5 來執行專案,或從功能表選擇 [偵錯] > [啟動但不偵錯]。 您會看到在這些教學課程中,您將建立之頁面的索引標籤和首頁。

Press CTRL+F5 to execute the project, or select the & gt; [started but not detected] from the functional table. You will see the index labels and headlines of the pages you will create in these courses.

Contoso University home page

若要將 EF Core 支援新增至專案,請安裝您欲使用資料庫的提供者。 本教學課程使用 SQL Server,其提供者套件為 Microsoft.EntityFrameworkCore.SqlServer。 此套件包含在 Microsoft.AspNetCore.App metapackage 中,因此您不需要參考該套件。

If you want to add EF Core support to the project, install the provider that you want to use the database. SQL Server is used in this course. The provider package is . This package is contained in 移轉教學課程中新增工具套件。

The EF SQL Server package and its dependencies (and) provide EF implementation session support. You will add a new tool package to the .

如需其他 Entity Framework Core 可用之資料庫提供者的資訊,請參閱資料庫提供者

For information on other database providers available in Entity Framewerk Core, please refer to .

接下來您會為 Contoso 大學應用程式建立實體類別。 您會從下列三個實體開始。

You will then create an entity category for the Contoso University application. You will start with the following three entities.

Course-Enrollment-Student data model diagram

在 和 實體之間存在一對多關聯性, 與 實體之間也存在一對多關聯性。 換句話說,一位學生可以註冊並參加任何數目的課程,而一個課程也可以有任何數目的學生註冊。

In other words, a student can register and attend classes for any number of purposes, while a student can register for any number of purposes.

在下節中,您會為這些實體建立各自的類別。

In the next section, you will create categories for these entities.

Student entity diagram

在 [Models] 資料夾中,建立一個名為 的類別檔案,然後使用下列程式碼取代範本程式碼。

Creates a class file in the [Models] folder and replaces the template code with the following code.


屬性會成為資料庫資料表中的主索引鍵資料行,並對應至這個類別。 Entity Framework 預設會將名為 或 的屬性解譯為主索引鍵。

Properties will become the main index key data line in the database database and correspond to this category. Entity Framewerk defaults to interpret properties by name or by name as the main index key.

屬性為導覽屬性。 導覽屬性會保留與此實體相關的其他實體。 在這個案例中, 的 屬性會保有與該 實體相關的所有 實體。 換句話說,若資料庫中 資料列有兩個相關的 資料列 (包含該學生於其 StudentID 外部索引鍵資料行中主索引鍵值的資料列),該 實體的 導覽屬性便會包含這兩個 實體。

Attributes are

若導覽屬性可保有多個實體 (例如在多對多或一對多關聯性中的情況),其類型必須為一個清單,使得實體可以在該清單中新增、刪除或更新,例如 。 您可以指定 或如 或 等類型。 若您指定了 ,EF 會根據預設建立一個 集合。

If the navigation properties can retain multiple entities (e. g. in multiple or multi-related situations), the type must be a list that allows the entity to add, delete or update the list, for example. You can specify either the type or the type. If you specify, the EF will create a collection according to the default.

Enrollment entity diagram

在 [Models] 資料夾中,建立 ,然後使用下列程式碼取代現有的程式碼:

Create in [Models] folder and then replace the existing code with the following code:


屬性將為主索引鍵。此實體會使用 模式,而非您在 實體中所見到的自身 。 通常您會選擇一個模式,然後在您整個資料模型中使用此模式。 在這裡,此變化僅作為向您展示使用不同模式之用。 在稍後的教學課程中,您會了解使用沒有 classname 的識別碼可讓在資料模型中實作繼承變得更為簡單。

Properties will be the main index key. This entity uses a mode, not the one you see in the entity. Usually you select a mode, and then use it in your entire data model. Here, this change is only used to show you different patterns. In , you will understand that the use of non-clasname identifiers can make it easier to inherit in the data model.

屬性為 。 問號之後的 類型宣告表示 屬性可為 Null。 為 Null 的成績不同於成績為零:Null 表示成績未知或尚未指派。

Properties are. The type of declaration after the question mark indicates that properties can be Null. The result for Null is different from the score of zero: Null means that grades are unknown or have not been assigned.

屬性是外部索引鍵,對應的導覽屬性是 。 實體與一個 實體關聯,因此屬性僅能保有單一 實體 (不像您先前看到的 導覽屬性可保有多個 實體)。

Properties are external index keys and the guide properties are. The entity is associated with an entity, so the attribute can only hold a single entity (not as many entities as you have seen before).

屬性是外部索引鍵,對應的導覽屬性是 。 一個 實體與一個 實體建立關聯。

Properties are external index keys, and the corresponding navigational properties are. An entity is associated with an entity.

Entity Framework 會將名為 的屬性解譯為外部索引鍵屬性 (例如 導覽屬性的 ,因為 實體的主索引鍵為 )。 外部索引鍵屬性也可以簡單的命名為 (例如 ,因為 實體的主索引鍵為 )。

Entity Framewerk interprets the attribute name as an external index key attribute (e. g. guide property because the entity's main index key is). The external index key attribute can also be simply named (e. g. because the entity's main index key is).

Course entity diagram

在 [Models] 資料夾中,建立 ,然後使用下列程式碼取代現有的程式碼:

Create in [Models] folder and then replace the existing code with the following code:


屬性為導覽屬性。 實體可以與任何數量的 實體相關。

Properties are navigation properties. An entity can be associated with any number of entities.

我們會在此系列稍後的教學課程中進一步討論 屬性。 基本上,此屬性可讓您為課程輸入主索引鍵,而非讓資料庫產生它。

We will discuss the properties further in this series later in the course. Basically, this attributes allows you to enter the main index key for the course rather than to generate it in the database.

為指定資料模型協調 Entity Framework 功能的主要類別便是資料庫內容類別。 若要建立此類別,您可以從 類別來衍生。 在您的程式碼中,您會指定資料模型中包含哪些實體。 您也可以自訂某些 Entity Framework 行為。 在此專案中,類別命名為 。

The main category for the specified data model function is the database content class. To create this category, you can derive from the category. In your code, you specify which entities are included in the data model. You can also customize some Entity Framewerk behaviors. In this case, the category is named.

在專案資料夾中,建立名為 Data 的資料夾。

Creates a folder in the project folder named Data.

在 [Data] 資料夾中,建立名為 的新類別檔案,然後使用下列程式碼取代範本程式碼:

In the [Data] folder, create a new type of file named, and then replace the template code with the following code:


程式碼會為每一個實體集建立 屬性。 在 Entity Framework 詞彙中,實體集通常會對應至資料庫資料表,而實體則對應至資料表中的資料列。

Codes create attributes for each set of entities. In the Entity Framewerk vocabulary, the collection usually corresponds to the database data sheet, while the entity corresponds to the data column in the data sheet.

您可以省略 及 陳述式,其結果也會是相同的。 Entity Framework 會隱含它們,因為 實體參考了 實體;而 實體參考了 實體。

You can omit and make statements, and the results will be the same. Entity Framewerk will cover them because the entity refers to the entity; the entity refers to the entity.

資料庫建立時,EF 會建立和 屬性名稱相同的資料表。 集合的屬性名稱通常都是複數 (Students 而非 Student),但許多開發人員會為了資料表名稱究竟是否該是複數型態而爭論。 在此系列教學課程中,您會藉由指定 DbContext 中的單數資料表名稱來覆寫預設行為。 若要完成這項操作,請在最後一個 DbSet 屬性後方新增下列醒目提示程式碼。

When the database is created, the EF will create the same datasheet as the property name. The property name of the collection is usually a complex number (Students rather than Student), but many developers will argue whether or not the name of the table should be a complex type. In this series, you will overwrite the default behaviour by specifying the name of the singular data sheet in DbContext. To do this, add the following sharp hint code after the last DbSet attribute.


建置專案以檢查編譯器錯誤。

Build project to check compiler error.

根據預設,ASP.NET Core 會實作相依性插入。 服務 (例如 EF 資料庫內容) 是在應用程式啟動期間使用相依性插入來註冊。 接著,會透過建構函式參數,針對需要這些服務的元件 (例如 MVC 控制器) 來提供服務。 您會在此教學課程的稍後看到取得內容執行個體的控制器建構函式。

As foreseen, ASP.NET Core will insert . The service (e.g. EF database content) is registered using dependencies during application startup.

若要將 註冊為服務,請開啟 ,並將醒目標示的程式碼新增至 方法。

To register as service, open and add the Awakening Target code to the method.


連接字串的名稱,會透過呼叫 物件上的方法來傳遞至內容。 作為本機開發之用,ASP.NET Core 設定系統會從 檔案讀取連接字串。

The name of the connection string will be passed to content via the method on the call object. will read links from files.

為 和 命名空間新增 陳述式,然後建置專案。

Adds a statement for the space and name, and then builds the project.


開啟 檔案並新增連接字串,如下列範例所示。

Opens the file and adds a new connection string, as shown in the examples below.


連接字串會指定 SQL Server LocalDB 資料庫。 LocalDB 是輕量版的 SQL Server Express Database Engine,旨在用於應用程式開發,而不是生產用途。 LocalDB 會依需求啟動,並以使用者模式執行,因此沒有複雜的組態。 LocalDB 預設會在 目錄中建立 .mdf 資料庫檔案。

The connection string specifies the SQL Server LocalDB database. The LocalDB is a light version of SQL Server Express Database Engineering, designed to be developed for application purposes rather than for production purposes. The LocalDB is demand-driven and executed in user mode, so there is no complex configuration. The LocalDB default will create a database file in the directory .mdf.

Entity Framework 會為您建立空白資料庫。 在本節中,您會撰寫一個方法,該方法會在資料庫建立之後呼叫,以將測試資料填入資料庫。

Entity Framewerk will create an empty database for you. In this section you will write a method that will be called when the database is in place to fill the test data in the database.

在此您將使用 方法來自動建立資料庫。 在稍後的教學課程中,您將會了解到如何使用 Code First 移轉變更資料庫結構描述,而非卸除並重新建立資料庫,來處理模型的變更。

Here you will use the method to create a database. In , you will learn how to use Code First to change the profile of the database, rather than to remove and recreate the database to process changes in the model.

在 [Data] 資料夾中,建立一個名為 的新類別檔案,使用下列程式碼取代範本程式碼。這些程式碼會在需要的時候建立資料庫,並將測試資料載入至新的資料庫。

Creates a new type of file in the [Data] folder, replacing the template code with the following code. These codes create a database when needed and load the test data into the new database.


程式碼會檢查資料庫中是否有任何學生。若沒有的話,它便會假設資料庫是新的資料庫,因此需要植入測試資料。 會將測試資料載入至陣列而非 集合,以最佳化效能。

The code will check whether there are any students in the database. If it does not, it will assume that the database is a new database, and therefore the test data will need to be installed. The test data will be loaded into the array instead of the collection to optimize efficiency.

在 中,修改 方法來在應用程式啟動期間執行下列動作:

In, modify method to execute the following actions during application startup:

  • 從相依性插入容器中取得資料庫內容執行個體。
  • 呼叫種子方法,並將其傳遞給內容。
  • 種子方法完成時處理內容。

在您首次執行應用程式時,資料庫便會建立並植入測試資料。 每當您變更資料模型時:

When you run an application for the first time, the database builds and implants the test data. Every time you change the data model:

  • 刪除資料庫。
  • 更新種子方法,並使用相同方法以新的資料庫重新開始。

在稍後的教學課程中,您會了解如何在資料模型變更時修改資料庫,而不需要刪除和重新建立它。

Later in the course, you will learn how to modify the database when the data model changes, without the need to delete and recreate it.

在本節中,我們將會使用 Visual Studio 中的 Scaffolding 引擎來新增使用 EF 查詢和儲存資料的 MVC 控制器及檢視。

In this section, we will use the Scaffolding engine in Visual Studio to add a new MVC controller and view using EF query and data storage.

自動建立 CRUD 動作方法和檢視稱為 Scaffolding。 Scaffolding 與產生程式碼不同。Scaffold 程式碼是一個開始點,使得您可以修改它以符合您的需求,然而您通常不會去修改產生的程式碼。 當您需要自訂產生的程式碼時,您會使用部分類別,或者您會在事務變更時重新產生程式碼。

Automatically create the CRUD action method and view it as Scaffolding. Scaffolding is different from generating the code. The Scaffold code is a starting point that allows you to modify it to suit your needs, but you do not usually change the resulting code. When you need to customize the code, you will use some of the different types, or you will recreate the code when the matter changes.

  • 以滑鼠右鍵按一下 [方案總管] 中的 [Controllers] 資料夾,然後選取 [新增] > [新增 Scaffold 項目]
  • 在 [新增 Scaffold] 對話方塊中:
    • 選取 [使用 Entity Framework 執行檢視的 MVC 控制器]
    • 按一下新增。 [新增使用 Entity Framework 執行檢視的 MVC 控制器] 對話方塊隨即出現:Scaffold Student
    • 在 [模型類別] 中,選取 [Student]
    • 在 [資料內容類別] 中,選取 [SchoolContext]
    • 接受預設的 StudentsController 作為名稱。
    • 按一下新增

Visual Studio Scaffolding 引擎會建立 檔案及一組可以使用該控制器的檢視 ( 檔案)。

The Visual Studio Scaffolding engine will create files and a set of views (files) that can use the controller.

請注意,控制器會接受 作為建構函式的參數。

Please note that the controller will accept as a construction function parameter.


ASP.NET Core 相依性插入會負責傳遞 的執行個體給控制器。 該項已在 檔案中設定。

ASP.NET Core Dependency Inserts an executable individual to controller that will be responsible for transmission. This is set in the file.

控制器含有一個 動作方法,該方法會顯示資料庫中的所有學生。 方法會藉由讀取資料庫內容執行個體的 屬性,來從 Students 實體集中取得學生的清單:

The controller contains an action method that shows all students in the database. The method is to get a list of students from the Stuarts entity by reading the properties of the database contents:


您會在教學課程的稍後學習到此程式碼中的非同步程式設計項目。

You will learn about non-synchronous program design items in this code later in the course.

檢視會在資料表中顯示此清單:

The view will show this list in the table:


按 CTRL+F5 來執行專案,或從功能表選擇 [偵錯] > [啟動但不偵錯]

Press CTRL+F5 to execute the project, or select & gt from the functional table; [started but not detected] .

按一下 [Students] 索引標籤來查看 方法插入的測試資料。 取決於您瀏覽器視窗的寬度,您可能會在頁面的頂端看到 索引標籤連結,或是按一下位於右上角的導覽圖示來查看連結。

Click the [Students] index label to see the test data inserted by the method. Depending on the width of your browser window, you may see the link at the top of the page or the link at the top right-hand corner.

Contoso University home page narrow

Students Index page

當您啟動應用程式時, 方法會呼叫 。 EF 看到不存在任何資料庫,於是便建立了一個資料庫,接著 方法程式碼的剩餘部分便會將資料填入資料庫。 您可以使用 [SQL Server 物件總管 (SSOX) 來在 Visual Studio 中檢視資料庫。

When you start the application, the method calls. If you see that there is no database, the EF has created a database, which will then be filled into the database with the rest of the method code. You can use the [SQL Server Object Manager (SSOX) to view the database in Visual Studio.

關閉瀏覽器。

Closes the browser.

若 SSOX 視窗尚未開啟,請從 Visual Studio 中的 [檢視] 功能表選取它。

If the SSOX window is not open, select it from the [view] menu in Visual Studio.

在 SSOX 中,按一下 [(localdb)\MSSQLLocalDB] > [Databases],然後按一下位於 檔案中連接字串內資料庫名稱的項目。

In SSOX, press [(localdb)\MSSQLLocalDB] & gt; [Databases], and then click on the entry of the database name in the connecting string in the file.

展開 [資料表] 節點以查看資料庫中的資料表。

Expands [datasheets] nodes to view the data sheets in the database.

Tables in SSOX

以滑鼠右鍵按一下 Students 資料表,並按一下 [檢視資料] 查看建立的資料行及插入資料表中的資料列。

Press the Students database with the right mouse button and click the [viewing data] to view the established data line and insert the data column in the data table.

Student table in SSOX

.mdf.ldf 資料庫檔案位於 C:\Users<使用者名稱> 資料夾中。

The database files for .mdf and .ldf are located in C:\USERS< username > folders.

因為您在應用程式啟動時執行的初始設定式方法中呼叫了 ,您現在可以對 類別進行變更、刪除資料庫、重新執行應用程式,資料庫會自動重新建立以符合您所作出的變更。 例如,若您將一個 屬性新增到 類別,您便會在重新建立的資料表中看到新的 資料行。

Because you have been called in the initial configuration method that you will be running on application startup, you can now change the category, delete the database, rerun the application, and the database will automatically recreate the changes you have made. For example, if you add a attribute to the class, you will see a new data line in the recreated database.

為了讓 Entity Framework 能夠建立一個完整資料庫,您所需要撰寫的程式碼非常少,多虧了慣例的使用及 Entity Framework 所做出的假設。

In order for Entity Framewerk to be able to build a full database, you need to write very few codes, thanks to routine usage and assumptions made by Entity Framewerk.

  • 屬性的名稱會用於資料表名稱。 針對 屬性並未參考的實體,實體類別名稱會用於資料表名稱。
  • 實體屬性名稱會用於資料行名稱。
  • 命名為 ID 或 classnameID 的實體屬性,會辨識為主索引鍵屬性。
  • 如果屬性命名為 <導覽屬性名稱><主索引鍵屬性名稱>,系統就會將該屬性解譯為外部索引鍵屬性 (例如,若為 導覽屬性則為 ,因為 實體的主索引鍵是 )。 外部索引鍵屬性也可以直接命名為 <主索引鍵屬性名稱> (例如 ,因為 實體的主索引鍵為)。

慣例行為可以被覆寫。 例如,您可以明確指定資料表名稱,如稍早在本教學課程中您所見到的。 您可以設定資料行名稱以及將任何屬性設為主索引鍵或外部索引鍵,如同您在本系列稍後的教學課程中所見。

As is customary, you can be overwritten. For example, you can specify clearly the name of the data sheet, as you saw earlier in the course. You can set the data line name and set any attributes as main or external index keys, as you see in the later course of this series at

非同步程式設計是預設的 ASP.NET Core 和 EF Core 模式。

Non-sync program designs are default ASP.NET Core and EF Core modes.

網頁伺服器的可用執行緒數量有限,而且在高負載情況下,可能會使用所有可用的執行緒。 發生此情況時,伺服器將無法處理新的要求,直到執行緒空出來。 使用同步程式碼,許多執行緒可能在實際上並未執行任何工作時受到占用,原因是在等候 I/O 完成。 使用非同步程式碼,處理程序在等候 I/O 完成時,其執行緒將會空出來以讓伺服器處理其他要求。 因此,非同步程式碼可讓伺服器資源更有效率地使用,而且伺服器可處理更多流量而不會造成延遲。

The web server has a limited number of available runs and, in high load situations, may use all available executors. In this case, the server will not be able to handle new requests until the executable is empty. Using synchronous code, many executors may be occupied when they are not actually performing any work, because I/O is waiting to do it. Using non-sync code, the processor will be empty to allow the server to process other requests when I/O is ready. Therefore, non-synchronous code allows server resources to be used more efficiently and the server can handle more traffic without causing delay.

非同步程式碼雖然的確會在執行階段造成少量的負荷,但在低流量情況下,對效能的衝擊非常微小;在高流量情況下,潛在的效能改善則相當大。

While non-synchronous codes do create a small number of negative loads during the implementation phase, in low-flow situations, the impact on effectiveness is minimal; in high-flow situations, the potential for improvement is considerable.

在下列程式碼中, 關鍵字、 傳回值、 關鍵字和 方法使程式碼以非同步方式執行。

In the following codes, keywords, returns, keywords and methods enable the code to be executed in a non-sync manner.


  • 關鍵字會告訴編譯器為方法本體的一部分產生回呼,並自動建立傳回的 物件。
  • 傳回類型 代表了正在進行的工作,其結果為 類型。
  • 關鍵字會使編譯器將方法分割為兩部分。 第一個部分會與非同步啟動的作業一同結束。 第二個部分則會放入作業完成時呼叫的回呼方法中。
  • 是 擴充方法的非同步版本。

當您在撰寫使用 Entity Framework 的非同步程式碼時,請注意下列事項:

When you are writing a non-sync code using Entity Framewerk, please note the following:

  • 只有讓查詢或命令傳送至資料庫的陳述式,會以非同步方式執行。 其中包含,例如 、,以及 。 其中不包含,例如:僅變更 的陳述式,例如 。
  • EF 內容在執行緒中並不安全:不要嘗試執行多個平行作業。 當您呼叫任何 async EF 方法時,請一律使用 關鍵字。
  • 若您想要充分利用非同步程式碼帶來的效能優點,請確保任何您正在使用的程式庫 (例如分頁) 也使用了非同步 (若它們有呼叫任何可能會傳送查詢到資料庫的 Entity Framework 方法的話)。

如需在 .NET 中非同步程式設計的詳細資訊,請參閱非同步總覽

See .

若要了解如何執行基本的 CRUD (建立、讀取、更新、刪除) 作業,請前往下一個教學課程。

If you want to know how to run a basic CRUD (create, read, update, delete) study, go to the next course.

美化布局示例

欧易(OKX)最新版本

【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   全球官网 大陆官网

币安(Binance)最新版本

币安交易所app【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   官网地址

火币HTX最新版本

火币老牌交易所【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   官网地址
文字格式和图片示例

注册有任何问题请添加 微信:MVIP619 拉你进入群

弹窗与图片大小一致 文章转载注明

分享:

扫一扫在手机阅读、分享本文

发表评论
平台列表
美化布局示例

欧易(OKX)

  全球官网 大陆官网

币安(Binance)

  官网

火币(HTX)

  官网

Gate.io

  官网

Bitget

  官网

deepcoin

  官网
热门文章
  • 支付領域投下震撼彈!美國數位銀行Chime疑與GuardPay 神盾支付合作!

    支付領域投下震撼彈!美國數位銀行Chime疑與GuardPay 神盾支付合作!
    2020年,新冠肺炎(COVID-19)疫情加速數位貨幣進展。例如:2019年4月,國際清算銀行(BIS)的調查顯示,在全球66家中央銀行中,沒有一家計畫發行跨境支付的數位貨幣。惟到了2020年10月,BIS支付委員會主席康利夫(Jon Cunliffe)指出,肺炎疫情拉高民眾對無現金支付的需求,迫使各國加快數位貨幣的研發進程日本與韓國於2021年進入數位貨幣試驗階段。直到2019年12月,美國聯邦準備理事會(Fed)都尚無數位貨幣規劃,惟到了2020年2月,Fed已開始研擬...
  • 区块链:交易系统开发指南

    区块链:交易系统开发指南
    播报编辑《区块链:交易系统开发指南》使用通俗易懂的语言,从技术的角度详细介绍了区块链交易系统应有的功能架构及工作原理,让人们能够张开双臂轻松地拥抱区块链技术,享受区块链交易系统带来的惊喜与成就感。《区块链:交易系统开发指南》共分 7 章,第 1~2 章主要介绍区块链及数字货币的基本概念,以及各种公有链的 API 接口;第3~5 章主要介绍区块链交易系统的分类架构及功能; 6 章主要介绍区块链交易系统面临的问题及演进方向;第 7 章对全书做了总结。《区块链:交易系统开发指南》是...
  • 5.14加密货币价格:BTC突破6.2万美元以太坊和山寨币反映市场情绪

    5.14加密货币价格:BTC突破6.2万美元以太坊和山寨币反映市场情绪
    今天,随着比特币(BTC)的价格突破62 000美元的门槛,顶级加密货币的价格反弹了。 此外,以铁大幅上涨,维持在2 900美元的水平。 此外,其他顶尖山硬币,如索拉纳(SOL )、XRP、卡达诺(ADA )也大幅上涨。    今天密钥加密货币价格 1. 比特币价格    在5月14日星期二撰写本文时,比特币价格上升了2.57%,达到62 487.50美元。 另一方面,在过去24小时内,交易量从65.26 % 急剧上升至277亿美元。 与此同时,加密货币的市场价值为...
  • OKEx回应用户质疑:合约交易非期货 平台无机器人

    OKEx回应用户质疑:合约交易非期货 平台无机器人
       热点点 自选股份 数据中心 数据中心 研究和资料中心 资金流动 模拟交易 客户客户 具体来说,OKEx回答用户的问题:合同交易不是期货,平台不是机器人。 金融同步化,3月22日。    昨天下午,OKEx公司就维护先前用户线下的权利问题对同步财务公司作出了回应,指出OKEx公司提供的合同交易不是期货交易,在旗下的业务中没有正式的机器人。 同时,OKEX称,它不会以非法为由对任何投资损失索赔作出答复。 答复全文如下: 同步你的财务! 近日来,...
  • 0.00006694个比特币等于多少人民币/美金

    0.00006694个比特币等于多少人民币/美金
    0.00006694比特币等于多少人民币?根据比特币对人民币的最新汇率,0.00006694比特币等于4.53424784美元/32.5436 16人民币。比特币(BTC)美元(USDT)人民币(CNY)0.000066944.53424784【比特币密码】32.82795436 16比特币对人民币的最新汇率为:490408.64 CNY(1比特币=490408.64人民币)(1美元=7.24人民币)(0.00006694USDT=0.0004846456 CNY)汇率更新时...
标签列表