65 lines
2.1 KiB
C#
65 lines
2.1 KiB
C#
using GerstITS.Data.EntityFramework;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
namespace GerstITS.Examples.Transactions.Migrations;
|
|
|
|
/// <summary>
|
|
/// Configures <see cref="ProductDbContext" /> to use a self-contained SQLite in-memory database.
|
|
///
|
|
/// SQLite is a RELATIONAL provider and therefore supports real ACID transactions, which is what the
|
|
/// transaction example needs to show an atomic rollback that actually discards partial work.
|
|
///
|
|
/// The EF Core InMemory provider (<c>UseInMemoryDatabase</c>) is deliberately NOT used here: it does
|
|
/// not support transactions at all - <c>Database.BeginTransaction()</c> raises the
|
|
/// <c>TransactionIgnoredWarning</c> - so it cannot demonstrate an atomic rollback. In production the
|
|
/// same code runs unchanged against PostgreSQL or SQL Server.
|
|
///
|
|
/// A single <see cref="SqliteConnection" /> is opened and kept open for the lifetime of the process so
|
|
/// the in-memory database is shared across every <see cref="ProductDbContext" /> instance (an in-memory
|
|
/// SQLite database only lives as long as its connection is open).
|
|
/// </summary>
|
|
public sealed class SqliteInMemoryDatabaseConfigurator : DatabaseConfiguratorBase, IDisposable
|
|
{
|
|
#region Fields
|
|
|
|
private readonly SqliteConnection _connection;
|
|
|
|
#endregion
|
|
|
|
#region Constructors
|
|
|
|
public SqliteInMemoryDatabaseConfigurator(IConfiguration configuration)
|
|
: base(configuration)
|
|
{
|
|
_connection = new SqliteConnection("DataSource=:memory:");
|
|
_connection.Open();
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region DatabaseConfiguratorBase
|
|
|
|
public override void ConfigureModelCreating(ModelBuilder modelBuilder)
|
|
{
|
|
// No relational-specific mapping is required; ProductEntity is mapped by convention.
|
|
}
|
|
|
|
protected override void ConfigureDatabase(DbContextOptionsBuilder optionsBuilder, string connectionString)
|
|
{
|
|
optionsBuilder.UseSqlite(_connection);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region IDisposable
|
|
|
|
public void Dispose()
|
|
{
|
|
_connection.Dispose();
|
|
}
|
|
|
|
#endregion
|
|
}
|