語言

DatabaseFacade.EnsureCreatedAsync(CancellationToken) 方法

定義

確保上下文的資料庫存在。

public virtual System.Threading.Tasks.Task<bool> EnsureCreatedAsync(System.Threading.CancellationToken cancellationToken = default);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Migrations operations require building the design-time model which is not supported with NativeAOT Use a migration bundle or an alternate way of executing migration operations.")]
public virtual System.Threading.Tasks.Task<bool> EnsureCreatedAsync(System.Threading.CancellationToken cancellationToken = default);
abstract member EnsureCreatedAsync : System.Threading.CancellationToken -> System.Threading.Tasks.Task<bool>
override this.EnsureCreatedAsync : System.Threading.CancellationToken -> System.Threading.Tasks.Task<bool>
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Migrations operations require building the design-time model which is not supported with NativeAOT Use a migration bundle or an alternate way of executing migration operations.")>]
abstract member EnsureCreatedAsync : System.Threading.CancellationToken -> System.Threading.Tasks.Task<bool>
override this.EnsureCreatedAsync : System.Threading.CancellationToken -> System.Threading.Tasks.Task<bool>
Public Overridable Function EnsureCreatedAsync (Optional cancellationToken As CancellationToken = Nothing) As Task(Of Boolean)

參數

cancellationToken
CancellationToken

A CancellationToken 在等待任務完成時觀察。

傳回

代表非同步儲存操作的任務。 任務結果會顯示 true 資料庫是否已建立,或 false 資料庫是否已存在。

屬性

例外狀況

備註

  • 如果資料庫存在且有任何資料表,則不會採取任何動作。 並未採取任何措施確保資料庫結構與實體框架模型相容。
  • 如果資料庫存在但沒有任何資料表,則會使用實體框架模型來建立資料庫結構。
  • 若資料庫不存在,則建立資料庫並使用實體框架模型建立資料庫結構。

在使用 Entity Framework 進行測試或原型設計時,通常會緊接EnsureDeletedAsync(CancellationToken)著使用EnsureCreatedAsync(CancellationToken)。 這確保資料庫在每次測試/原型執行前都處於乾淨狀態。 但請注意,資料庫中的資料並未被保存。

請注意,這個 API **不**使用遷移來建立資料庫。 此外,所建立的資料庫無法透過遷移功能進行後續更新。 如果你目標是關聯式資料庫並使用遷移,那麼你可以用來 Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.MigrateAsync 確保資料庫是透過遷移建立的,且所有遷移都已套用。

Entity Framework Core 不支援在同一個 DbContext 實例上執行多個平行操作。 這包括平行執行非同步查詢,以及明確同時使用多個執行緒。 因此,務必立即等待非同步呼叫,或使用獨立的 DbContext 實例來執行平行執行的操作。 更多資訊與範例請參見 「避免 DbContext 執行緒問題 」。

更多資訊與範例請參閱「使用 EF Core 管理資料庫結構」及「資料庫建立 API」。

適用於