├── .github ├── dependabot.yml └── workflows │ ├── compilation.yml │ ├── PushToNuget.yml │ └── codeql-analysis.yml ├── LICENSE ├── src ├── EfCoreTemporalTable.csproj ├── EfCoreTemporalTable.sln └── TemporalExtensions.cs ├── README.md └── .gitignore /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: nuget 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "04:00" 8 | open-pull-requests-limit: 10 9 | ignore: 10 | - dependency-name: Microsoft.EntityFrameworkCore 11 | versions: 12 | - 5.0.3 13 | - 5.0.4 14 | - dependency-name: Microsoft.EntityFrameworkCore.Relational 15 | versions: 16 | - 5.0.3 17 | - 5.0.4 18 | -------------------------------------------------------------------------------- /.github/workflows/compilation.yml: -------------------------------------------------------------------------------- 1 | name: Compilation 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Setup .NET 17 | uses: actions/setup-dotnet@v1 18 | with: 19 | dotnet-version: 5.0.x 20 | - name: Build 21 | run: dotnet build src/EfCoreTemporalTable.sln 22 | - name: Unit Tests 23 | run: dotnet test src/EfCoreTemporalTable.sln 24 | -------------------------------------------------------------------------------- /.github/workflows/PushToNuget.yml: -------------------------------------------------------------------------------- 1 | name: NuGet Package Deploy 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v1 13 | - name: Setup .NET Core 14 | uses: actions/setup-dotnet@v1 15 | with: 16 | dotnet-version: 5.0.x 17 | - name: Build 18 | run: dotnet build src/EfCoreTemporalTable.sln --configuration Release 19 | - name: Unit Tests 20 | run: dotnet test src/EfCoreTemporalTable.sln 21 | - name: Build NuGet Package 22 | run: dotnet pack ./src/EfCoreTemporalTable.csproj --configuration Release -o NuGetPackages 23 | - name: Deploy NuGet Package 24 | run: dotnet nuget push ./NuGetPackages/EfCoreTemporalTable.1.0.5.nupkg -k ${{ secrets.NUGET_DEPLOY_KEY }} -s https://api.nuget.org/v3/index.json 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 glautrou 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 | -------------------------------------------------------------------------------- /src/EfCoreTemporalTable.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | true 6 | Gilles Lautrou 7 | Webnet 8 | Easily perform temporal queries on your favourite database by using Entity Framework Core 9 | temporal,sql,efcore 10 | 11 | 12 | 13 | true 14 | snupkg 15 | https://github.com/glautrou/EfCoreTemporalTable 16 | https://remixjobs-cache.s3-eu-west-1.amazonaws.com/1600x1200_thumbnail/1562574147-2a3818c7ef8893c42a11319a3501837b.jpeg 17 | https://github.com/glautrou/EfCoreTemporalTable 18 | 1.0.5.0 19 | 1.0.5.0 20 | 1.0.5 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/EfCoreTemporalTable.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29424.173 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EfCoreTemporalTable", "EfCoreTemporalTable.csproj", "{FEDC6C2C-48ED-4C3B-A696-3DC8CDFA3600}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{EC326EB8-DFE7-47D6-A29E-3302D6109D76}" 9 | ProjectSection(SolutionItems) = preProject 10 | ..\.github\workflows\codeql-analysis.yml = ..\.github\workflows\codeql-analysis.yml 11 | ..\.github\workflows\compilation.yml = ..\.github\workflows\compilation.yml 12 | ..\.github\workflows\PushToNuget.yml = ..\.github\workflows\PushToNuget.yml 13 | EndProjectSection 14 | EndProject 15 | Global 16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 17 | Debug|Any CPU = Debug|Any CPU 18 | Release|Any CPU = Release|Any CPU 19 | EndGlobalSection 20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 21 | {FEDC6C2C-48ED-4C3B-A696-3DC8CDFA3600}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {FEDC6C2C-48ED-4C3B-A696-3DC8CDFA3600}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {FEDC6C2C-48ED-4C3B-A696-3DC8CDFA3600}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {FEDC6C2C-48ED-4C3B-A696-3DC8CDFA3600}.Release|Any CPU.Build.0 = Release|Any CPU 25 | EndGlobalSection 26 | GlobalSection(SolutionProperties) = preSolution 27 | HideSolutionNode = FALSE 28 | EndGlobalSection 29 | GlobalSection(ExtensibilityGlobals) = postSolution 30 | SolutionGuid = {7DA8D0ED-DADF-49E8-A08E-E45777749C80} 31 | EndGlobalSection 32 | EndGlobal 33 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ master ] 20 | schedule: 21 | - cron: '42 7 * * 2' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | 28 | strategy: 29 | fail-fast: false 30 | matrix: 31 | language: [ 'csharp' ] 32 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 33 | # Learn more: 34 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 35 | 36 | steps: 37 | - name: Checkout repository 38 | uses: actions/checkout@v2 39 | 40 | # Initializes the CodeQL tools for scanning. 41 | - name: Initialize CodeQL 42 | uses: github/codeql-action/init@v1 43 | with: 44 | languages: ${{ matrix.language }} 45 | # If you wish to specify custom queries, you can do so here or in a config file. 46 | # By default, queries listed here will override any specified in a config file. 47 | # Prefix the list here with "+" to use these queries and those in the config file. 48 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 49 | 50 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 51 | # If this step fails, then you should remove it and run the build manually (see below) 52 | - name: Autobuild 53 | uses: github/codeql-action/autobuild@v1 54 | 55 | # ℹ️ Command-line programs to run using the OS shell. 56 | # 📚 https://git.io/JvXDl 57 | 58 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 59 | # and modify them (or add more) to build your code if your project 60 | # uses a compiled language 61 | 62 | # - run: | 63 | # make bootstrap 64 | # make release 65 | 66 | - name: Setup .NET Core 67 | uses: actions/setup-dotnet@v1 68 | with: 69 | dotnet-version: 5.0.x 70 | 71 | - name: Build 72 | run: dotnet build src/EfCoreTemporalTable.sln --configuration Release 73 | 74 | - name: Perform CodeQL Analysis 75 | uses: github/codeql-action/analyze@v1 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Easily perform **temporal queries** with **EF Core** 2 | 3 | Available on NuGet: ![latest version](https://img.shields.io/nuget/v/EfCoreTemporalTable) 4 | 5 | | :exclamation::exclamation::exclamation: IMPORTANT - EF Core 6 users :exclamation::exclamation::exclamation: | 6 | | ----------- | 7 | | If your project is targeting EF Core 6+ you may not need this extension, please read [the Microsoft blog post announcement](https://devblogs.microsoft.com/dotnet/prime-your-flux-capacitor-sql-server-temporal-tables-in-ef-core-6-0/) | 8 | | If you want help how to use it with EF Core 6, you can find [a sample](https://github.com/glautrou/EfCoreTemporalTablePart3/blob/master/README.md) and [associated tutorial](https://blog.webnet.fr/les-tables-temporelles-partie-3-utilisation-avec-entity-framework-core-6/) | 9 | 10 | ## Give a Star! :star: 11 | 12 | If you like or are using this NuGet extension, please give it a star. Thanks! 13 | 14 | ## Table of Contents 15 | 16 | [1. Overview](#1-overview) 17 | 18 | [2. Dependencies](#2-dependencies) 19 | 20 | [3. Installation](#3-installation) 21 | 22 | [4. Usage](#4-usage) 23 | 24 | ### 1. Overview 25 | There is no way querying temporal tables with Entity Framework Core except writing boring SQL code and executing raw queries. 26 | This package allows you to easily query your historic data and mix it with Entity Framework Core in an intuitive way. 27 | 28 | All temporal criterias are supported and it works with all databases supported by EF Core and all operating systems supported by .NET Core (Windows/MacOS/Linux). 29 | 30 | ### 2. Dependencies 31 | - NETStandard 2.0 32 | - Microsoft.EntityFrameworkCore >= 5.0.2 33 | - Microsoft.EntityFrameworkCore.Relational >= 5.0.2 34 | 35 | (EF Core [2.x](https://github.com/glautrou/EfCoreTemporalTable/tree/gilles/ef-core-2-support) or [3.x](https://github.com/glautrou/EfCoreTemporalTable/tree/gilles/ef-core-3-support) support) 36 | 37 | ### 3. Installation 38 | There are two ways to install the package: 39 | - via Visual Studio : Right Click on project > Manage NuGet packages > Search for "EfCoreTemporalTable" > Install 40 | - via command line: `dotnet add package EfCoreTemporalTable` 41 | 42 | ### 4. Usage 43 | You can use it with your existing EF Core DbContext/DbSet. 44 | On top of your file, add `using EfCoreTemporalTable;` 45 | 46 | On your DbSet properties you now get the following extension methods: 47 | - AsTemporalAll() 48 | - AsTemporalAsOf(date) 49 | - AsTemporalFrom(startDate, endDate) 50 | - AsTemporalBetween(startDate, endDate) 51 | - AsTemporalContained(startDate, endDate) 52 | 53 | Those methods return an `IQueryable`, meaning the execution is deferred and you can mix it with your usual EF Core and cutom methods. 54 | 55 | For example, if you want to get all employees named "Lautrou" at the time of yesterday, and their company at that time but with up-to-date information: 56 | 57 | ```csharp 58 | var result = myDbContext.Employees 59 | .AsTemporalOf(DateTime.UtcNow.AddDays(-1)) 60 | .Include(i=> i.Company) 61 | .FirstOrDefault(i => i.Name == "Lautrou"); 62 | ``` 63 | 64 | The generated SQL query will be: 65 | 66 | ```sql 67 | exec sp_executesql N'SELECT TOP(1) [e].[Id], [e].[CompanyId], [e].[Lastname], [e].[Firstname], [c].[Id], [c].[Name] 68 | FROM ( 69 | SELECT * FROM [dbo].[Employee] FOR SYSTEM_TIME AS OF @p0 70 | ) AS [e] 71 | INNER JOIN [Company] AS [c] ON [e].[CompanyId] = [c].[Id] 72 | WHERE [e].[Lastname] = N''Lautrou''',N'@p0 datetime2(7)',@p0='2019-11-27 17:26:10.1256588' 73 | ``` 74 | 75 | As you can see the SQL query is clean and the temporal parameter is a `DbParameter` (and not inlined). 76 | 77 | You can of course join temporal tables, and write your C# in the way you want: 78 | 79 | ```csharp 80 | var employees = from employee in db.Employees.AsTemporalOf(date) 81 | join company in db.Entreprise.AsTemporalOf(date) on employee.CompanyId equals company.Id 82 | select new 83 | { 84 | Employee = employee, 85 | Company = company 86 | }; 87 | ``` 88 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /src/TemporalExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Infrastructure; 3 | using System; 4 | using System.Linq; 5 | using System.Runtime.CompilerServices; 6 | 7 | namespace EfCoreTemporalTable 8 | { 9 | /// 10 | /// Temporal table extensions 11 | /// 12 | public static class TemporalExtensions 13 | { 14 | #region Public 15 | 16 | /// 17 | /// Returns the union of rows that belong to the current and the history table. 18 | /// 19 | /// Entity type 20 | /// Data set 21 | /// Temporal data 22 | public static IQueryable AsTemporalAll(this DbSet dbSet) where T : class 23 | { 24 | return dbSet.AsTemporal("ALL"); 25 | } 26 | 27 | /// 28 | /// Returns a table with a rows containing the values that were actual (current) at the 29 | /// specified point in time in the past. Internally, a union is performed between the 30 | /// temporal table and its history table and the results are filtered to return the 31 | /// values in the row that was valid at the point in time specified by the 32 | /// parameter. The value for a row is deemed valid if the system_start_time_column_name 33 | /// value is less than or equal to the parameter value and the 34 | /// system_end_time_column_name value is greater than the parameter value. 35 | /// 36 | /// Entity type 37 | /// Data set 38 | /// Exact date 39 | /// 40 | public static IQueryable AsTemporalAsOf(this DbSet dbSet, DateTime date) where T : class 41 | { 42 | return dbSet.AsTemporal("AS OF {0}", date.ToUniversalTime()); 43 | } 44 | 45 | /// 46 | /// Returns a table with the values for all row versions that were active within the 47 | /// specified time range, regardless of whether they started being active before the 48 | /// parameter value for the FROM argument or ceased being active after 49 | /// the parameter value for the TO argument. Internally, a union is 50 | /// performed between the temporal table and its history table and the results are 51 | /// filtered to return the values for all row versions that were active at any time 52 | /// during the time range specified. Rows that ceased being active exactly on the lower 53 | /// boundary defined by the FROM endpoint are not included and records that became active 54 | /// exactly on the upper boundary defined by the TO endpoint are not included also. 55 | /// 56 | /// Entity type 57 | /// Data set 58 | /// Start date 59 | /// End date 60 | /// Temporal data 61 | public static IQueryable AsTemporalFrom(this DbSet dbSet, DateTime startDate, DateTime endDate) where T : class 62 | { 63 | return dbSet.AsTemporal("FROM {0} TO {1}", startDate.ToUniversalTime(), endDate.ToUniversalTime()); 64 | } 65 | 66 | /// 67 | /// Same as above in the FOR SYSTEM_TIME FROM TO 68 | /// description, except the table of rows returned includes rows that became active on 69 | /// the upper boundary defined by the endpoint. 70 | /// 71 | /// Entity type 72 | /// Data set 73 | /// Start date 74 | /// End date 75 | /// Temporal data 76 | public static IQueryable AsTemporalBetween(this DbSet dbSet, DateTime startDate, DateTime endDate) where T : class 77 | { 78 | return dbSet.AsTemporal("BETWEEN {0} AND {1}", startDate.ToUniversalTime(), endDate.ToUniversalTime()); 79 | } 80 | 81 | /// 82 | /// Returns a table with the values for all row versions that were opened and closed 83 | /// within the specified time range defined by the two datetime values for the CONTAINED 84 | /// IN argument. Rows that became active exactly on the lower boundary or ceased being 85 | /// active exactly on the upper boundary are included. 86 | /// 87 | /// Entity type 88 | /// Data set 89 | /// Start date 90 | /// End date 91 | /// Temporal data 92 | public static IQueryable AsTemporalContained(this DbSet dbSet, DateTime startDate, DateTime endDate) where T : class 93 | { 94 | return dbSet.AsTemporal("CONTAINED IN ({0}, {1})", startDate.ToUniversalTime(), endDate.ToUniversalTime()); 95 | } 96 | 97 | #endregion 98 | 99 | #region Private 100 | 101 | /// 102 | /// Get temporal data 103 | /// 104 | /// Entity type 105 | /// Data set 106 | /// Temporal criteria of the SQL query 107 | /// Temporal SQL arguments 108 | /// Temporal data 109 | private static IQueryable AsTemporal(this DbSet dbSet, string temporalCriteria, params object[] arguments) where T : class 110 | { 111 | var table = dbSet 112 | .GetService() 113 | .GetTableName(); 114 | var selectSql = $"SELECT * FROM {table}"; 115 | var sql = FormattableStringFactory.Create(selectSql + " FOR SYSTEM_TIME " + temporalCriteria, arguments); 116 | return dbSet.FromSqlInterpolated(sql).AsNoTracking(); 117 | } 118 | 119 | /// 120 | /// Get the specified entity type SQL column full name 121 | /// 122 | /// Entity type 123 | /// Database context 124 | /// Full name of the table 125 | private static string GetTableName(this ICurrentDbContext dbContext) where T : class 126 | { 127 | var entityType = dbContext.Context.Model.FindEntityType(typeof(T)); 128 | var schema = entityType.GetSchema().GetSqlSafeName(); 129 | var table = entityType.GetTableName().GetSqlSafeName(); 130 | 131 | return string.IsNullOrEmpty(schema) 132 | ? table 133 | : string.Join(".", schema, table); 134 | } 135 | 136 | /// 137 | /// Get a safe SQL name for specified text. 138 | /// For example User will returns [User] 139 | /// 140 | /// SQL name 141 | /// Safe SQL name 142 | private static string GetSqlSafeName(this string sqlName) 143 | { 144 | return string.IsNullOrEmpty(sqlName) 145 | ? string.Empty 146 | : $"[{sqlName}]"; 147 | } 148 | 149 | #endregion 150 | 151 | } 152 | } 153 | --------------------------------------------------------------------------------