Facade. Ensure Created Async(CancellationToken) Method
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Ensures that the database for the context exists.
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>
Public Overridable Function EnsureCreatedAsync (Optional cancellationToken As CancellationToken = Nothing) As Task(Of Boolean)
A CancellationToken to observe while waiting for the task to complete.
A task that represents the asynchronous save operation. The task result contains
true if the database is created,
false if it already existed.
If the CancellationToken is canceled.
- If the database exists and has any tables, then no action is taken. Nothing is done to ensure the database schema is compatible with the Entity Framework model.
- If the database exists but does not have any tables, then the Entity Framework model is used to create the database schema.
- If the database does not exist, then the database is created and the Entity Framework model is used to create the database schema.
It is common to use EnsureCreatedAsync(CancellationToken) immediately following EnsureDeletedAsync(CancellationToken) when testing or prototyping using Entity Framework. This ensures that the database is in a clean state before each execution of the test/prototype. Note, however, that data in the database is not preserved.
Note that this API does **not** use migrations to create the database. In addition, the database that is created cannot be later updated using migrations. If you are targeting a relational database and using migrations, then you can use Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.MigrateAsync to ensure the database is created using migrations and that all migrations have been applied.
Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. This includes both parallel execution of async queries and any explicit concurrent use from multiple threads. Therefore, always await async calls immediately, or use separate DbContext instances for operations that execute in parallel. See Avoiding DbContext threading issues for more information and examples.
See Managing database schemas with EF Core and Database creation APIs for more information and examples.
Submit and view feedback for