using System; using System.Linq; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; await using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True"); await connection.OpenAsync(); var options = new DbContextOptionsBuilder().UseSqlite(connection).Options; var factory = new Microsoft.EntityFrameworkCore.Infrastructure.PooledDbContextFactory(options, poolSize: 1); Guid firstInstance; await using (var first = await factory.CreateDbContextAsync()) { await first.Database.EnsureCreatedAsync(); first.Items.Add(new Item { Name = "rune" }); await first.SaveChangesAsync(); Check(first.ChangeTracker.Entries().Count() == 1, "first lease tracks entity"); first.CustomNote = "lease-one"; firstInstance = first.ContextId.InstanceId; } await using (var second = await factory.CreateDbContextAsync()) { Check(second.ContextId.InstanceId == firstInstance, "controlled sequential pool reuse"); Check(!second.ChangeTracker.Entries().Any(), "EF tracker reset"); Check(second.CustomNote == "lease-one", "custom field persists"); Check(await second.Items.CountAsync() == 1, "SQLite still shared through open connection"); Console.WriteLine("tracked-after-return:0"); Console.WriteLine("custom-field:" + second.CustomNote); second.CustomNote = ""; } static void Check(bool condition, string name) { if (!condition) throw new InvalidOperationException("CHECK: " + name); }