├── .gitattributes ├── .gitignore ├── EntityFrameworkCore.TemporalTables.TestApp ├── DataContext.cs ├── DesignTimeDbContextFactory.cs ├── Entities │ ├── Role.cs │ └── User.cs ├── EntityFrameworkCore.TemporalTables.TestApp.csproj ├── Migrations │ ├── 20181002121553_InitialMigration.Designer.cs │ ├── 20181002121553_InitialMigration.cs │ └── DataContextModelSnapshot.cs ├── Program.cs └── appsettings.json ├── EntityFrameworkCore.TemporalTables.Tests ├── Cache │ └── TemporalEntitiesCacheTests.cs ├── EntityFrameworkCore.TemporalTables.Tests.csproj ├── Migrations │ └── TemporalTableMigratorTests.cs └── Mocks │ ├── DbContextOptionsSetup.cs │ ├── Entities │ └── User.cs │ ├── FakeDataContext.cs │ ├── FakeTableHelperNonTemporal.cs │ └── FakeTableHelperTemporal.cs ├── EntityFrameworkCore.TemporalTables.sln ├── EntityFrameworkCore.TemporalTables ├── Cache │ └── TemporalEntitiesCache.cs ├── EntityFrameworkCore.TemporalTables.csproj ├── Extensions │ ├── DbSetExtensions.cs │ ├── EntityTypeBuilderExtensions.cs │ ├── IServiceCollectionExtensions.cs │ └── ModelBuilderExtensions.cs ├── Migrations │ ├── ITemporalTableMigrator.cs │ ├── TemporalTableMigrator.cs │ ├── TemporalTableMigratorResolver.cs │ └── TemporalTablesMigrationsSqlGenerator.cs ├── Sql │ ├── Factory │ │ ├── ITemporalTableSqlGeneratorFactory.cs │ │ └── TemporalTableSqlGeneratorFactory.cs │ ├── Generation │ │ ├── BaseTemporalTableSqlGenerator.cs │ │ ├── CreateTemporalTableGenerator.cs │ │ ├── DropTemporalTableGenerator.cs │ │ ├── ITemporalTableSqlGenerator.cs │ │ └── NoSqlTemporalTableGenerator.cs │ ├── ISqlQueryExecutor.cs │ ├── ITemporalTableSqlBuilder.cs │ ├── ITemporalTableSqlExecutor.cs │ ├── SqlQueryExecutor.cs │ ├── Table │ │ ├── ITableHelper.cs │ │ └── TableHelper.cs │ ├── TemporalTableSqlBuilder.cs │ └── TemporalTableSqlExecutor.cs └── SqlTemplates │ ├── Constants.cs │ ├── Helpers │ └── SqlTemplateProcessor.cs │ ├── SqlTemplates.Designer.cs │ ├── SqlTemplates.resx │ └── Templates │ ├── CreateTemporalTable.sql │ ├── DropTemporalTable.sql │ └── IsDatabaseTableTemporal.sql ├── LICENSE.txt └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.TestApp/DataContext.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Extensions; 2 | using EntityFrameworkCore.TemporalTables.TestApp.Entities; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace EntityFrameworkCore.TemporalTables.TestApp 6 | { 7 | public class DataContext : DbContext 8 | { 9 | public DataContext(DbContextOptions options) 10 | : base(options) 11 | { 12 | } 13 | 14 | public DbSet Users { get; set; } 15 | 16 | public DbSet Roles { get; set; } 17 | 18 | protected override void OnModelCreating(ModelBuilder modelBuilder) 19 | { 20 | base.OnModelCreating(modelBuilder); 21 | 22 | modelBuilder.UseTemporalTables(); 23 | 24 | //modelBuilder.Entity(b => 25 | //{ 26 | // b.UseTemporalTable(); 27 | 28 | // b.HasData(new User 29 | // { 30 | // Id = 1, 31 | // UserName = "testUser", 32 | // Password = "testPassword", 33 | // IsDeleted = false 34 | // }); 35 | //}); 36 | 37 | modelBuilder.Entity(b => b.PreventTemporalTable()); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.TestApp/DesignTimeDbContextFactory.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Design; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using System.IO; 6 | using EntityFrameworkCore.TemporalTables.Extensions; 7 | 8 | namespace EntityFrameworkCore.TemporalTables.TestApp 9 | { 10 | public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory 11 | { 12 | public DataContext CreateDbContext(string[] args) 13 | { 14 | IConfigurationRoot configuration = new ConfigurationBuilder() 15 | .SetBasePath(Directory.GetCurrentDirectory()) 16 | .AddJsonFile("appsettings.json") 17 | .Build(); 18 | 19 | var builder = new DbContextOptionsBuilder(); 20 | var connectionString = configuration.GetConnectionString("DefaultConnection"); 21 | 22 | IServiceCollection services = new ServiceCollection(); 23 | 24 | services.AddDbContext((provider, options) => 25 | { 26 | options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")); 27 | options.UseInternalServiceProvider(provider); 28 | }); 29 | 30 | services.AddEntityFrameworkSqlServer(); 31 | services.RegisterTemporalTablesForDatabase(); 32 | 33 | var serviceProvider = services.BuildServiceProvider(); 34 | 35 | builder.UseSqlServer(connectionString); 36 | builder.UseInternalServiceProvider(serviceProvider); 37 | 38 | return serviceProvider.GetService(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.TestApp/Entities/Role.cs: -------------------------------------------------------------------------------- 1 | namespace EntityFrameworkCore.TemporalTables.TestApp.Entities 2 | { 3 | public class Role 4 | { 5 | public int Id { get; set; } 6 | 7 | public string Name { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.TestApp/Entities/User.cs: -------------------------------------------------------------------------------- 1 | namespace EntityFrameworkCore.TemporalTables.TestApp.Entities 2 | { 3 | public class User 4 | { 5 | public int Id { get; set; } 6 | 7 | public string UserName { get; set; } 8 | 9 | public string Password { get; set; } 10 | 11 | public bool IsDeleted { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.TestApp/EntityFrameworkCore.TemporalTables.TestApp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | PreserveNewest 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.TestApp/Migrations/20181002121553_InitialMigration.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using EntityFrameworkCore.TemporalTables.TestApp; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | namespace EntityFrameworkCore.TemporalTables.TestApp.Migrations 10 | { 11 | [DbContext(typeof(DataContext))] 12 | [Migration("20181002121553_InitialMigration")] 13 | partial class InitialMigration 14 | { 15 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 16 | { 17 | #pragma warning disable 612, 618 18 | modelBuilder 19 | .HasAnnotation("ProductVersion", "2.1.3-rtm-32065") 20 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 21 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 22 | 23 | modelBuilder.Entity("EntityFrameworkCore.TemporalTables.TestApp.Entities.Role", b => 24 | { 25 | b.Property("Id") 26 | .ValueGeneratedOnAdd() 27 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 28 | 29 | b.Property("Name"); 30 | 31 | b.HasKey("Id"); 32 | 33 | b.ToTable("Roles"); 34 | }); 35 | 36 | modelBuilder.Entity("EntityFrameworkCore.TemporalTables.TestApp.Entities.User", b => 37 | { 38 | b.Property("Id") 39 | .ValueGeneratedOnAdd() 40 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 41 | 42 | b.Property("IsDeleted"); 43 | 44 | b.Property("Password"); 45 | 46 | b.Property("UserName"); 47 | 48 | b.HasKey("Id"); 49 | 50 | b.ToTable("Users"); 51 | }); 52 | #pragma warning restore 612, 618 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.TestApp/Migrations/20181002121553_InitialMigration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Metadata; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | namespace EntityFrameworkCore.TemporalTables.TestApp.Migrations 5 | { 6 | public partial class InitialMigration : Migration 7 | { 8 | protected override void Up(MigrationBuilder migrationBuilder) 9 | { 10 | migrationBuilder.CreateTable( 11 | name: "Roles", 12 | columns: table => new 13 | { 14 | Id = table.Column(nullable: false) 15 | .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), 16 | Name = table.Column(nullable: true) 17 | }, 18 | constraints: table => 19 | { 20 | table.PrimaryKey("PK_Roles", x => x.Id); 21 | }); 22 | 23 | migrationBuilder.CreateTable( 24 | name: "Users", 25 | columns: table => new 26 | { 27 | Id = table.Column(nullable: false) 28 | .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), 29 | UserName = table.Column(nullable: true), 30 | Password = table.Column(nullable: true), 31 | IsDeleted = table.Column(nullable: false) 32 | }, 33 | constraints: table => 34 | { 35 | table.PrimaryKey("PK_Users", x => x.Id); 36 | }); 37 | } 38 | 39 | protected override void Down(MigrationBuilder migrationBuilder) 40 | { 41 | migrationBuilder.DropTable( 42 | name: "Roles"); 43 | 44 | migrationBuilder.DropTable( 45 | name: "Users"); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.TestApp/Migrations/DataContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using EntityFrameworkCore.TemporalTables.TestApp; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | 8 | namespace EntityFrameworkCore.TemporalTables.TestApp.Migrations 9 | { 10 | [DbContext(typeof(DataContext))] 11 | partial class DataContextModelSnapshot : ModelSnapshot 12 | { 13 | protected override void BuildModel(ModelBuilder modelBuilder) 14 | { 15 | #pragma warning disable 612, 618 16 | modelBuilder 17 | .HasAnnotation("ProductVersion", "2.1.3-rtm-32065") 18 | .HasAnnotation("Relational:MaxIdentifierLength", 128) 19 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 20 | 21 | modelBuilder.Entity("EntityFrameworkCore.TemporalTables.TestApp.Entities.Role", b => 22 | { 23 | b.Property("Id") 24 | .ValueGeneratedOnAdd() 25 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 26 | 27 | b.Property("Name"); 28 | 29 | b.HasKey("Id"); 30 | 31 | b.ToTable("Roles"); 32 | }); 33 | 34 | modelBuilder.Entity("EntityFrameworkCore.TemporalTables.TestApp.Entities.User", b => 35 | { 36 | b.Property("Id") 37 | .ValueGeneratedOnAdd() 38 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 39 | 40 | b.Property("IsDeleted"); 41 | 42 | b.Property("Password"); 43 | 44 | b.Property("UserName"); 45 | 46 | b.HasKey("Id"); 47 | 48 | b.ToTable("Users"); 49 | }); 50 | #pragma warning restore 612, 618 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.TestApp/Program.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Extensions; 2 | using EntityFrameworkCore.TemporalTables.Sql; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using System.IO; 7 | 8 | namespace EntityFrameworkCore.TemporalTables.TestApp 9 | { 10 | class Program 11 | { 12 | static void Main(string[] args) 13 | { 14 | IConfigurationRoot configuration = new ConfigurationBuilder() 15 | .SetBasePath(Directory.GetCurrentDirectory()) 16 | .AddJsonFile("appsettings.json") 17 | .Build(); 18 | 19 | IServiceCollection services = new ServiceCollection(); 20 | 21 | services.AddDbContextPool((provider, options) => 22 | { 23 | options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")); 24 | options.UseInternalServiceProvider(provider); 25 | }); 26 | 27 | services.AddEntityFrameworkSqlServer(); 28 | 29 | services.RegisterTemporalTablesForDatabase(); 30 | 31 | var serviceProvider = services 32 | .BuildServiceProvider(); 33 | 34 | var dbContext = serviceProvider.GetService(); 35 | 36 | // Update temporal tables automatically by calling Migrate() / MigrateAsync() or Update-Database from Package Manager Console. 37 | dbContext.Database.Migrate(); 38 | 39 | // Just generate the temporal tables SQL without executing it against the database. 40 | var temporalTableSqlBuilder = serviceProvider.GetService>(); 41 | string sql = temporalTableSqlBuilder.BuildTemporalTablesSql(); 42 | 43 | // Execute the temporal tables SQL code against the database (SQL code is generated internally without exposing to outside). 44 | var temporalTableSqlExecutor = serviceProvider.GetService>(); 45 | temporalTableSqlExecutor.Execute(); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.TestApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Server=.;Database=TemporalTablesDemoDatabase;Trusted_Connection=True;MultipleActiveResultSets=true" 4 | }, 5 | "Logging": { 6 | "LogLevel": { 7 | "Default": "Warning" 8 | } 9 | }, 10 | "AllowedHosts": "*" 11 | } 12 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.Tests/Cache/TemporalEntitiesCacheTests.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Cache; 2 | using EntityFrameworkCore.TemporalTables.Tests.Mocks; 3 | using EntityFrameworkCore.TemporalTables.Tests.Mocks.Entities; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | using System.Linq; 7 | 8 | namespace EntityFrameworkCore.TemporalTables.Tests.Cache 9 | { 10 | [TestClass] 11 | public class TemporalEntitiesCacheTests 12 | { 13 | [TestMethod] 14 | public void AddTemporalTableTest() 15 | { 16 | var options = DbContextOptionsSetup.Setup(); 17 | 18 | using (var context = new FakeDataContext(options)) 19 | { 20 | var entityType = context.Model.FindEntityType(typeof(User)); 21 | 22 | // Add entity type. 23 | TemporalEntitiesCache.Add(entityType); 24 | 25 | // Test if the entity type exists in the cache. 26 | Assert.IsTrue(TemporalEntitiesCache.IsEntityConfigurationTemporal(entityType)); 27 | } 28 | } 29 | 30 | [TestMethod] 31 | public void RemoveTemporalTableTest() 32 | { 33 | var options = DbContextOptionsSetup.Setup(); 34 | 35 | using (var context = new FakeDataContext(options)) 36 | { 37 | var entityType = context.Model.FindEntityType(typeof(User)); 38 | 39 | // Add entity type. 40 | TemporalEntitiesCache.Add(entityType); 41 | 42 | // Remove entity type. 43 | TemporalEntitiesCache.Remove(entityType); 44 | 45 | // Test if the entity type is actually removed. 46 | Assert.IsTrue(!TemporalEntitiesCache.IsEntityConfigurationTemporal(entityType)); 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.Tests/EntityFrameworkCore.TemporalTables.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | all 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.Tests/Migrations/TemporalTableMigratorTests.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Cache; 2 | using EntityFrameworkCore.TemporalTables.Extensions; 3 | using EntityFrameworkCore.TemporalTables.Sql; 4 | using EntityFrameworkCore.TemporalTables.Sql.Factory; 5 | using EntityFrameworkCore.TemporalTables.Sql.Table; 6 | using EntityFrameworkCore.TemporalTables.Tests.Mocks; 7 | using EntityFrameworkCore.TemporalTables.Tests.Mocks.Entities; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.VisualStudio.TestTools.UnitTesting; 10 | using System; 11 | using System.Linq; 12 | 13 | namespace EntityFrameworkCore.TemporalTables.Tests.Migrations 14 | { 15 | [TestClass] 16 | public class TemporalTableMigratorTests 17 | { 18 | [TestInitialize] 19 | public void Setup() 20 | { 21 | TemporalEntitiesCache.Clear(); 22 | } 23 | 24 | [TestMethod] 25 | public void TestIfCreateTemporalTableSqlWillBeGeneratedForUserIfTableConfigurationIsNotTemporal() 26 | { 27 | string temporalTableSql = GetTemporalTableSqlDependingOnIfTableIsTemporalOrNot( 28 | new FakeTableHelperNonTemporal(), 29 | typeof(User)); 30 | 31 | // Temporal table doesn't exists so create it 32 | Assert.IsTrue(temporalTableSql.StartsWith("IF NOT EXISTS")); 33 | } 34 | 35 | [TestMethod] 36 | public void TestIfEmptySqlWillBeGeneratedForUserIfTableConfigurationIsTemporal() 37 | { 38 | string temporalTableSql = GetTemporalTableSqlDependingOnIfTableIsTemporalOrNot( 39 | new FakeTableHelperTemporal(), 40 | typeof(User)); 41 | 42 | // Temporal table exists so no SQL code will be generated. 43 | Assert.IsTrue(string.IsNullOrWhiteSpace(temporalTableSql)); 44 | } 45 | 46 | [TestMethod] 47 | public void TestIfDropTemporalTableSqlWillBeGeneratedForUserIfTableConfigurationIsNotTemporal() 48 | { 49 | string temporalTableSql = GetTemporalTableSqlDependingOnIfTableIsTemporalOrNot( 50 | new FakeTableHelperTemporal()); 51 | 52 | // Temporal table exists but we don't want it, so drop it. 53 | Assert.IsTrue(temporalTableSql.StartsWith("IF EXISTS")); 54 | } 55 | 56 | [TestMethod] 57 | public void TestIfEmptySqlWillBeGeneratedForUserIfTableConfigurationIsNotTemporal() 58 | { 59 | string temporalTableSql = GetTemporalTableSqlDependingOnIfTableIsTemporalOrNot( 60 | new FakeTableHelperNonTemporal()); 61 | 62 | // Temporal table doesn't exist and we don't want it, so empty SQL should be generated. 63 | Assert.IsTrue(string.IsNullOrWhiteSpace(temporalTableSql)); 64 | } 65 | 66 | private string GetTemporalTableSqlDependingOnIfTableIsTemporalOrNot( 67 | ITableHelper tableHelper, 68 | params Type[] entityTypesToCreateTemporalTablesFor) where TEntity : class 69 | { 70 | var options = DbContextOptionsSetup.Setup(); 71 | 72 | using (var context = new FakeDataContext(options)) 73 | { 74 | // Register entity types to support temporal tables. 75 | entityTypesToCreateTemporalTablesFor 76 | ?.ToList() 77 | ?.ForEach(e => TemporalEntitiesCache.Add(context.Model.FindEntityType(e))); 78 | 79 | var entityType = context.Model.FindEntityType(typeof(TEntity)); 80 | 81 | var temporalTableSqlBuilder = new TemporalTableSqlBuilder( 82 | context, 83 | new TemporalTableSqlGeneratorFactory(), 84 | tableHelper); 85 | 86 | string sql = temporalTableSqlBuilder.BuildTemporalTablesSqlForEntityTypes(new[] { entityType }); 87 | 88 | return sql; 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.Tests/Mocks/DbContextOptionsSetup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace EntityFrameworkCore.TemporalTables.Tests.Mocks 4 | { 5 | public class DbContextOptionsSetup 6 | { 7 | public static DbContextOptions Setup() where TContext : DbContext 8 | { 9 | return new DbContextOptionsBuilder() 10 | .UseInMemoryDatabase(databaseName: "TemporalTablesDatabase") 11 | .Options; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.Tests/Mocks/Entities/User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace EntityFrameworkCore.TemporalTables.Tests.Mocks.Entities 6 | { 7 | public class User 8 | { 9 | public int Id { get; set; } 10 | 11 | public string UserName { get; set; } 12 | 13 | public string Password { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.Tests/Mocks/FakeDataContext.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Tests.Mocks.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using System; 4 | 5 | namespace EntityFrameworkCore.TemporalTables.Tests.Mocks 6 | { 7 | public class FakeDataContext : DbContext 8 | { 9 | public FakeDataContext(DbContextOptions options) 10 | : base(options) 11 | { 12 | } 13 | 14 | public DbSet Users { get; set; } 15 | 16 | protected override void OnModelCreating(ModelBuilder modelBuilder) 17 | { 18 | base.OnModelCreating(modelBuilder); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.Tests/Mocks/FakeTableHelperNonTemporal.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Sql.Table; 2 | 3 | namespace EntityFrameworkCore.TemporalTables.Tests.Mocks 4 | { 5 | public class FakeTableHelperNonTemporal : ITableHelper 6 | { 7 | public bool IsTableTemporal(string tableName, string schema = "dbo") => false; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.Tests/Mocks/FakeTableHelperTemporal.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Sql.Table; 2 | 3 | namespace EntityFrameworkCore.TemporalTables.Tests.Mocks 4 | { 5 | public class FakeTableHelperTemporal : ITableHelper 6 | { 7 | public bool IsTableTemporal(string tableName, string schema = "dbo") => true; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29728.190 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.TemporalTables", "EntityFrameworkCore.TemporalTables\EntityFrameworkCore.TemporalTables.csproj", "{DA5BA862-9D60-4C81-993C-FBDEC9CC0339}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.TemporalTables.TestApp", "EntityFrameworkCore.TemporalTables.TestApp\EntityFrameworkCore.TemporalTables.TestApp.csproj", "{A292790B-B872-4C43-820F-6B13DF78AEE2}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.TemporalTables.Tests", "EntityFrameworkCore.TemporalTables.Tests\EntityFrameworkCore.TemporalTables.Tests.csproj", "{70930D00-F249-4B91-B390-C2780651E0E3}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {DA5BA862-9D60-4C81-993C-FBDEC9CC0339}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {DA5BA862-9D60-4C81-993C-FBDEC9CC0339}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {DA5BA862-9D60-4C81-993C-FBDEC9CC0339}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {DA5BA862-9D60-4C81-993C-FBDEC9CC0339}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {A292790B-B872-4C43-820F-6B13DF78AEE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {A292790B-B872-4C43-820F-6B13DF78AEE2}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {A292790B-B872-4C43-820F-6B13DF78AEE2}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {A292790B-B872-4C43-820F-6B13DF78AEE2}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {70930D00-F249-4B91-B390-C2780651E0E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {70930D00-F249-4B91-B390-C2780651E0E3}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {70930D00-F249-4B91-B390-C2780651E0E3}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {70930D00-F249-4B91-B390-C2780651E0E3}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {42ADA7B8-B29A-46B7-A6C8-13FB615474BF} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Cache/TemporalEntitiesCache.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Metadata; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Runtime.CompilerServices; 6 | 7 | [assembly: InternalsVisibleTo("EntityFrameworkCore.TemporalTables.Tests")] 8 | namespace EntityFrameworkCore.TemporalTables.Cache 9 | { 10 | internal static class TemporalEntitiesCache 11 | { 12 | private static readonly ConcurrentDictionary addedTemporalEntities = new ConcurrentDictionary(); 13 | private static readonly ConcurrentDictionary removedTemporalEntities = new ConcurrentDictionary(); 14 | 15 | internal static void Add(IEntityType entityType) 16 | { 17 | if (addedTemporalEntities.TryAdd(entityType.Name, entityType)) 18 | { 19 | if (removedTemporalEntities.TryGetValue(entityType.Name, out IEntityType removedEntityType)) 20 | { 21 | removedTemporalEntities.TryRemove(entityType.Name, out removedEntityType); 22 | } 23 | } 24 | } 25 | 26 | internal static void Remove(IEntityType entityType) 27 | { 28 | if (removedTemporalEntities.TryAdd(entityType.Name, entityType)) 29 | { 30 | if (addedTemporalEntities.TryGetValue(entityType.Name, out IEntityType addedEntityType)) 31 | { 32 | addedTemporalEntities.TryRemove(entityType.Name, out addedEntityType); 33 | } 34 | } 35 | } 36 | 37 | internal static bool IsEntityConfigurationTemporal(IEntityType entityType) 38 | { 39 | return addedTemporalEntities.ContainsKey(entityType.Name) && !removedTemporalEntities.ContainsKey(entityType.Name); 40 | } 41 | 42 | internal static IReadOnlyList GetAll() 43 | { 44 | return addedTemporalEntities 45 | .Concat(removedTemporalEntities) 46 | .Select(e => e.Value) 47 | .ToList(); 48 | } 49 | 50 | internal static void Clear() 51 | { 52 | addedTemporalEntities.Clear(); 53 | removedTemporalEntities.Clear(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/EntityFrameworkCore.TemporalTables.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | true 6 | false 7 | George Findulov 8 | 9 | 1.1.1 10 | 1.1.1.0 11 | 1.1.1.0 12 | https://github.com/findulov/EntityFrameworkCore.TemporalTables 13 | git 14 | https://github.com/findulov/EntityFrameworkCore.TemporalTables 15 | Extension library for Entity Framework Core which allows developers who use SQL Server to easily use temporal tables. 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | all 34 | runtime; build; native; contentfiles; analyzers; buildtransitive 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | True 43 | True 44 | SqlTemplates.resx 45 | 46 | 47 | 48 | 49 | 50 | ResXFileCodeGenerator 51 | SqlTemplates.Designer.cs 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Extensions/DbSetExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using EntityFrameworkCore.TemporalTables.Cache; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | 8 | namespace EntityFrameworkCore.TemporalTables.Extensions 9 | { 10 | public static class DbSetExtensions 11 | { 12 | /// 13 | /// Filters the DbSet with entities at a given date and time. 14 | /// 15 | /// The type of the entity. 16 | /// The database set. 17 | /// The date. 18 | /// The entities represented at the specified time. 19 | public static IQueryable AsOf(this DbSet dbSet, DateTime date) 20 | where TEntity : class 21 | { 22 | ValidateDbSet(dbSet); 23 | 24 | var sql = FormattableString.Invariant($"SELECT * FROM [{GetTableName(dbSet)}] FOR SYSTEM_TIME AS OF {{0}}"); 25 | return dbSet.FromSqlRaw(sql, date).AsNoTracking(); 26 | } 27 | 28 | /// 29 | /// Filters the DbSet with entities at a given date and time. 30 | /// 31 | /// The type of the entity. 32 | /// The database set. 33 | /// The date time offset. 34 | /// The entities represented at the specified time. 35 | public static IQueryable AsOf(this DbSet dbSet, DateTimeOffset dateTimeOffset) 36 | where TEntity : class 37 | { 38 | ValidateDbSet(dbSet); 39 | 40 | var sql = FormattableString.Invariant($"SELECT * FROM [{GetTableName(dbSet)}] FOR SYSTEM_TIME AS OF {{0}}"); 41 | return dbSet.FromSqlRaw(sql, dateTimeOffset).AsNoTracking(); 42 | } 43 | 44 | /// 45 | /// Filters the DbSet with entities between the provided dates. 46 | /// 47 | /// The type of the entity. 48 | /// The database set. 49 | /// The start date. 50 | /// The end date. 51 | /// The entities found between the provided dates. 52 | /// The same entity might be returned more than once if it was modified 53 | /// during that time frame. 54 | public static IQueryable Between(this DbSet dbSet, DateTime startDate, DateTime endDate) 55 | where TEntity : class 56 | { 57 | ValidateDbSet(dbSet); 58 | 59 | var sql = FormattableString.Invariant($"SELECT * FROM [{GetTableName(dbSet)}] FOR SYSTEM_TIME BETWEEN {{0}} AND {{1}}"); 60 | return dbSet.FromSqlRaw(sql, startDate, endDate).AsNoTracking(); 61 | } 62 | 63 | /// 64 | /// Filters the DbSet with entities between the provided dates. 65 | /// 66 | /// The type of the entity. 67 | /// The database set. 68 | /// The start date time offset. 69 | /// The end date time offset. 70 | /// The entities found between the provided dates. 71 | /// The same entity might be returned more than once if it was modified 72 | /// during that time frame. 73 | public static IQueryable Between(this DbSet dbSet, DateTimeOffset startDateOffset, DateTimeOffset endDateOffset) 74 | where TEntity : class 75 | { 76 | ValidateDbSet(dbSet); 77 | 78 | var sql = FormattableString.Invariant($"SELECT * FROM [{GetTableName(dbSet)}] FOR SYSTEM_TIME BETWEEN {{0}} AND {{1}}"); 79 | return dbSet.FromSqlRaw(sql, startDateOffset, endDateOffset).AsNoTracking(); 80 | } 81 | 82 | /// 83 | /// Validates that temporal tables are enabled on the provided data set. 84 | /// 85 | /// The type of the entity. 86 | /// The database set. 87 | private static void ValidateDbSet(DbSet dbSet) 88 | where TEntity : class 89 | { 90 | var entityType = GetEntityType(dbSet); 91 | if (!TemporalEntitiesCache.IsEntityConfigurationTemporal(entityType)) 92 | { 93 | throw new ArgumentException(FormattableString.Invariant($"The entity '{entityType.DisplayName()}' is not using temporal tables."), nameof(dbSet)); 94 | } 95 | } 96 | 97 | /// 98 | /// Gets the name of the table for the provided DbSet. 99 | /// 100 | /// The type of the entity. 101 | /// The database set. 102 | /// The name of the table. 103 | private static string GetTableName(DbSet dbSet) 104 | where TEntity : class 105 | { 106 | var entityType = GetEntityType(dbSet); 107 | var tableNameAnnotation = entityType.GetAnnotation("Relational:TableName"); 108 | var tableName = tableNameAnnotation.Value.ToString(); 109 | return tableName; 110 | } 111 | 112 | /// 113 | /// Gets the type of the entity. 114 | /// 115 | /// The type of the entity. 116 | /// The database set. 117 | /// The entity type. 118 | private static IEntityType GetEntityType(DbSet dbSet) 119 | where TEntity : class 120 | { 121 | var dbContext = GetDbContext(dbSet); 122 | 123 | var model = dbContext.Model; 124 | var entityTypes = model.GetEntityTypes(); 125 | return entityTypes.First(t => t.ClrType == typeof(TEntity)); 126 | } 127 | 128 | /// 129 | /// Gets the database context. 130 | /// 131 | /// The type of the entity. 132 | /// The database set. 133 | /// The DbContext for the provided DbSet. 134 | private static DbContext GetDbContext(DbSet dbSet) 135 | where TEntity : class 136 | { 137 | var infrastructure = dbSet as IInfrastructure; 138 | var serviceProvider = infrastructure.Instance; 139 | var currentDbContext = serviceProvider.GetService(typeof(ICurrentDbContext)) as ICurrentDbContext; 140 | return currentDbContext.Context; 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Extensions/EntityTypeBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Cache; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | 4 | namespace EntityFrameworkCore.TemporalTables.Extensions 5 | { 6 | public static class EntityTypeBuilderExtensions 7 | { 8 | /// 9 | /// Configure temporal table for the specified entity type configuration. 10 | /// 11 | public static void UseTemporalTable(this EntityTypeBuilder entity) where TEntity : class 12 | { 13 | TemporalEntitiesCache.Add(entity.Metadata); 14 | } 15 | 16 | /// 17 | /// Configure not using a temporal table for the specified entity type configuration. 18 | /// 19 | public static void PreventTemporalTable(this EntityTypeBuilder entity) where TEntity : class 20 | { 21 | TemporalEntitiesCache.Remove(entity.Metadata); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Extensions/IServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Migrations; 2 | using EntityFrameworkCore.TemporalTables.Sql; 3 | using EntityFrameworkCore.TemporalTables.Sql.Factory; 4 | using EntityFrameworkCore.TemporalTables.Sql.Table; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Microsoft.Extensions.DependencyInjection.Extensions; 9 | 10 | namespace EntityFrameworkCore.TemporalTables.Extensions 11 | { 12 | public static class IServiceCollectionExtensions 13 | { 14 | /// 15 | /// Register temporal table services for the specified . 16 | /// 17 | public static IServiceCollection RegisterTemporalTablesForDatabase( 18 | this IServiceCollection services) 19 | where TContext : DbContext 20 | { 21 | services.AddScoped, SqlQueryExecutor>(); 22 | services.AddScoped, TableHelper>(); 23 | services.AddScoped, TemporalTableSqlBuilder>(); 24 | services.AddScoped, TemporalTableSqlExecutor>(); 25 | //services.AddScoped>(); //<-- with 2 temporal-DbContexts, an IMigrator gets registered twice, the second migrator takes precedence, so it is called by EF, even when the other Context is passed as the arg to the CLI tool 26 | services.AddScoped>(); 27 | services.AddScoped(); 28 | services.AddScoped>(); 29 | 30 | services.AddSingleton(); 31 | 32 | return services; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Extensions/ModelBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Cache; 2 | using Microsoft.EntityFrameworkCore; 3 | using System.Linq; 4 | 5 | namespace EntityFrameworkCore.TemporalTables.Extensions 6 | { 7 | public static class ModelBuilderExtensions 8 | { 9 | /// 10 | /// Configure all tables to be temporal by default. 11 | /// You may skip this method and register them manually by using method. 12 | /// 13 | public static void UseTemporalTables(this ModelBuilder modelBuilder) 14 | { 15 | var entityTypes = modelBuilder.Model.GetEntityTypes() 16 | .Where(e => !e.IsOwned()) 17 | .ToList(); 18 | 19 | foreach (var entityType in entityTypes) 20 | { 21 | TemporalEntitiesCache.Add(entityType); 22 | } 23 | } 24 | 25 | /// 26 | /// Configure none of the tables to be temporal by default. 27 | /// You can still register them manually by using method. 28 | /// 29 | public static void PreventTemporalTables(this ModelBuilder modelBuilder) 30 | { 31 | var entityTypes = modelBuilder.Model.GetEntityTypes() 32 | .Where(e => !e.IsOwned()) 33 | .ToList(); 34 | 35 | foreach (var entityType in entityTypes) 36 | { 37 | TemporalEntitiesCache.Remove(entityType); 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Migrations/ITemporalTableMigrator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Microsoft.EntityFrameworkCore.Migrations; 5 | 6 | namespace EntityFrameworkCore.TemporalTables.Migrations 7 | { 8 | public interface ITemporalTableMigrator : IMigrator 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Migrations/TemporalTableMigrator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using EntityFrameworkCore.TemporalTables.Sql; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Diagnostics; 7 | using Microsoft.EntityFrameworkCore.Infrastructure; 8 | using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; 9 | using Microsoft.EntityFrameworkCore.Migrations; 10 | using Microsoft.EntityFrameworkCore.Migrations.Internal; 11 | using Microsoft.EntityFrameworkCore.Storage; 12 | 13 | namespace EntityFrameworkCore.TemporalTables.Migrations 14 | { 15 | public class TemporalTableMigrator : Migrator, ITemporalTableMigrator 16 | where TContext : DbContext 17 | { 18 | private readonly ITemporalTableSqlExecutor temporalTableSqlExecutor; 19 | 20 | public TemporalTableMigrator( 21 | IMigrationsAssembly migrationsAssembly, 22 | IHistoryRepository historyRepository, 23 | IDatabaseCreator databaseCreator, 24 | IEnumerable migrationsSqlGenerators, 25 | IRawSqlCommandBuilder rawSqlCommandBuilder, 26 | IMigrationCommandExecutor migrationCommandExecutor, 27 | IRelationalConnection connection, 28 | ISqlGenerationHelper sqlGenerationHelper, 29 | ICurrentDbContext currentDbContext, 30 | IConventionSetBuilder conventionSetBuilder, 31 | IDiagnosticsLogger logger, 32 | IDiagnosticsLogger commandLogger, 33 | IDatabaseProvider databaseProvider, 34 | ITemporalTableSqlExecutor temporalTableSqlExecutor) 35 | : base(migrationsAssembly, historyRepository, databaseCreator, resolveMigrationsSqlGenerator(migrationsSqlGenerators), rawSqlCommandBuilder, migrationCommandExecutor, connection, sqlGenerationHelper, currentDbContext, conventionSetBuilder, logger, commandLogger, databaseProvider) 36 | { 37 | this.temporalTableSqlExecutor = temporalTableSqlExecutor; 38 | } 39 | 40 | private static IMigrationsSqlGenerator resolveMigrationsSqlGenerator(IEnumerable migrationsSqlGenerators) => migrationsSqlGenerators?.OfType>().LastOrDefault() ?? migrationsSqlGenerators?.LastOrDefault(); 41 | 42 | public override void Migrate(string targetMigration = null) 43 | { 44 | base.Migrate(targetMigration); 45 | 46 | temporalTableSqlExecutor.Execute(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Migrations/TemporalTableMigratorResolver.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Microsoft.EntityFrameworkCore.Infrastructure; 8 | using Microsoft.EntityFrameworkCore.Migrations; 9 | 10 | namespace EntityFrameworkCore.TemporalTables.Migrations 11 | { 12 | internal class TemporalTableMigratorResolver : IMigrator 13 | { 14 | private IMigrator CurrentTemporalTableMigrator { get; set; } 15 | 16 | private static Type ReflectiveTemporalTableManager(ICurrentDbContext currentDbContext) => typeof(TemporalTableMigrator<>).MakeGenericType(currentDbContext.Context.GetType()); 17 | 18 | public TemporalTableMigratorResolver(IEnumerable temporalTableMigrators, ICurrentDbContext currentDbContext) 19 | { 20 | CurrentTemporalTableMigrator = temporalTableMigrators.LastOrDefault(m => ReflectiveTemporalTableManager(currentDbContext).IsAssignableFrom(m.GetType())); 21 | } 22 | 23 | public string GenerateScript(string fromMigration = null, string toMigration = null, MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default) 24 | { 25 | return CurrentTemporalTableMigrator.GenerateScript(fromMigration, toMigration, options); 26 | } 27 | 28 | public void Migrate(string targetMigration = null) 29 | { 30 | CurrentTemporalTableMigrator.Migrate(targetMigration); 31 | } 32 | 33 | public async Task MigrateAsync(string targetMigration = null, CancellationToken cancellationToken = default) 34 | { 35 | await CurrentTemporalTableMigrator.MigrateAsync(targetMigration, cancellationToken); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Migrations/TemporalTablesMigrationsSqlGenerator.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Cache; 2 | using EntityFrameworkCore.TemporalTables.Sql.Factory; 3 | using EntityFrameworkCore.TemporalTables.Sql.Generation; 4 | using EntityFrameworkCore.TemporalTables.Sql.Table; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Migrations.Operations; 9 | 10 | namespace EntityFrameworkCore.TemporalTables.Migrations 11 | { 12 | public class TemporalTablesMigrationsSqlGenerator : SqlServerMigrationsSqlGenerator 13 | where TContext : DbContext 14 | { 15 | private readonly ITemporalTableSqlGeneratorFactory temporalTableSqlGeneratorFactory; 16 | private readonly ITableHelper tableHelper; 17 | 18 | public TemporalTablesMigrationsSqlGenerator( 19 | MigrationsSqlGeneratorDependencies dependencies, 20 | IRelationalAnnotationProvider migrationsAnnotations, 21 | ITemporalTableSqlGeneratorFactory temporalTableSqlGeneratorFactory, 22 | ITableHelper tableHelper) 23 | : base(dependencies, migrationsAnnotations) 24 | { 25 | this.temporalTableSqlGeneratorFactory = temporalTableSqlGeneratorFactory; 26 | this.tableHelper = tableHelper; 27 | } 28 | 29 | protected override void Generate(DropTableOperation operation, IModel model, MigrationCommandListBuilder builder, bool terminate = true) 30 | { 31 | string tableName = operation.Name; 32 | string schema = operation.Schema ?? "dbo"; 33 | 34 | bool isEntityTemporalInDatabase = tableHelper.IsTableTemporal(tableName, schema); 35 | 36 | if (isEntityTemporalInDatabase) 37 | { 38 | ITemporalTableSqlGenerator temporalTableSqlGenerator = new DropTemporalTableGenerator(tableName, schema); 39 | string temporalTableSql = temporalTableSqlGenerator.Generate(); 40 | 41 | builder.AppendLine(temporalTableSql); 42 | } 43 | 44 | base.Generate(operation, model, builder, terminate); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/Factory/ITemporalTableSqlGeneratorFactory.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Sql.Generation; 2 | 3 | namespace EntityFrameworkCore.TemporalTables.Sql.Factory 4 | { 5 | /// 6 | /// Factory used to create an innstance of . 7 | /// 8 | public interface ITemporalTableSqlGeneratorFactory 9 | { 10 | /// 11 | /// Creates an innstance of . 12 | /// 13 | /// Specifies if the entity is configured to be temporal. 14 | /// Specifies if the entity table is already temporal in the database. 15 | /// The table name. 16 | /// The schema name. 17 | /// 18 | ITemporalTableSqlGenerator CreateInstance( 19 | bool isEntityConfigurationTemporal, 20 | bool isEntityTemporalInDatabase, 21 | string tableName, 22 | string schemaName = "dbo"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/Factory/TemporalTableSqlGeneratorFactory.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Sql.Generation; 2 | using Microsoft.Extensions.Logging; 3 | 4 | namespace EntityFrameworkCore.TemporalTables.Sql.Factory 5 | { 6 | /// 7 | public class TemporalTableSqlGeneratorFactory : ITemporalTableSqlGeneratorFactory 8 | { 9 | /// 10 | public ITemporalTableSqlGenerator CreateInstance( 11 | bool isEntityConfigurationTemporal, 12 | bool isEntityTemporalInDatabase, 13 | string tableName, 14 | string schemaName) 15 | { 16 | ITemporalTableSqlGenerator temporalTableSqlGenerator = null; 17 | 18 | if (isEntityConfigurationTemporal && !isEntityTemporalInDatabase) 19 | { 20 | temporalTableSqlGenerator = new CreateTemporalTableGenerator(tableName, schemaName); 21 | } 22 | else if (!isEntityConfigurationTemporal && isEntityTemporalInDatabase) 23 | { 24 | temporalTableSqlGenerator = new DropTemporalTableGenerator(tableName, schemaName); 25 | } 26 | else 27 | { 28 | temporalTableSqlGenerator = new NoSqlTemporalTableGenerator(tableName, schemaName); 29 | } 30 | 31 | return temporalTableSqlGenerator; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/Generation/BaseTemporalTableSqlGenerator.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.SqlTemplates.Helpers; 2 | using System; 3 | 4 | namespace EntityFrameworkCore.TemporalTables.Sql.Generation 5 | { 6 | /// 7 | public abstract class BaseTemporalTableSqlGenerator : ITemporalTableSqlGenerator 8 | { 9 | protected string schemaName; 10 | 11 | protected string tableName; 12 | 13 | protected string TableWithSchema { get; } 14 | 15 | protected string HistoryTableName { get; } 16 | 17 | protected string SysTimeConstraint { get; } 18 | 19 | public BaseTemporalTableSqlGenerator(string tableName, string schemaName = "dbo") 20 | { 21 | this.tableName = tableName; 22 | this.schemaName = schemaName; 23 | 24 | if (string.IsNullOrWhiteSpace(tableName)) 25 | { 26 | throw new ArgumentNullException("Table name not initialized"); 27 | } 28 | 29 | TableWithSchema = $"[{schemaName}].[{tableName}]"; 30 | HistoryTableName = $"[{schemaName}].[{tableName}History]"; 31 | SysTimeConstraint = schemaName == "dbo" 32 | ? tableName 33 | : $"{schemaName}_{tableName}"; 34 | } 35 | 36 | public abstract string Generate(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/Generation/CreateTemporalTableGenerator.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.SqlTemplates; 2 | using EntityFrameworkCore.TemporalTables.SqlTemplates.Helpers; 3 | using System.Collections.Generic; 4 | 5 | namespace EntityFrameworkCore.TemporalTables.Sql.Generation 6 | { 7 | /// 8 | /// Generates a SQL code used to create a temporal table. 9 | /// 10 | public class CreateTemporalTableGenerator : BaseTemporalTableSqlGenerator 11 | { 12 | public CreateTemporalTableGenerator(string tableName, string schemaName) 13 | : base(tableName, schemaName) 14 | { 15 | } 16 | 17 | /// 18 | public override string Generate() 19 | { 20 | string sql = SqlTemplateProcessor.Process(SqlTemplates.SqlTemplates.CreateTemporalTable, 21 | new Dictionary 22 | { 23 | { Constants.TableWithSchemaPlaceholder, TableWithSchema }, 24 | { Constants.TableNamePlaceholder, tableName }, 25 | { Constants.HistoryTableNamePlaceholder, HistoryTableName }, 26 | { Constants.SystemTimeConstraintPlaceholder, SysTimeConstraint } 27 | }); 28 | 29 | return sql; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/Generation/DropTemporalTableGenerator.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.SqlTemplates; 2 | using EntityFrameworkCore.TemporalTables.SqlTemplates.Helpers; 3 | using System.Collections.Generic; 4 | 5 | namespace EntityFrameworkCore.TemporalTables.Sql.Generation 6 | { 7 | /// 8 | /// Generates a SQL code used to drop a temporal table. 9 | /// 10 | public class DropTemporalTableGenerator : BaseTemporalTableSqlGenerator 11 | { 12 | public DropTemporalTableGenerator(string tableName, string schemaName) 13 | : base(tableName, schemaName) 14 | { 15 | } 16 | 17 | public override string Generate() 18 | { 19 | string sql = SqlTemplateProcessor.Process(SqlTemplates.SqlTemplates.DropTemporalTable, 20 | new Dictionary 21 | { 22 | { Constants.TableWithSchemaPlaceholder, TableWithSchema }, 23 | { Constants.TableNamePlaceholder, tableName }, 24 | { Constants.HistoryTableNamePlaceholder, HistoryTableName }, 25 | { Constants.SystemTimeConstraintPlaceholder, SysTimeConstraint } 26 | }); 27 | 28 | return sql; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/Generation/ITemporalTableSqlGenerator.cs: -------------------------------------------------------------------------------- 1 | namespace EntityFrameworkCore.TemporalTables.Sql.Generation 2 | { 3 | /// 4 | /// Abstraction layer used to provide SQL generation for temporal tables. 5 | /// 6 | public interface ITemporalTableSqlGenerator 7 | { 8 | /// 9 | /// Generates the appropriate SQL code for temporal table. 10 | /// 11 | string Generate(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/Generation/NoSqlTemporalTableGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EntityFrameworkCore.TemporalTables.Sql.Generation 4 | { 5 | /// 6 | /// No real SQL code generation for temporal tables. Refer to the Null object pattern for more details. 7 | /// 8 | public class NoSqlTemporalTableGenerator : BaseTemporalTableSqlGenerator 9 | { 10 | public NoSqlTemporalTableGenerator(string tableName, string schemaName) 11 | : base(tableName, schemaName) 12 | { 13 | } 14 | 15 | public override string Generate() 16 | { 17 | return string.Empty; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/ISqlQueryExecutor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace EntityFrameworkCore.TemporalTables.Sql 4 | { 5 | /// 6 | /// Database SQL query execution wrapper around . 7 | /// 8 | public interface ISqlQueryExecutor 9 | where TContext : DbContext 10 | { 11 | /// 12 | /// Executes a raw SQL query. 13 | /// 14 | void ExecuteSqlQuery(string sql, bool useTransaction = false); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/ITemporalTableSqlBuilder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata; 3 | using System.Collections.Generic; 4 | 5 | namespace EntityFrameworkCore.TemporalTables.Sql 6 | { 7 | public interface ITemporalTableSqlBuilder 8 | where TContext : DbContext 9 | { 10 | /// 11 | /// Builds SQL code for temporal tables for the specified entity types based on their configuration. 12 | /// 13 | /// A collection of entity types to generate temporal table SQL code for. 14 | /// Whether to use a dashes separator indicator in the SQL code between the entity types. (---------) 15 | string BuildTemporalTablesSqlForEntityTypes(IEnumerable entityTypes, bool appendSeparator = true); 16 | 17 | /// 18 | /// Builds SQL code for temporal tables for all configured entity types. 19 | /// 20 | /// Whether to use a dashes separator indicator in the SQL code between the entity types. (---------) 21 | string BuildTemporalTablesSql(bool appendSeparator = true); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/ITemporalTableSqlExecutor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace EntityFrameworkCore.TemporalTables.Sql 4 | { 5 | /// 6 | /// Abstraction layer responsible for executing the SQL code for temporal tables. 7 | /// 8 | public interface ITemporalTableSqlExecutor 9 | where TContext : DbContext 10 | { 11 | /// 12 | /// Executes the SQL code for temporal tables. 13 | /// 14 | void Execute(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/SqlQueryExecutor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using System.Text; 3 | 4 | namespace EntityFrameworkCore.TemporalTables.Sql 5 | { 6 | public class SqlQueryExecutor : ISqlQueryExecutor 7 | where TContext : DbContext 8 | { 9 | private readonly TContext context; 10 | 11 | public SqlQueryExecutor(TContext context) 12 | { 13 | this.context = context; 14 | } 15 | 16 | public void ExecuteSqlQuery(string sql, bool useTransaction = false) 17 | { 18 | StringBuilder sqlBuilder = new StringBuilder(); 19 | 20 | if (useTransaction) 21 | { 22 | sqlBuilder.AppendLine("SET XACT_ABORT ON;"); 23 | sqlBuilder.AppendLine("BEGIN TRANSACTION;"); 24 | sqlBuilder.AppendLine(); 25 | 26 | sqlBuilder.AppendLine(sql); 27 | 28 | sqlBuilder.AppendLine("COMMIT;"); 29 | } 30 | else 31 | { 32 | sqlBuilder.AppendLine(sql); 33 | } 34 | 35 | context.Database.ExecuteSqlRaw(sqlBuilder.ToString()); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/Table/ITableHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace EntityFrameworkCore.TemporalTables.Sql.Table 4 | { 5 | public interface ITableHelper 6 | where TContext : DbContext 7 | { 8 | /// 9 | /// Checks if the relational table is temporal. 10 | /// 11 | bool IsTableTemporal(string tableName, string schema = "dbo"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/Table/TableHelper.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.SqlTemplates; 2 | using EntityFrameworkCore.TemporalTables.SqlTemplates.Helpers; 3 | using Microsoft.EntityFrameworkCore; 4 | using System.Collections.Generic; 5 | using System.Data; 6 | 7 | namespace EntityFrameworkCore.TemporalTables.Sql.Table 8 | { 9 | public class TableHelper : ITableHelper 10 | where TContext : DbContext 11 | { 12 | private readonly TContext context; 13 | 14 | public TableHelper(TContext context) 15 | { 16 | this.context = context; 17 | } 18 | 19 | public bool IsTableTemporal(string tableName, string schema = "dbo") 20 | { 21 | string sqlTemplateContent = SqlTemplateProcessor.Process(SqlTemplates.SqlTemplates.IsDatabaseTableTemporal, 22 | new Dictionary { { Constants.TableWithSchemaPlaceholder, $"{schema}.{tableName}" } }); 23 | 24 | int numberOfRowsAffected = -1; 25 | 26 | // Querying SELECT statements using the classic ADO.NET way until Entity Framework Core team provide a better way to query non-entity records. 27 | var connection = context.Database.GetDbConnection(); 28 | 29 | if (connection.State != ConnectionState.Open) 30 | { 31 | connection.Open(); 32 | } 33 | 34 | var command = connection.CreateCommand(); 35 | command.CommandText = sqlTemplateContent; 36 | 37 | var reader = command.ExecuteReader(); 38 | 39 | if (reader.Read()) 40 | { 41 | numberOfRowsAffected = reader.GetInt32(0); 42 | } 43 | 44 | if (connection.State == ConnectionState.Open) 45 | { 46 | connection.Close(); 47 | } 48 | 49 | return numberOfRowsAffected > 0; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/TemporalTableSqlBuilder.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Cache; 2 | using EntityFrameworkCore.TemporalTables.Sql.Factory; 3 | using EntityFrameworkCore.TemporalTables.Sql.Generation; 4 | using EntityFrameworkCore.TemporalTables.Sql.Table; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Text; 10 | 11 | namespace EntityFrameworkCore.TemporalTables.Sql 12 | { 13 | public class TemporalTableSqlBuilder : ITemporalTableSqlBuilder 14 | where TContext : DbContext 15 | { 16 | private readonly TContext context; 17 | private readonly ITemporalTableSqlGeneratorFactory temporalTableSqlGeneratorFactory; 18 | private readonly ITableHelper tableHelper; 19 | 20 | public TemporalTableSqlBuilder( 21 | TContext context, 22 | ITemporalTableSqlGeneratorFactory temporalTableSqlGeneratorFactory, 23 | ITableHelper tableHelper) 24 | { 25 | this.context = context; 26 | this.temporalTableSqlGeneratorFactory = temporalTableSqlGeneratorFactory; 27 | this.tableHelper = tableHelper; 28 | } 29 | 30 | /// 31 | public string BuildTemporalTablesSql(bool appendSeparator = true) 32 | { 33 | var entityTypes = EnsureTemporalEntitiesCacheIsInitialized(() => TemporalEntitiesCache.GetAll()); 34 | 35 | return BuildTemporalTablesSqlForEntityTypes(entityTypes); 36 | } 37 | 38 | /// 39 | public string BuildTemporalTablesSqlForEntityTypes(IEnumerable entityTypes, bool appendSeparator = true) 40 | { 41 | StringBuilder sqlBuilder = new StringBuilder(); 42 | 43 | foreach (var entityType in entityTypes) 44 | { 45 | string sql = BuildTemporalTableSqlFromEntityTypeConfiguration(entityType, appendSeparator); 46 | 47 | if (!string.IsNullOrWhiteSpace(sql)) 48 | { 49 | sqlBuilder.Append(sql); 50 | } 51 | } 52 | 53 | return sqlBuilder.ToString(); 54 | } 55 | 56 | private string BuildTemporalTableSqlFromEntityTypeConfiguration(IEntityType entityType, bool appendSeparator) 57 | { 58 | StringBuilder sqlBuilder = new StringBuilder(); 59 | 60 | var relationalEntityType = context.Model.FindEntityType(entityType.Name); 61 | if (relationalEntityType is IEntityType) 62 | { 63 | 64 | string tableName = relationalEntityType.GetTableName(); 65 | if (tableName is not null) // the above returns null if not mapped to a table (views) 66 | { 67 | string schema = relationalEntityType.GetSchema() ?? "dbo"; 68 | 69 | bool isEntityConfigurationTemporal = TemporalEntitiesCache.IsEntityConfigurationTemporal(entityType); 70 | bool isEntityTemporalInDatabase = tableHelper.IsTableTemporal(tableName, schema); 71 | 72 | ITemporalTableSqlGenerator temporalTableSqlGenerator = temporalTableSqlGeneratorFactory 73 | .CreateInstance(isEntityConfigurationTemporal, isEntityTemporalInDatabase, tableName, schema); 74 | 75 | string temporalTableSql = temporalTableSqlGenerator.Generate(); 76 | 77 | if (!string.IsNullOrWhiteSpace(temporalTableSql)) 78 | { 79 | sqlBuilder.AppendLine(temporalTableSql); 80 | 81 | if (appendSeparator) 82 | { 83 | sqlBuilder.AppendLine(new string('-', 100)); 84 | } 85 | } 86 | } 87 | } 88 | return sqlBuilder.ToString(); 89 | } 90 | 91 | private IReadOnlyList EnsureTemporalEntitiesCacheIsInitialized(Func> getEntityTypesFromCache) 92 | { 93 | // If OnModelCreating() method in the DbContext is not called yet, TemporalEntitiesCache will not be called 94 | // to cache the configuration for entity types and temporal tables SQL code will not be generated. 95 | // In such scenario, we just need to open a database connection manually to trigger OnModelCreating() and then close it. 96 | 97 | var entityTypes = getEntityTypesFromCache(); 98 | 99 | if (entityTypes.Count == 0) 100 | { 101 | context.Database.OpenConnection(); 102 | context.Database.CloseConnection(); 103 | 104 | entityTypes = getEntityTypesFromCache(); 105 | } 106 | 107 | return entityTypes; 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/Sql/TemporalTableSqlExecutor.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.TemporalTables.Cache; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata; 4 | using System; 5 | using System.Collections.Generic; 6 | 7 | namespace EntityFrameworkCore.TemporalTables.Sql 8 | { 9 | /// 10 | public class TemporalTableSqlExecutor : ITemporalTableSqlExecutor 11 | where TContext : DbContext 12 | { 13 | private readonly ISqlQueryExecutor sqlQueryExecutor; 14 | private readonly ITemporalTableSqlBuilder temporalTableSqlBuilder; 15 | 16 | public TemporalTableSqlExecutor( 17 | ISqlQueryExecutor sqlQueryExecutor, 18 | ITemporalTableSqlBuilder temporalTableSqlBuilder) 19 | { 20 | this.sqlQueryExecutor = sqlQueryExecutor; 21 | this.temporalTableSqlBuilder = temporalTableSqlBuilder; 22 | } 23 | 24 | /// 25 | public void Execute() 26 | { 27 | string sql = temporalTableSqlBuilder.BuildTemporalTablesSql(); 28 | 29 | if (!string.IsNullOrWhiteSpace(sql)) 30 | { 31 | sqlQueryExecutor.ExecuteSqlQuery(sql, useTransaction: true); 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/SqlTemplates/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace EntityFrameworkCore.TemporalTables.SqlTemplates 2 | { 3 | public class Constants 4 | { 5 | public const string TableWithSchemaPlaceholder = "{TABLE_WITH_SCHEMA}"; 6 | public const string TableNamePlaceholder = "{TABLE_NAME}"; 7 | public const string HistoryTableNamePlaceholder = "{HISTORY_TABLE_NAME}"; 8 | public const string SystemTimeConstraintPlaceholder = "{SYS_TIME_CONSTRAINT}"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/SqlTemplates/Helpers/SqlTemplateProcessor.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Text; 3 | 4 | namespace EntityFrameworkCore.TemporalTables.SqlTemplates.Helpers 5 | { 6 | internal static class SqlTemplateProcessor 7 | { 8 | /// 9 | /// Processes the specified SQL query by replacing placeholder values with the actual ones, provided in the passed dictionary. 10 | /// 11 | internal static string Process(string sqlQuery, IReadOnlyDictionary valuesToReplace) 12 | { 13 | StringBuilder sbSqlQuery = new StringBuilder(sqlQuery); 14 | 15 | foreach (var kvp in valuesToReplace) 16 | { 17 | sbSqlQuery = sbSqlQuery.Replace(kvp.Key, kvp.Value); 18 | } 19 | 20 | return sbSqlQuery.ToString(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/SqlTemplates/SqlTemplates.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace EntityFrameworkCore.TemporalTables.SqlTemplates { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class SqlTemplates { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal SqlTemplates() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("EntityFrameworkCore.TemporalTables.SqlTemplates.SqlTemplates", typeof(SqlTemplates).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | 63 | /// 64 | /// Looks up a localized string similar to IF NOT EXISTS -- if temporal table doesn't exist 65 | ///( 66 | /// SELECT 1 67 | /// FROM sys.tables 68 | /// WHERE object_id = OBJECT_ID('{TABLE_WITH_SCHEMA}', 'u') AND temporal_type = 2 69 | ///) 70 | ///BEGIN 71 | /// ALTER TABLE {TABLE_WITH_SCHEMA} 72 | /// ADD 73 | /// SysStartTime datetime2(0) GENERATED ALWAYS AS ROW START HIDDEN 74 | /// CONSTRAINT {TABLE_NAME}_DF_SysStart DEFAULT SYSUTCDATETIME() 75 | /// , SysEndTime datetime2(0) GENERATED ALWAYS AS ROW END HIDDEN 76 | /// CONSTRAINT {TABLE_NAME}_DF_SysEnd DEFAULT CONVE [rest of string was truncated]";. 77 | /// 78 | internal static string CreateTemporalTable { 79 | get { 80 | return ResourceManager.GetString("CreateTemporalTable", resourceCulture); 81 | } 82 | } 83 | 84 | /// 85 | /// Looks up a localized string similar to IF EXISTS-- if temporal table exists 86 | ///( 87 | /// SELECT 1 88 | /// FROM sys.tables 89 | /// WHERE object_id = OBJECT_ID('{TABLE_WITH_SCHEMA}', 'u') AND temporal_type = 2 90 | ///) 91 | ///BEGIN 92 | /// ALTER TABLE {TABLE_WITH_SCHEMA} SET (SYSTEM_VERSIONING = OFF); 93 | /// 94 | /// /* Optionally, DROP PERIOD if you want to revert temporal table to a non-temporal */ 95 | /// ALTER TABLE {TABLE_WITH_SCHEMA} 96 | /// DROP PERIOD FOR SYSTEM_TIME; 97 | /// 98 | /// ALTER TABLE {TABLE_WITH_SCHEMA} 99 | /// DROP COLUMN SysStartTime, SysEndTime; 100 | /// 101 | /// DROP TABLE {TABLE_WITH_SCHEMA}His [rest of string was truncated]";. 102 | /// 103 | internal static string DropTemporalTable { 104 | get { 105 | return ResourceManager.GetString("DropTemporalTable", resourceCulture); 106 | } 107 | } 108 | 109 | /// 110 | /// Looks up a localized string similar to SELECT 1 111 | ///FROM sys.tables 112 | ///WHERE object_id = OBJECT_ID('{TABLE_WITH_SCHEMA}', 'u') AND temporal_type = 2. 113 | /// 114 | internal static string IsDatabaseTableTemporal { 115 | get { 116 | return ResourceManager.GetString("IsDatabaseTableTemporal", resourceCulture); 117 | } 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/SqlTemplates/SqlTemplates.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 122 | Templates\CreateTemporalTable.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 123 | 124 | 125 | Templates\DropTemporalTable.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 126 | 127 | 128 | Templates\IsDatabaseTableTemporal.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 129 | 130 | -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/SqlTemplates/Templates/CreateTemporalTable.sql: -------------------------------------------------------------------------------- 1 | IF NOT EXISTS -- if temporal table doesn't exist 2 | ( 3 | SELECT 1 4 | FROM sys.tables 5 | WHERE object_id = OBJECT_ID('{TABLE_WITH_SCHEMA}', 'u') AND temporal_type = 2 6 | ) 7 | AND 8 | EXISTS -- if the base table exists 9 | ( 10 | SELECT 1 11 | FROM sys.tables 12 | WHERE object_id = OBJECT_ID('{TABLE_WITH_SCHEMA}', 'u') 13 | ) 14 | BEGIN 15 | ALTER TABLE {TABLE_WITH_SCHEMA} 16 | ADD 17 | SysStartTime datetime2(0) GENERATED ALWAYS AS ROW START HIDDEN 18 | CONSTRAINT {SYS_TIME_CONSTRAINT}_DF_SysStart DEFAULT DATEADD(SECOND, -10, SYSUTCDATETIME()) 19 | , SysEndTime datetime2(0) GENERATED ALWAYS AS ROW END HIDDEN 20 | CONSTRAINT {SYS_TIME_CONSTRAINT}_DF_SysEnd DEFAULT CONVERT(datetime2 (0), '9999-12-31 23:59:59'), 21 | PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime); 22 | 23 | ALTER TABLE {TABLE_WITH_SCHEMA} 24 | SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = {HISTORY_TABLE_NAME})); 25 | END -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/SqlTemplates/Templates/DropTemporalTable.sql: -------------------------------------------------------------------------------- 1 | IF EXISTS-- if temporal table exists 2 | ( 3 | SELECT 1 4 | FROM sys.tables 5 | WHERE object_id = OBJECT_ID('{TABLE_WITH_SCHEMA}', 'u') AND temporal_type = 2 6 | ) 7 | AND 8 | EXISTS -- if the base table exists 9 | ( 10 | SELECT 1 11 | FROM sys.tables 12 | WHERE object_id = OBJECT_ID('{TABLE_WITH_SCHEMA}', 'u') 13 | ) 14 | BEGIN 15 | ALTER TABLE {TABLE_WITH_SCHEMA} SET (SYSTEM_VERSIONING = OFF); 16 | 17 | /* Optionally, DROP PERIOD if you want to revert temporal table to a non-temporal */ 18 | ALTER TABLE {TABLE_WITH_SCHEMA} 19 | DROP PERIOD FOR SYSTEM_TIME; 20 | 21 | ALTER TABLE {TABLE_WITH_SCHEMA} 22 | DROP CONSTRAINT {SYS_TIME_CONSTRAINT}_DF_SysStart, {SYS_TIME_CONSTRAINT}_DF_SysEnd; 23 | 24 | ALTER TABLE {TABLE_WITH_SCHEMA} 25 | DROP COLUMN SysStartTime, SysEndTime; 26 | 27 | DROP TABLE {HISTORY_TABLE_NAME}; 28 | END -------------------------------------------------------------------------------- /EntityFrameworkCore.TemporalTables/SqlTemplates/Templates/IsDatabaseTableTemporal.sql: -------------------------------------------------------------------------------- 1 | SELECT 1 2 | FROM sys.tables 3 | WHERE object_id = OBJECT_ID('{TABLE_WITH_SCHEMA}', 'u') AND temporal_type = 2 -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 George Findulov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EntityFrameworkCore.TemporalTables 2 | Extension library for Entity Framework Core which allows developers who use SQL Server to easily use temporal tables. 3 | 4 | How to use it? 5 | 6 |

Service Provider configuration

7 | 8 | 1. Use ``UseInternalServiceProvider()`` on ``DbContextOptionsBuilder`` when registering your DbContext to replace Entity Framework's internal service provider with yours. For example: 9 | 10 | ``` 11 | services.AddDbContextPool((provider, options) => 12 | { 13 | options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")); 14 | options.UseInternalServiceProvider(provider); 15 | }); 16 | ``` 17 | 18 | 2. Then register all Entity Framework services into your service provider by using: 19 | ``services.AddEntityFrameworkSqlServer();`` 20 | 21 | 3. And finally call: 22 | ``services.RegisterTemporalTablesForDatabase();`` 23 | 24 | Use the first two settings only when you want your temporal tables to be executed by default when using ``Update-Database`` command from Package Manager Console or ``DbContext.Database.Migrate() / DbContext.Database.MigrateAsync()``. 25 | 26 | If you want to handle the temporal tables SQL execution yourself, you can do it manually by using: 27 | ``` 28 | var temporalTableSqlExecutor = serviceProvider.GetService>(); 29 | temporalTableSqlExecutor.Execute(); 30 | ``` 31 | 32 |
33 | 34 |

DbContext configuration

35 | 36 | In ``OnModelCreating(ModelBuilder modelBuilder)`` method you have the following options: 37 | 38 | * ``modelBuilder.UseTemporalTables()`` - create temporal table for all of your entities by default. 39 | * ``modelBuilder.PreventTemporalTables()`` - do not create temporal table for none of your entities by default. 40 | 41 | * ``modelBuilder.Entity(b => b.UseTemporalTable());`` - create a temporal table for the specified entity ``TEntity``. This method is compatible with ``UseTemporalTables()`` and ``PreventTemporalTables()`` methods - e.g. you can call ``PreventTemporalTables()`` and then only register the entities you want. 42 | * ``modelBuilder.Entity(b => b.PreventTemporalTable());`` - do not create a temporal table for the specified entity ``TEntity``. This method is also compatible with ``UseTemporalTables()`` and ``PreventTemporalTables()`` methods. 43 | 44 |
45 | You can refer to the sample application for more configuration information. 46 | 47 | You can install the NuGet package from here: https://www.nuget.org/packages/EntityFrameworkCore.TemporalTables/ 48 | --------------------------------------------------------------------------------