Class DatabaseFacade
- Namespace
- Microsoft.EntityFrameworkCore.Infrastructure
- Assembly
- Microsoft.EntityFrameworkCore.dll
Provides access to database related information and operations for a context. Instances of this class are typically obtained from Database and it is not designed to be directly constructed in your application code.
public class DatabaseFacade : IInfrastructure<IServiceProvider>, IDatabaseFacadeDependenciesAccessor, IResettableService
- Inheritance
-
DatabaseFacade
- Implements
- Inherited Members
- Extension Methods
Constructors
DatabaseFacade(DbContext)
Initializes a new instance of the DatabaseFacade class. Instances of this class are typically obtained from Database and it is not designed to be directly constructed in your application code.
public DatabaseFacade(DbContext context)
Parameters
context
DbContextThe context this database API belongs to.
Properties
AutoSavepointsEnabled
Whether a transaction savepoint will be created automatically by SaveChanges() if it is called after a transaction has been manually started with BeginTransaction().
public virtual bool AutoSavepointsEnabled { get; set; }
Property Value
Remarks
The default value is true, meaning that SaveChanges() will create a transaction savepoint within a manually-started transaction. Regardless of this property, savepoints are only created if the data provider supports them; see SupportsSavepoints.
Setting this value to false should only be done with caution since the database could be left in a corrupted state if SaveChanges() fails.
See Transactions in EF Core for more information and examples.
AutoTransactionBehavior
Gets or sets a value indicating whether or not a transaction will be created automatically by SaveChanges() if neither 'BeginTransaction' nor 'UseTransaction' has been called.
public virtual AutoTransactionBehavior AutoTransactionBehavior { get; set; }
Property Value
Remarks
The default setting is WhenNeeded.
Setting this to Never with caution, since the database could be left in an inconsistent state if failure occurs.
See Transactions in EF Core for more information and examples.
AutoTransactionsEnabled
Gets or sets a value indicating whether or not a transaction will be created automatically by SaveChanges() if none of the 'BeginTransaction' or 'UseTransaction' methods have been called.
[Obsolete("Use AutoTransactionBehavior instead")]
public virtual bool AutoTransactionsEnabled { get; set; }
Property Value
Remarks
Setting this value to false will also disable the IExecutionStrategy for SaveChanges()
The default value is true, meaning that SaveChanges() will always use a transaction when saving changes.
Setting this value to false should only be done with caution, since the database could be left in an inconsistent state if failure occurs.
See Transactions in EF Core for more information and examples.
CurrentTransaction
Gets the current IDbContextTransaction being used by the context, or null if no transaction is in use.
public virtual IDbContextTransaction? CurrentTransaction { get; }
Property Value
Remarks
This property is null unless one of BeginTransaction(),
Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.BeginTransaction, or
For relational databases, the underlying System.Data.Common.DbTransaction can be obtained using Microsoft.EntityFrameworkCore.Storage.DbContextTransactionExtensions.GetDbTransaction on the returned IDbContextTransaction.
See Transactions in EF Core for more information and examples.
ProviderName
Returns the name of the database provider currently in use. The name is typically the name of the provider assembly. It is usually easier to use a sugar method such as Microsoft.EntityFrameworkCore.SqlServerDatabaseFacadeExtensions.IsSqlServer instead of calling this method directly.
public virtual string? ProviderName { get; }
Property Value
Remarks
This method can only be used after the DbContext has been configured because it is only then that the provider is known. This means that this method cannot be used in OnConfiguring(DbContextOptionsBuilder) because this is where application code sets the provider to use as part of configuring the context.
See DbContext lifetime, configuration, and initialization for more information and examples.
Methods
BeginTransaction()
Starts a new transaction.
public virtual IDbContextTransaction BeginTransaction()
Returns
- IDbContextTransaction
A IDbContextTransaction that represents the started transaction.
Remarks
See Transactions in EF Core for more information and examples.
BeginTransactionAsync(CancellationToken)
Asynchronously starts a new transaction.
public virtual Task<IDbContextTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenA CancellationToken to observe while waiting for the task to complete.
Returns
- Task<IDbContextTransaction>
A task that represents the asynchronous transaction initialization. The task result contains a IDbContextTransaction that represents the started transaction.
Remarks
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 Transactions in EF Core for more information and examples.
Exceptions
- OperationCanceledException
If the CancellationToken is canceled.
CanConnect()
Determines whether or not the database is available and can be connected to.
public virtual bool CanConnect()
Returns
Remarks
Any exceptions thrown when attempting to connect are caught and not propagated to the application.
The configured connection string is used to create the connection in the normal way, so all configured options such as timeouts are honored.
Note that being able to connect to the database does not mean that it is up-to-date with regard to schema creation, etc.
See Database connections in EF Core for more information and examples.
CanConnectAsync(CancellationToken)
Determines whether or not the database is available and can be connected to.
public virtual Task<bool> CanConnectAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenA CancellationToken to observe while waiting for the task to complete.
Returns
Remarks
Any exceptions thrown when attempting to connect are caught and not propagated to the application.
The configured connection string is used to create the connection in the normal way, so all configured options such as timeouts are honored.
Note that being able to connect to the database does not mean that it is up-to-date with regard to schema creation, etc.
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 Database connections in EF Core for more information and examples.
Exceptions
- OperationCanceledException
If the CancellationToken is canceled.
CommitTransaction()
Applies the outstanding operations in the current transaction to the database.
public virtual void CommitTransaction()
CommitTransactionAsync(CancellationToken)
Applies the outstanding operations in the current transaction to the database.
public virtual Task CommitTransactionAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenA CancellationToken to observe while waiting for the task to complete.
Returns
- Task
A Task representing the asynchronous operation.
Remarks
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 Transactions in EF Core for more information and examples.
Exceptions
- OperationCanceledException
If the CancellationToken is canceled.
CreateExecutionStrategy()
Creates an instance of the configured IExecutionStrategy.
public virtual IExecutionStrategy CreateExecutionStrategy()
Returns
- IExecutionStrategy
An IExecutionStrategy instance.
Remarks
See Connection resiliency and database retries for more information and examples.
EnsureCreated()
Ensures that the database for the context exists.
public virtual bool EnsureCreated()
Returns
Remarks
- 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 EnsureCreated() immediately following EnsureDeleted() 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.Migrate to ensure the database is created using migrations and that all migrations have been applied.
See Managing database schemas with EF Core and Database creation APIs for more information and examples.
EnsureCreatedAsync(CancellationToken)
Ensures that the database for the context exists.
public virtual Task<bool> EnsureCreatedAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenA CancellationToken to observe while waiting for the task to complete.
Returns
- Task<bool>
A task that represents the asynchronous save operation. The task result contains true if the database is created, false if it already existed.
Remarks
- 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.
Exceptions
- OperationCanceledException
If the CancellationToken is canceled.
EnsureDeleted()
Ensures that the database for the context does not exist. If it does not exist, no action is taken. If it does exist then the database is deleted.
Warning: The entire database is deleted, and no effort is made to remove just the database objects that are used by the model for this context.
public virtual bool EnsureDeleted()
Returns
Remarks
It is common to use EnsureCreated() immediately following EnsureDeleted() 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.
See Managing database schemas with EF Core and Database creation APIs for more information and examples.
EnsureDeletedAsync(CancellationToken)
Asynchronously ensures that the database for the context does not exist. If it does not exist, no action is taken. If it does exist then the database is deleted.
Warning: The entire database is deleted, and no effort is made to remove just the database objects that are used by the model for this context.
public virtual Task<bool> EnsureDeletedAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenA CancellationToken to observe while waiting for the task to complete.
Returns
- Task<bool>
A task that represents the asynchronous save operation. The task result contains true if the database is deleted, false if it did not exist.
Remarks
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.
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.
Exceptions
- OperationCanceledException
If the CancellationToken is canceled.
RollbackTransaction()
Discards the outstanding operations in the current transaction.
public virtual void RollbackTransaction()
Remarks
See Transactions in EF Core for more information and examples.
RollbackTransactionAsync(CancellationToken)
Discards the outstanding operations in the current transaction.
public virtual Task RollbackTransactionAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenA CancellationToken to observe while waiting for the task to complete.
Returns
- Task
A Task representing the asynchronous operation.
Remarks
See Transactions in EF Core for more information and examples.
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.
Exceptions
- OperationCanceledException
If the CancellationToken is canceled.