├── .gitignore ├── LICENSE ├── README.md ├── build ├── NuGet_clean.ps1 └── NuGet_push.ps1 └── src └── EntityFrameworkCore.Parallel ├── EntityFrameworkCore.Parallel.DemoModel ├── Detail.cs ├── EntityBase.cs ├── EntityFrameworkCore.Parallel.DemoModel.csproj ├── Order.cs └── OrderContext.cs ├── EntityFrameworkCore.Parallel.Tests ├── CastExtensionTests.cs ├── DatabaseTests.cs ├── EntityFrameworkCore.Parallel.Tests.csproj ├── PerformanceTests.cs └── TestHelper.cs ├── EntityFrameworkCore.Parallel.sln ├── EntityFrameworkCore.Parallel ├── AsyncEnumerableExtensions.cs ├── AutoDisposingAsyncEnumerable.cs ├── AutoDisposingAsyncEnumerator.cs ├── AutoDisposingEnumerable.cs ├── AutoDisposingEnumerator.cs ├── DbContextFactoryExtensions.cs ├── DbContextFactoryQueryContext.cs ├── DbContextFactoryWrapper.cs ├── EntityFrameworkCore.Parallel.csproj ├── EntityFrameworkCore.Parallel.xml ├── EntityQueryRootExpressionReplaceVisitor.cs ├── EnumerableExtensions.cs ├── GlobalSuppressions.cs ├── IQueryContext.cs ├── Internal │ ├── EntityType.cs │ └── SharedTypeExtensions.cs └── QueryProvider.cs └── NuGet.config /.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 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EntityFrameworkCore.Parallel 2 | 3 | This extension to Entity Framework Core adds a `Set()` method to `IDbContextFactory`. 4 | For easy use it also adds a `Parallel()` method to `IDbContextFactory` and a `Set()` method to `IDbContextFactory`. 5 | This allows you to easily execute multiple queries in parallel without the need to write complex code, or a lot of `using` blocks or statements. 6 | You can stick to all your known methods from `IQueryable`. 7 | As the context is disposed after your query is executed, all results will obviously not be tracked and disconnected from any `DbContext`. 8 | 9 | # How to use 10 | 11 | In your `Startup` class, add a `DbContextfactory`. If you want a pooled one, or not is up to you. 12 | 13 | ```csharp 14 | services.AddPooledDbContextFactory(options => options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=OrderTest")); 15 | ``` 16 | 17 | In your business class, inject an `IDbContextFactory` and use it like this 18 | 19 | ```csharp 20 | var ordersFromDb = await _factory.Parallel().Set().Where(o => o.Id > 3).ToListAsync(cancellationToken); 21 | ``` 22 | 23 | Or like this 24 | 25 | ```csharp 26 | var ordersFromDb = await _factory.Set().Where(o => o.Id > 3).ToListAsync(cancellationToken); 27 | ``` 28 | 29 | # Migration from Entity Framework Core 5 to 6 30 | 31 | Since Entity Framework Core 6, `IDbContextFactory` is no longer covariant (`TContext` is not marked with the `out` keyword). 32 | Because of that, the following code does no longer work. 33 | 34 | ```csharp 35 | var ordersFromDb = await _factory.Set().Where(o => o.Id > 3).ToListAsync(); 36 | ``` 37 | 38 | See the *How to use* section for two possibilities that you can use instead. 39 | If you want some background information, have a look at -------------------------------------------------------------------------------- /build/NuGet_clean.ps1: -------------------------------------------------------------------------------- 1 | Get-ChildItem -Path ../src -Filter *.*nupkg -Recurse | Where-Object { $_.FullName.Contains("bin\Release") } | ForEach-Object { Remove-Item $_ } -------------------------------------------------------------------------------- /build/NuGet_push.ps1: -------------------------------------------------------------------------------- 1 | Get-ChildItem -Path ../src -Filter *.*nupkg -Recurse | Where-Object { $_.FullName.Contains("bin\Release") } | ForEach-Object { dotnet nuget push $_.FullName --source https://api.nuget.org/v3/index.json --skip-duplicate } -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.DemoModel/Detail.cs: -------------------------------------------------------------------------------- 1 | namespace EntityFrameworkCore.Parallel.DemoModel; 2 | 3 | public class Detail : EntityBase 4 | { 5 | public string? Product { get; set; } 6 | public int Quantity { get; set; } 7 | public long OrderId { get; set; } 8 | public virtual Order? Order { get; set; } 9 | } -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.DemoModel/EntityBase.cs: -------------------------------------------------------------------------------- 1 | namespace EntityFrameworkCore.Parallel.DemoModel; 2 | 3 | public abstract class EntityBase 4 | { 5 | public long Id { get; set; } 6 | public byte[]? Timestamp { get; set; } 7 | } 8 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.DemoModel/EntityFrameworkCore.Parallel.DemoModel.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net9.0 5 | enable 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.DemoModel/Order.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace EntityFrameworkCore.Parallel.DemoModel; 4 | 5 | public class Order : EntityBase 6 | { 7 | public string? OrderNumber { get; set; } 8 | 9 | public virtual ICollection Details { get; set; } = new HashSet(); 10 | } -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.DemoModel/OrderContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace EntityFrameworkCore.Parallel.DemoModel; 4 | 5 | public class OrderContext : DbContext 6 | { 7 | public OrderContext(DbContextOptions options) 8 | : base(options) 9 | { 10 | 11 | } 12 | 13 | public DbSet Orders { get; set; } = default!; 14 | 15 | public DbSet Details { get; set; } = default!; 16 | } 17 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.Tests/CastExtensionTests.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.Parallel.DemoModel; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace EntityFrameworkCore.Parallel.Tests; 8 | 9 | [TestClass] 10 | public class CastExtensionTests 11 | { 12 | private IDbContextFactory _factory = default!; 13 | 14 | [TestInitialize] 15 | public async Task TestInitialize() 16 | { 17 | _factory = await TestHelper.CreateFreshDatabase(10); 18 | } 19 | 20 | [TestMethod] 21 | public void WithParallel_and_Set_of_TEntity_should_return_the_same_value_as_Set_of_TContext_TEntity() 22 | { 23 | // Act 24 | var orderWithParallelAndSet = _factory.Parallel().Set().First(); 25 | var orderWithSetOnly = _factory.Set().First(); 26 | 27 | // Assert 28 | Assert.AreEqual(orderWithSetOnly.Id, orderWithParallelAndSet.Id); 29 | } 30 | 31 | [TestMethod] 32 | public void WithCast_and_Set_of_TEntity_should_return_the_same_value_as_Set_of_TContext_TEntity() 33 | { 34 | // Act 35 | var orderWithCastAndSet = _factory.Cast().Set().First(); 36 | var orderWithSetOnly = _factory.Set().First(); 37 | 38 | // Assert 39 | Assert.AreEqual(orderWithSetOnly.Id, orderWithCastAndSet.Id); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.Tests/DatabaseTests.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.Parallel.DemoModel; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace EntityFrameworkCore.Parallel.Tests; 8 | 9 | [TestClass] 10 | public class DatabaseTests 11 | { 12 | private IDbContextFactory _factory = default!; 13 | 14 | [TestInitialize] 15 | public async Task TestInitialize() 16 | { 17 | _factory = await TestHelper.CreateFreshDatabase(10); 18 | } 19 | 20 | [TestMethod] 21 | public void ToList_should_return_the_Orders_from_the_database() 22 | { 23 | // Act 24 | var ordersFromDb = _factory.Set().ToList(); 25 | 26 | // Assert 27 | Assert.AreEqual(10, ordersFromDb.Count); 28 | } 29 | 30 | [TestMethod] 31 | public async Task ToListAsync_should_return_the_Orders_from_the_database() 32 | { 33 | // Act 34 | var ordersFromDb = await _factory.Set().ToListAsync(); 35 | 36 | // Assert 37 | Assert.AreEqual(10, ordersFromDb.Count); 38 | } 39 | 40 | [TestMethod] 41 | public void SelectMany_and_ToList_should_return_the_Details_from_the_database() 42 | { 43 | // Act 44 | var detailsFromDb = _factory.Set().SelectMany(o => o.Details).ToList(); 45 | 46 | // Assert 47 | Assert.AreEqual(100, detailsFromDb.Count); 48 | } 49 | 50 | [TestMethod] 51 | public async Task SelectMany_and_ToListAsync_should_return_the_Details_from_the_database() 52 | { 53 | // Act 54 | var detailsFromDb = await _factory.Set().SelectMany(o => o.Details).ToListAsync(); 55 | 56 | // Assert 57 | Assert.AreEqual(100, detailsFromDb.Count); 58 | } 59 | 60 | [TestMethod] 61 | public void SelectMany_and_Select_and_ToList_should_return_the_Details_from_the_database() 62 | { 63 | // Act 64 | var detailsFromDb = _factory.Set().SelectMany(o => o.Details).Select(d => d.Order).ToList(); 65 | 66 | // Assert 67 | Assert.AreEqual(100, detailsFromDb.Count); 68 | } 69 | 70 | [TestMethod] 71 | public async Task SelectMany_and_Select_and_ToListAsync_should_return_the_Details_from_the_database() 72 | { 73 | // Act 74 | var detailsFromDb = await _factory.Set().SelectMany(o => o.Details).Select(d => d.Order).ToListAsync(); 75 | 76 | // Assert 77 | Assert.AreEqual(100, detailsFromDb.Count); 78 | } 79 | 80 | [TestMethod] 81 | public async Task Select_and_ToListAsync_should_return_the_Orders_from_the_database() 82 | { 83 | // Act 84 | var detailsFromDb = await _factory.Set().Select(d => d.Order).ToListAsync(); 85 | 86 | // Assert 87 | Assert.AreEqual(100, detailsFromDb.Count); 88 | } 89 | 90 | [TestMethod] 91 | public void Select_and_ToList_should_return_the_Orders_from_the_database() 92 | { 93 | // Act 94 | var detailsFromDb = _factory.Set().Select(d => d.Order).ToList(); 95 | 96 | // Assert 97 | Assert.AreEqual(100, detailsFromDb.Count); 98 | } 99 | 100 | [TestMethod] 101 | public async Task Select_to_anonymous_type_and_ToListAsync_should_return_the_Orders_from_the_database() 102 | { 103 | // Act 104 | var detailsFromDb = await _factory.Set().Select(d => new { d.Id, d.Quantity }).ToListAsync(); 105 | 106 | // Assert 107 | Assert.AreEqual(100, detailsFromDb.Count); 108 | } 109 | 110 | [TestMethod] 111 | public void Select_to_anonymous_type_and_ToList_should_return_the_Orders_from_the_database() 112 | { 113 | // Act 114 | var detailsFromDb = _factory.Set().Select(d => new { d.Id, d.Quantity }).ToList(); 115 | 116 | // Assert 117 | Assert.AreEqual(100, detailsFromDb.Count); 118 | } 119 | 120 | [TestMethod] 121 | public void ToList_with_Where_should_return_the_Orders_from_the_database() 122 | { 123 | // Act 124 | var ordersFromDb = _factory.Set().Where(o => o.Id > 3).ToList(); 125 | 126 | // Assert 127 | Assert.AreEqual(7, ordersFromDb.Count); 128 | } 129 | 130 | [TestMethod] 131 | public async Task ToListAsync_with_Where_should_return_the_Orders_from_the_database() 132 | { 133 | // Act 134 | var ordersFromDb = await _factory.Set().Where(o => o.Id > 3).ToListAsync(); 135 | 136 | // Assert 137 | Assert.AreEqual(7, ordersFromDb.Count); 138 | } 139 | 140 | [TestMethod] 141 | public void First_should_return_the_first_Order_from_the_database() 142 | { 143 | // Act 144 | var orderFromDb = _factory.Set().First(); 145 | 146 | // Assert 147 | Assert.IsNotNull(orderFromDb); 148 | } 149 | 150 | [TestMethod] 151 | public void FirstOrDefault_should_return_the_first_Order_from_the_database() 152 | { 153 | // Act 154 | var orderFromDb = _factory.Set().FirstOrDefault(); 155 | 156 | // Assert 157 | Assert.IsNotNull(orderFromDb); 158 | } 159 | 160 | [TestMethod] 161 | public async Task FirstAsync_should_return_the_first_Order_from_the_database() 162 | { 163 | // Act 164 | var orderFromDb = await _factory.Set().FirstAsync(); 165 | 166 | // Assert 167 | Assert.IsNotNull(orderFromDb); 168 | } 169 | 170 | [TestMethod] 171 | public void Select_to_anonymous_type_and_FirstOrDefault_should_return_the_first_Order_from_the_database() 172 | { 173 | // Act 174 | var orderFromDb = _factory.Set().Select(o => new { o.Id, o.OrderNumber }).FirstOrDefault(); 175 | 176 | // Assert 177 | Assert.IsNotNull(orderFromDb); 178 | } 179 | 180 | [TestMethod] 181 | public async Task FirstOrDefaultAsync_should_return_the_first_Order_from_the_database() 182 | { 183 | // Act 184 | var orderFromDb = await _factory.Set().FirstOrDefaultAsync(); 185 | 186 | // Assert 187 | Assert.IsNotNull(orderFromDb); 188 | } 189 | 190 | [TestMethod] 191 | public async Task Select_to_anonymous_type_and_FirstOrDefaultAsync_should_return_the_first_Order_from_the_database() 192 | { 193 | // Act 194 | var orderFromDb = await _factory.Set().Select(o => new { o.Id, o.OrderNumber }).FirstOrDefaultAsync(); 195 | 196 | // Assert 197 | Assert.IsNotNull(orderFromDb); 198 | } 199 | 200 | 201 | [TestMethod] 202 | public async Task SingleAsync_should_return_the_Single_Order_from_the_database() 203 | { 204 | // Act 205 | var orderFromDb = await _factory.Set().Where(o => o.Id == 1).SingleAsync(); 206 | 207 | // Assert 208 | Assert.IsNotNull(orderFromDb); 209 | } 210 | 211 | [TestMethod] 212 | public void Select_to_anonymous_type_and_SingleOrDefault_should_return_the_Single_Order_from_the_database() 213 | { 214 | // Act 215 | var orderFromDb = _factory.Set().Where(o => o.Id == 1).Select(o => new { o.Id, o.OrderNumber }).SingleOrDefault(); 216 | 217 | // Assert 218 | Assert.IsNotNull(orderFromDb); 219 | } 220 | 221 | [TestMethod] 222 | public async Task SingleOrDefaultAsync_should_return_the_Single_Order_from_the_database() 223 | { 224 | // Act 225 | var orderFromDb = await _factory.Set().Where(o => o.Id == 1).SingleOrDefaultAsync(); 226 | 227 | // Assert 228 | Assert.IsNotNull(orderFromDb); 229 | } 230 | 231 | [TestMethod] 232 | public async Task Select_to_anonymous_type_and_SingleOrDefaultAsync_should_return_the_Single_Order_from_the_database() 233 | { 234 | // Act 235 | var orderFromDb = await _factory.Set().Where(o => o.Id == 1).Select(o => new { o.Id, o.OrderNumber }).SingleOrDefaultAsync(); 236 | 237 | // Assert 238 | Assert.IsNotNull(orderFromDb); 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.Tests/EntityFrameworkCore.Parallel.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net9.0 5 | false 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | all 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.Tests/PerformanceTests.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.Parallel.DemoModel; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System; 5 | using System.Diagnostics; 6 | using System.Threading.Tasks; 7 | 8 | namespace EntityFrameworkCore.Parallel.Tests; 9 | 10 | [TestClass] 11 | public class PerformanceTests 12 | { 13 | private static IDbContextFactory _factory = default!; 14 | private static TimeSpan _timeSpanSerial; 15 | private static TimeSpan _timeSpanInclude; 16 | private static TimeSpan _timeSpanParallel; 17 | private static TimeSpan _timeSpanFactory; 18 | 19 | [ClassInitialize] 20 | public static async Task ClassInitialize(TestContext _) 21 | { 22 | // Arrange 23 | _factory = await TestHelper.CreateFreshDatabase(100); 24 | 25 | var count = 500; 26 | 27 | // Prime 28 | await GetAllWithContextSerial(); 29 | await GetAllWithContextParallel(); 30 | await GetAllWithFactoryParallel(); 31 | 32 | // Act 33 | _timeSpanSerial = await Benchmark(GetAllWithContextSerial, count); 34 | _timeSpanInclude = await Benchmark(GetAllWithContextInclude, count); 35 | _timeSpanParallel = await Benchmark(GetAllWithContextParallel, count); 36 | _timeSpanFactory = await Benchmark(GetAllWithFactoryParallel, count); 37 | 38 | // The output will appear in the first test which is executed as "additional output". 39 | Console.WriteLine($" {nameof(GetAllWithContextSerial)} - {_timeSpanSerial}"); 40 | Console.WriteLine($" {nameof(GetAllWithContextInclude)} - {_timeSpanInclude}"); 41 | Console.WriteLine($" {nameof(GetAllWithContextParallel)} - {_timeSpanParallel}"); 42 | Console.WriteLine($" {nameof(GetAllWithFactoryParallel)} - {_timeSpanFactory}"); 43 | } 44 | 45 | [TestMethod] 46 | public void Parallel_should_be_faster_than_serial() 47 | { 48 | Assert.IsTrue(_timeSpanParallel < _timeSpanSerial, $"{_timeSpanParallel} was not less than {_timeSpanSerial}"); 49 | } 50 | 51 | [TestMethod] 52 | public void Factory_should_be_faster_than_include() 53 | { 54 | Assert.IsTrue(_timeSpanFactory < _timeSpanInclude, $"{_timeSpanFactory} was not less than {_timeSpanInclude}"); 55 | } 56 | 57 | [TestMethod] 58 | public void Factory_should_be_roughly_equal_to_parallel() 59 | { 60 | var delta = _timeSpanFactory.TotalMilliseconds * 0.1; // 10% difference is ok 61 | Assert.AreEqual(_timeSpanFactory.TotalMilliseconds, _timeSpanParallel.TotalMilliseconds, delta, $"{_timeSpanFactory} was not roughly equal to {_timeSpanParallel}"); 62 | } 63 | 64 | private static async Task Benchmark(Func method, int count) 65 | { 66 | var sw = new Stopwatch(); 67 | sw.Start(); 68 | for (int i = 0; i < count; i++) 69 | { 70 | await method(); 71 | } 72 | sw.Stop(); 73 | return sw.Elapsed; 74 | } 75 | 76 | private static async Task GetAllWithContextInclude() 77 | { 78 | using var context = _factory.CreateDbContext(); 79 | context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 80 | var orders = await EntityFrameworkQueryableExtensions.ToListAsync(context.Set().Include(o => o.Details)); 81 | } 82 | 83 | private static async Task GetAllWithContextSerial() 84 | { 85 | using var context = _factory.CreateDbContext(); 86 | context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 87 | var orders = await EntityFrameworkQueryableExtensions.ToListAsync(context.Set()); 88 | var details = await EntityFrameworkQueryableExtensions.ToListAsync(context.Set()); 89 | } 90 | 91 | private static async Task GetAllWithContextParallel() 92 | { 93 | using var context1 = _factory.CreateDbContext(); 94 | using var context2 = _factory.CreateDbContext(); 95 | context1.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 96 | context2.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 97 | var ordersTask = EntityFrameworkQueryableExtensions.ToListAsync(context1.Set()); 98 | var detailsTask = EntityFrameworkQueryableExtensions.ToListAsync(context2.Set()); 99 | 100 | await Task.WhenAll(ordersTask, detailsTask); 101 | 102 | var orders = ordersTask.Result; 103 | var details = detailsTask.Result; 104 | } 105 | 106 | private static async Task GetAllWithFactoryParallel() 107 | { 108 | var ordersTask = _factory.Set().ToListAsync(); 109 | var detailsTask = _factory.Set().ToListAsync(); 110 | 111 | await Task.WhenAll(ordersTask, detailsTask); 112 | _ = ordersTask.Result; 113 | _ = detailsTask.Result; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.Tests/TestHelper.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.Parallel.DemoModel; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | 7 | namespace EntityFrameworkCore.Parallel.Tests; 8 | 9 | public static class TestHelper 10 | { 11 | public static async Task> CreateFreshDatabase(int entitiesInEachTable) 12 | { 13 | var services = new ServiceCollection(); 14 | services.AddPooledDbContextFactory(options => options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=OrderTest")); 15 | 16 | var provider = services.BuildServiceProvider(); 17 | 18 | var factory = provider.GetRequiredService>(); 19 | using (var context = factory.CreateDbContext()) 20 | { 21 | await context.Database.EnsureDeletedAsync(); 22 | await context.Database.EnsureCreatedAsync(); 23 | 24 | var orders = new List(); 25 | for (int i = 0; i < entitiesInEachTable; i++) 26 | { 27 | var order = new Order { OrderNumber = $"O{i}" }; 28 | orders.Add(order); 29 | for (int j = 0; j < entitiesInEachTable; j++) 30 | { 31 | var detail = new Detail { Order = order, Product = $"P{i}-{j}", Quantity = i * j }; 32 | order.Details.Add(detail); 33 | } 34 | } 35 | 36 | context.AddRange(orders); 37 | await context.SaveChangesAsync(); 38 | } 39 | 40 | return factory; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30517.126 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Parallel", "EntityFrameworkCore.Parallel\EntityFrameworkCore.Parallel.csproj", "{6CF22135-ADC4-4212-A054-E73AE70E3087}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Parallel.Tests", "EntityFrameworkCore.Parallel.Tests\EntityFrameworkCore.Parallel.Tests.csproj", "{6565439E-6CF8-4EF3-97E2-C7B5E264E952}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Parallel.DemoModel", "EntityFrameworkCore.Parallel.DemoModel\EntityFrameworkCore.Parallel.DemoModel.csproj", "{8B8E9F92-8ECA-4848-B038-1D904B2D59AC}" 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 | {6CF22135-ADC4-4212-A054-E73AE70E3087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {6CF22135-ADC4-4212-A054-E73AE70E3087}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {6CF22135-ADC4-4212-A054-E73AE70E3087}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {6CF22135-ADC4-4212-A054-E73AE70E3087}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {6565439E-6CF8-4EF3-97E2-C7B5E264E952}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {6565439E-6CF8-4EF3-97E2-C7B5E264E952}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {6565439E-6CF8-4EF3-97E2-C7B5E264E952}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {6565439E-6CF8-4EF3-97E2-C7B5E264E952}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {8B8E9F92-8ECA-4848-B038-1D904B2D59AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {8B8E9F92-8ECA-4848-B038-1D904B2D59AC}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {8B8E9F92-8ECA-4848-B038-1D904B2D59AC}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {8B8E9F92-8ECA-4848-B038-1D904B2D59AC}.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 = {C3F70A06-0327-4F4A-BB50-AB1547B8A691} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/AsyncEnumerableExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EntityFrameworkCore.Parallel; 5 | 6 | /// 7 | /// Contains extension methods for . 8 | /// 9 | public static class AsyncEnumerableExtensions 10 | { 11 | /// 12 | /// Disposes the after enumeration. 13 | /// 14 | /// The element type. 15 | /// The source. 16 | /// The database set. 17 | /// 18 | public static IAsyncEnumerable DisposeAfterEnumeration(this IAsyncEnumerable source, IAsyncDisposable dbSet) 19 | => new AutoDisposingAsyncEnumerable(source, dbSet); 20 | } 21 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/AutoDisposingAsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading; 4 | 5 | namespace EntityFrameworkCore.Parallel; 6 | 7 | /// 8 | /// An which will dispose the given disposable object once fully enumerated. 9 | /// 10 | /// The element type. 11 | public class AutoDisposingAsyncEnumerable : IAsyncEnumerable 12 | { 13 | private readonly IAsyncDisposable _asyncDisposable; 14 | private readonly IAsyncEnumerable _source; 15 | 16 | /// 17 | /// Initializes a new instance of the class. 18 | /// 19 | /// The source. 20 | /// The database set. 21 | /// 22 | /// source 23 | /// or 24 | /// dbSet 25 | /// 26 | public AutoDisposingAsyncEnumerable(IAsyncEnumerable source, IAsyncDisposable dbSet) 27 | { 28 | _source = source ?? throw new ArgumentNullException(nameof(source)); 29 | _asyncDisposable = dbSet ?? throw new ArgumentNullException(nameof(dbSet)); 30 | } 31 | 32 | /// 33 | public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) => new AutoDisposingAsyncEnumerator(_source, _asyncDisposable); 34 | } -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/AutoDisposingAsyncEnumerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace EntityFrameworkCore.Parallel; 6 | 7 | /// 8 | /// This async enumerator will automatically dispose the given async disposable object once fully enumerated. 9 | /// 10 | /// The element type. 11 | public class AutoDisposingAsyncEnumerator : IAsyncEnumerator 12 | { 13 | private readonly IAsyncDisposable _asyncDisposable; 14 | private readonly IAsyncEnumerator _enumerator; 15 | 16 | /// 17 | /// Initializes a new instance of the class. 18 | /// 19 | /// The source. 20 | /// The asynchronous disposable. 21 | /// 22 | /// source 23 | /// or 24 | /// asyncDisposable 25 | /// 26 | public AutoDisposingAsyncEnumerator(IAsyncEnumerable source, IAsyncDisposable asyncDisposable) 27 | { 28 | ArgumentNullException.ThrowIfNull(source); 29 | 30 | _enumerator = source.GetAsyncEnumerator(); 31 | _asyncDisposable = asyncDisposable ?? throw new ArgumentNullException(nameof(asyncDisposable)); 32 | } 33 | /// 34 | public T Current => _enumerator.Current; 35 | 36 | /// 37 | public async ValueTask DisposeAsync() 38 | { 39 | await _enumerator.DisposeAsync(); 40 | await _asyncDisposable.DisposeAsync(); 41 | } 42 | 43 | /// 44 | public ValueTask MoveNextAsync() => _enumerator.MoveNextAsync(); 45 | } 46 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/AutoDisposingEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EntityFrameworkCore.Parallel; 5 | 6 | /// 7 | /// An which will dispose the given disposable object once fully enumerated. 8 | /// 9 | /// The element type. 10 | public class AutoDisposingEnumerable : IEnumerable 11 | { 12 | private readonly IDisposable _disposable; 13 | private readonly IEnumerable _source; 14 | 15 | /// 16 | /// Initializes a new instance of the class. 17 | /// 18 | /// The source. 19 | /// The disposable. 20 | /// 21 | /// source 22 | /// or 23 | /// disposable 24 | /// 25 | public AutoDisposingEnumerable(IEnumerable source, IDisposable disposable) 26 | { 27 | _source = source ?? throw new ArgumentNullException(nameof(source)); 28 | _disposable = disposable ?? throw new ArgumentNullException(nameof(disposable)); 29 | } 30 | 31 | /// 32 | public IEnumerator GetEnumerator() 33 | { 34 | return new AutoDisposingEnumerator(_source, _disposable); 35 | } 36 | 37 | /// 38 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); 39 | } 40 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/AutoDisposingEnumerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EntityFrameworkCore.Parallel; 5 | 6 | /// 7 | /// This enumerator will automatically dispose the given disposable object once fully enumerated. 8 | /// 9 | /// The element type. 10 | public class AutoDisposingEnumerator : IEnumerator 11 | { 12 | private readonly IDisposable _disposable; 13 | private readonly IEnumerator _enumerator; 14 | 15 | /// Initializes a new instance of the class. 16 | /// The source. 17 | /// The disposable. 18 | /// source 19 | /// or 20 | /// disposable 21 | public AutoDisposingEnumerator(IEnumerable source, IDisposable disposable) 22 | { 23 | ArgumentNullException.ThrowIfNull(source); 24 | 25 | _enumerator = source.GetEnumerator(); 26 | _disposable = disposable ?? throw new ArgumentNullException(nameof(disposable)); 27 | } 28 | 29 | /// 30 | public T Current => _enumerator.Current; 31 | 32 | /// 33 | object System.Collections.IEnumerator.Current => Current!; 34 | 35 | /// 36 | public void Dispose() 37 | { 38 | _enumerator.Dispose(); 39 | _disposable.Dispose(); 40 | 41 | GC.SuppressFinalize(this); 42 | } 43 | 44 | /// 45 | public bool MoveNext() => _enumerator.MoveNext(); 46 | 47 | /// 48 | public void Reset() => _enumerator.Reset(); 49 | } -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/DbContextFactoryExtensions.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.Parallel; 2 | using EntityFrameworkCore.Parallel.Internal; 3 | using Microsoft.EntityFrameworkCore.Query.Internal; 4 | using System.Linq; 5 | 6 | namespace Microsoft.EntityFrameworkCore; 7 | 8 | /// 9 | /// Contains the extension method which is the starting point for any query. 10 | /// 11 | public static class DbContextFactoryExtensions 12 | { 13 | /// 14 | /// The starting point for your query if you do not want to use the extension method on your context. Make sure is available as a on your . 15 | /// 16 | /// The type of the context. 17 | /// The type of the entities. 18 | /// The factory which can create the . 19 | /// 20 | public static IQueryable Set(this IDbContextFactory contextFactory) 21 | where TContext : DbContext 22 | where TEntity : class 23 | { 24 | System.ArgumentNullException.ThrowIfNull(contextFactory); 25 | 26 | var query = new EntityQueryable( 27 | new QueryProvider(new DbContextFactoryQueryContext(contextFactory)), 28 | new EntityType()); 29 | return query; 30 | } 31 | /// 32 | /// The starting point for your query. Make sure is available as a on your . 33 | /// 34 | /// The type of the entities. 35 | /// The factory which can create the . 36 | /// 37 | public static IQueryable Set(this IDbContextFactory contextFactory) 38 | where TEntity : class 39 | { 40 | System.ArgumentNullException.ThrowIfNull(contextFactory); 41 | 42 | var query = new EntityQueryable( 43 | new QueryProvider(new DbContextFactoryQueryContext(contextFactory)), 44 | new EntityType()); 45 | return query; 46 | } 47 | 48 | /// 49 | /// Wraps the factory as an IDbContextFactory<DbContext> to allow the usage of the Method without having to specify the type of the context. 50 | /// 51 | /// The type of the context. 52 | /// The factory which can create the . 53 | /// The factory wrapped as an IDbContextFactory<DbContext>. 54 | public static IDbContextFactory Parallel(this IDbContextFactory contextFactory) 55 | where TContext : DbContext 56 | => new DbContextFactoryWrapper(contextFactory); 57 | 58 | /// 59 | /// Down-casts the generic parameter of to . 60 | /// 61 | /// The type of the context to wrap. 62 | /// The type of the context to return. 63 | /// The factory which can create the . 64 | /// The factory wrapped as an 65 | public static IDbContextFactory Cast(this IDbContextFactory contextFactory) 66 | where TContextIn : TContextOut 67 | where TContextOut : DbContext 68 | => new DbContextFactoryWrapper(contextFactory); 69 | } 70 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/DbContextFactoryQueryContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Query; 3 | using System; 4 | using System.Collections; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Linq.Expressions; 8 | using System.Reflection; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | 12 | namespace EntityFrameworkCore.Parallel; 13 | 14 | /// 15 | /// This class contains the logic which will actually create the and 16 | /// execute the query on it. 17 | /// 18 | /// The type of the context. 19 | /// The type of the entity. 20 | public class DbContextFactoryQueryContext : DbContextFactoryQueryContext, IQueryContext 21 | where TContext : DbContext 22 | where TEntity : class 23 | { 24 | private readonly IDbContextFactory factory; 25 | 26 | /// 27 | /// Initializes a new instance of the class. 28 | /// 29 | /// The factory. 30 | /// factory 31 | public DbContextFactoryQueryContext(IDbContextFactory factory) 32 | { 33 | this.factory = factory ?? throw new ArgumentNullException(nameof(factory)); 34 | } 35 | 36 | /// 37 | public TResult Execute(Expression query) 38 | { 39 | ArgumentNullException.ThrowIfNull(query); 40 | 41 | var context = factory.CreateDbContext(); 42 | try 43 | { 44 | context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 45 | var set = context.Set(); 46 | var queryable = set.AsQueryable(); 47 | var provider = queryable.Provider; 48 | 49 | var replaced = ReplaceProvider(query, set, provider); 50 | var result = provider.Execute(replaced); 51 | var autoDisposing = DisposeAfterEnumeration(result, context); 52 | return autoDisposing; 53 | } 54 | catch 55 | { 56 | context.Dispose(); 57 | throw; 58 | } 59 | } 60 | 61 | /// 62 | public TResult ExecuteAsync(Expression query, CancellationToken cancellationToken = default) 63 | { 64 | ArgumentNullException.ThrowIfNull(query); 65 | 66 | // We cannot use a using block here, because the result will be enumerated after this 67 | // method has already returned. Instead we pass the DbContext down to the enumerator 68 | // which will then dispose the context once itself gets disposed. This will happen when 69 | // the result is enumerated. 70 | var context = factory.CreateDbContext(); 71 | try 72 | { 73 | context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; 74 | var set = context.Set(); 75 | var queryable = set.AsQueryable(); 76 | var provider = queryable.Provider; 77 | 78 | if (provider is IAsyncQueryProvider asyncProvider) 79 | { 80 | var replaced = ReplaceProvider(query, set, provider); 81 | var result = asyncProvider.ExecuteAsync(replaced, cancellationToken); 82 | var autoDisposing = DisposeAfterEnumerationAsync(result, context); 83 | return autoDisposing; 84 | } 85 | 86 | throw new InvalidOperationException("Cannot execute an async query on a non async query provider."); 87 | } 88 | catch 89 | { 90 | context.Dispose(); 91 | throw; 92 | } 93 | } 94 | 95 | private static TResult DisposeAfterEnumeration(TResult result, DbContext dbContext) 96 | { 97 | if (result is IEnumerable enumerableResult) 98 | { 99 | var autoDisposing = MakeAutoDisposing(enumerableResult, dbContext); 100 | return autoDisposing; 101 | } 102 | 103 | dbContext.Dispose(); 104 | return result; 105 | } 106 | 107 | private static TResult DisposeAfterEnumerationAsync(TResult result, DbContext dbContext) 108 | { 109 | if (result is IEnumerable enumerableResult) 110 | { 111 | var autoDisposing = MakeAsyncAutoDisposing(enumerableResult, dbContext); 112 | return autoDisposing; 113 | } 114 | 115 | if (result is Task taskResult) 116 | { 117 | var autoDisposing = MakeAsyncAutoDisposing(taskResult, dbContext); 118 | return autoDisposing; 119 | } 120 | 121 | dbContext.Dispose(); 122 | return result; 123 | } 124 | 125 | private static Expression ReplaceProvider(Expression query, DbSet set, IQueryProvider provider) 126 | => EntityQueryRootExpressionReplaceVisitor.ReplaceProvider(query, set, provider); 127 | } 128 | 129 | /// 130 | /// Base class for which contains some non 131 | /// generic reflection stuff. 132 | /// 133 | /// 134 | /// 135 | public abstract class DbContextFactoryQueryContext 136 | { 137 | /// 138 | /// of . 139 | /// 140 | private static readonly MethodInfo _disposeEnumerableAfterEnumerationAsyncMethodInfo = typeof(DbContextFactoryQueryContext) 141 | .GetMethod(nameof(DisposeEnumerableAfterEnumerationAsync), BindingFlags.Static | BindingFlags.NonPublic) 142 | ?? throw new MissingMethodException(nameof(DbContextFactoryQueryContext), nameof(DisposeEnumerableAfterEnumerationAsync)); 143 | 144 | /// 145 | /// of . 146 | /// 147 | private static readonly MethodInfo _disposeEnumerableAfterEnumerationMethodInfo = typeof(DbContextFactoryQueryContext) 148 | .GetMethod(nameof(DisposeEnumerableAfterEnumeration), BindingFlags.Static | BindingFlags.NonPublic) 149 | ?? throw new MissingMethodException(nameof(DbContextFactoryQueryContext), nameof(DisposeEnumerableAfterEnumeration)); 150 | 151 | /// 152 | /// of . 153 | /// 154 | private static readonly MethodInfo _disposeAfterAwaitMethodInfo = typeof(DbContextFactoryQueryContext) 155 | .GetMethod(nameof(DisposeAfterAwait), BindingFlags.Static | BindingFlags.NonPublic) 156 | ?? throw new MissingMethodException(nameof(DbContextFactoryQueryContext), nameof(DisposeAfterAwait)); 157 | 158 | /// 159 | /// Wraps the in an which disposes the after enumeration. 160 | /// 161 | /// The result type. 162 | /// The result. 163 | /// The DB context. 164 | protected static TResult MakeAutoDisposing(IEnumerable result, DbContext dbContext) 165 | { 166 | var resultType = typeof(TResult); 167 | var elementType = resultType.IsGenericType ? resultType.GetGenericArguments()[0] : resultType.GetElementType() ?? typeof(object); 168 | var genericMethod = _disposeEnumerableAfterEnumerationMethodInfo.MakeGenericMethod(elementType); 169 | var autoDisposing = genericMethod.Invoke(null, [result, dbContext])!; 170 | 171 | return (TResult)autoDisposing; 172 | } 173 | 174 | /// 175 | /// Wraps the in an which disposes the after enumeration. 176 | /// 177 | /// The result type. 178 | /// The result. 179 | /// The DB context. 180 | protected static TResult MakeAsyncAutoDisposing(IEnumerable result, DbContext dbContext) 181 | { 182 | var resultType = typeof(TResult); 183 | var elementType = resultType.IsGenericType ? resultType.GetGenericArguments()[0] : resultType.GetElementType() ?? typeof(object); 184 | var genericMethod = _disposeEnumerableAfterEnumerationAsyncMethodInfo.MakeGenericMethod(elementType); 185 | var autoDisposing = genericMethod.Invoke(null, [result, dbContext])!; 186 | 187 | return (TResult)autoDisposing; 188 | } 189 | 190 | /// 191 | /// Wraps the in a which disposes the after awaiting the original and returns the original as . 192 | /// 193 | /// The result type. 194 | /// The result. 195 | /// The DB context. 196 | protected static TResult MakeAsyncAutoDisposing(Task result, DbContext dbContext) 197 | { 198 | var resultType = typeof(TResult); 199 | var elementType = resultType.IsGenericType ? resultType.GetGenericArguments()[0] : typeof(object); 200 | var genericMethod = _disposeAfterAwaitMethodInfo.MakeGenericMethod(elementType); 201 | var autoDisposing = genericMethod.Invoke(null, [result, dbContext])!; 202 | 203 | return (TResult)autoDisposing; 204 | } 205 | 206 | private static IEnumerable DisposeEnumerableAfterEnumeration(IEnumerable result, DbContext dbContext) 207 | { 208 | var autoDisposing = EnumerableExtensions.DisposeAfterEnumeration(result, dbContext); 209 | return autoDisposing; 210 | } 211 | 212 | private static IAsyncEnumerable DisposeEnumerableAfterEnumerationAsync(IAsyncEnumerable result, DbContext dbContext) 213 | { 214 | var autoDisposing = AsyncEnumerableExtensions.DisposeAfterEnumeration(result, dbContext); 215 | return autoDisposing; 216 | } 217 | 218 | private async static Task DisposeAfterAwait(Task task, DbContext dbContext) 219 | { 220 | var result = await task; 221 | await dbContext.DisposeAsync(); 222 | return result; 223 | } 224 | } -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/DbContextFactoryWrapper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace EntityFrameworkCore.Parallel; 4 | 5 | /// 6 | /// This class wraps an as . 7 | /// It is basically down-casting to . 8 | /// This became necessary because in Entity Framework Core 6 the interface is no longer covariant. 9 | /// 10 | /// The type of the context to wrap. 11 | /// The type of the context to return. 12 | /// See https://github.com/dotnet/efcore/issues/26630 13 | public class DbContextFactoryWrapper : IDbContextFactory 14 | where TContextIn : TContextOut 15 | where TContextOut : DbContext 16 | { 17 | private readonly IDbContextFactory _factory; 18 | 19 | /// 20 | /// Initializes a new instance of the class. 21 | /// 22 | /// The factory to wrap. 23 | public DbContextFactoryWrapper(IDbContextFactory factory) 24 | { 25 | _factory = factory ?? throw new System.ArgumentNullException(nameof(factory)); 26 | } 27 | 28 | /// 29 | public TContextOut CreateDbContext() => _factory.CreateDbContext(); 30 | } 31 | 32 | /// 33 | /// This class wraps an so it can be used with the extension method. 34 | /// This became necessary because in Entity Framework Core 6 the interface is no longer covariant. 35 | /// 36 | /// The type of the context to wrap. 37 | /// See https://github.com/dotnet/efcore/issues/26630 38 | public class DbContextFactoryWrapper : DbContextFactoryWrapper 39 | where TContext : DbContext 40 | { 41 | /// 42 | /// Initializes a new instance of the class. 43 | /// 44 | /// The factory to wrap. 45 | public DbContextFactoryWrapper(IDbContextFactory factory) 46 | : base(factory) 47 | { 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net9.0 5 | Library 6 | true 7 | true 8 | true 9 | 5.0.1 10 | wertzui 11 | true 12 | Unlicense 13 | https://github.com/wertzui/EntityFrameworkCore.Parallel 14 | https://github.com/wertzui/EntityFrameworkCore.Parallel 15 | true 16 | GIT 17 | This extension to Entity Framework Core adds a Set<TContext, TEntity> method to IDbCOntextFactory<TContext>. This allows you to easily execute multiple queries in parallel without the need to write complex code, or a lot of using blocks or statements. You can stick to all your known methods from IQueryable<TEntity>. As the context is disposed after your query is executed, all results will obviously not be tracked and disconnected from any DbContext. 18 | bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml 19 | true 20 | snupkg 21 | README.md 22 | enable 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml 31 | 32 | 33 | 34 | 35 | 36 | all 37 | runtime; build; native; contentfiles; analyzers; buildtransitive 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EntityFrameworkCore.Parallel 5 | 6 | 7 | 8 | 9 | An which will dispose the given disposable object once fully enumerated. 10 | 11 | The element type. 12 | 13 | 14 | 15 | This async enumerator will automatically dispose the given async disposable object once fully enumerated. 16 | 17 | The element type. 18 | 19 | 20 | 21 | An which will dispose the given disposable object once fully enumerated. 22 | 23 | The element type. 24 | 25 | 26 | 27 | This enumerator will automatically dispose the given disposable object once fully enumerated. 28 | 29 | The element type. 30 | 31 | 32 | 33 | This class contains the logic which will actually create the and execute the query on it. 34 | 35 | 36 | 37 | 38 | 39 | 40 | This is a minimal implementation of to support the creation of queries without the need of a DbContext. 41 | Most of its methods will just throw exceptions. 42 | When the query is actually executed, the expression which is started with this class is replaced to contain an instance of the implementation from the real Entity Framework library. 43 | 44 | The type of the entities in the DbSet. 45 | 46 | 47 | 48 | Contains extension methods to find the generic type parameter of a collection type. 49 | 50 | 51 | 52 | 53 | Interface for a query context. A query context is the thing that will actually execute any query. 54 | 55 | 56 | 57 | 58 | A basic query provider which will pass the execution logic down the given . 59 | 60 | 61 | 62 | 63 | Contains the extension method which is the starting point for any query. 64 | 65 | 66 | 67 | 68 | The starting point for your query. Make sure is available as a on your . 69 | 70 | The type of the . 71 | The type of the entities. 72 | The factory which can create the . 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/EntityQueryRootExpressionReplaceVisitor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata; 3 | using Microsoft.EntityFrameworkCore.Query; 4 | using System; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | using System.Reflection; 8 | 9 | namespace EntityFrameworkCore.Parallel 10 | { 11 | /// 12 | /// A that will replace each with the one given to it. 13 | /// 14 | /// The type of the entity. 15 | /// 16 | public class EntityQueryRootExpressionReplaceVisitor : ExpressionVisitor 17 | where TEntity : class 18 | { 19 | /// 20 | /// Gets a value indicating whether the query was replaced. 21 | /// 22 | public bool QueryWasReplaced { get; private set; } 23 | 24 | private readonly Expression _query; 25 | private readonly DbSet _set; 26 | private readonly IQueryProvider _provider; 27 | 28 | /// 29 | /// Initializes a new instance of the class. 30 | /// 31 | /// The query. 32 | /// The set. 33 | /// The provider of the set. 34 | public EntityQueryRootExpressionReplaceVisitor(Expression query, DbSet set, IQueryProvider provider) 35 | { 36 | _query = query; 37 | _set = set; 38 | _provider = provider; 39 | } 40 | 41 | /// 42 | public override Expression? Visit(Expression? node) 43 | { 44 | if (node is EntityQueryRootExpression root) 45 | { 46 | QueryWasReplaced = true; 47 | var replacedQuery = CreateQueryWithNewProvider(root, _set, _provider); 48 | return replacedQuery; 49 | } 50 | 51 | return base.Visit(node); 52 | } 53 | 54 | /// 55 | /// Creates a new query of the same type as the given query but with the new provider. 56 | /// 57 | private static EntityQueryRootExpression CreateQueryWithNewProvider(EntityQueryRootExpression query, DbSet set, IQueryProvider provider) 58 | { 59 | GetConstructorWithMostParameters(query, provider, out var queryType, out var constructorWithMostParameters, out var constructorParameters); 60 | 61 | var parameters = CreateConstructorParameterValues(query, set, provider, queryType, constructorParameters); 62 | 63 | var replaced = (EntityQueryRootExpression)constructorWithMostParameters.Invoke(parameters); 64 | 65 | return replaced; 66 | } 67 | 68 | private static object?[] CreateConstructorParameterValues(EntityQueryRootExpression query, DbSet set, IQueryProvider provider, Type queryType, ParameterInfo[] constructorParameters) 69 | { 70 | return constructorParameters 71 | .Select(p => p.ParameterType switch 72 | { 73 | var t when t == typeof(IAsyncQueryProvider) => (IAsyncQueryProvider)provider, 74 | var t when t == typeof(IEntityType) => set.EntityType, 75 | _ => queryType.GetProperty(p.Name!, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase)?.GetValue(query) 76 | } 77 | ) 78 | .ToArray(); 79 | } 80 | 81 | private static void GetConstructorWithMostParameters( 82 | EntityQueryRootExpression query, 83 | IQueryProvider provider, 84 | out Type queryType, 85 | out ConstructorInfo constructorWithMostParameters, 86 | out ParameterInfo[] constructorParameters) 87 | { 88 | queryType = query.GetType(); 89 | constructorWithMostParameters = queryType.GetConstructors() 90 | .Where(c => provider is not IAsyncQueryProvider || c.GetParameters().Any(p => p.ParameterType == typeof(IAsyncQueryProvider))) 91 | .OrderByDescending(c => c.GetParameters().Length) 92 | .First(); 93 | constructorParameters = constructorWithMostParameters.GetParameters(); 94 | } 95 | } 96 | 97 | /// 98 | /// Provides a way to replace the provider of an expression with a given one. 99 | /// 100 | public static class EntityQueryRootExpressionReplaceVisitor 101 | { 102 | /// 103 | /// Replaces the provider of the expression with the given one. 104 | /// 105 | /// The type of the entity. 106 | /// The query. 107 | /// The set. 108 | /// The provider of the set. 109 | /// The replaced expression. 110 | /// 111 | /// Thrown when , , or is null. 112 | /// 113 | /// 114 | /// Thrown when the supplied query does not originate from an and therefore does not come from Entity Framework. 115 | /// 116 | public static Expression ReplaceProvider(Expression query, DbSet set, IQueryProvider provider) 117 | where TEntity : class 118 | { 119 | ArgumentNullException.ThrowIfNull(query); 120 | ArgumentNullException.ThrowIfNull(set); 121 | ArgumentNullException.ThrowIfNull(provider); 122 | 123 | var visitor = new EntityQueryRootExpressionReplaceVisitor(query, set, provider); 124 | var replaced = visitor.Visit(query); 125 | 126 | if (!visitor.QueryWasReplaced) 127 | throw new ArgumentException($"The supplied query does not originate from an {nameof(EntityQueryRootExpression)} and therefore does not come from Entity Framework.", nameof(query)); 128 | 129 | return replaced ?? throw new ArgumentException($"The supplied query resulted in a replaced expression which was null. This should not happen.", nameof(query)); 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/EnumerableExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EntityFrameworkCore.Parallel; 5 | 6 | /// 7 | /// Contains extension methods for . 8 | /// 9 | public static class EnumerableExtensions 10 | { 11 | /// 12 | /// Disposes the after enumeration. 13 | /// 14 | /// The entity type. 15 | /// The source. 16 | /// The database set. 17 | /// 18 | public static IEnumerable DisposeAfterEnumeration(this IEnumerable source, IDisposable dbSet) 19 | => new AutoDisposingEnumerable(source, dbSet); 20 | } 21 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | // This file is used by Code Analysis to maintain SuppressMessage 2 | // attributes that are applied to this project. 3 | // Project-level suppressions either have no target or are given 4 | // a specific target and scoped to a namespace, type, member, etc. 5 | 6 | using System.Diagnostics.CodeAnalysis; 7 | 8 | [assembly: SuppressMessage("Usage", "EF1001:Internal EF Core API usage.", Justification = "This package needs to access EF Core internals to work.")] 9 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/IQueryContext.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | using System.Threading; 3 | 4 | namespace EntityFrameworkCore.Parallel; 5 | 6 | /// 7 | /// Interface for a query context. A query context is the thing that will actually execute any query. 8 | /// 9 | public interface IQueryContext 10 | { 11 | /// 12 | /// Executes the specified query. 13 | /// 14 | /// The type of the result. 15 | /// The query. 16 | /// 17 | TResult Execute(Expression query); 18 | 19 | /// 20 | /// Executes the asynchronous. 21 | /// 22 | /// The type of the result. 23 | /// The query. 24 | /// The cancellation token. 25 | /// 26 | TResult ExecuteAsync(Expression query, CancellationToken cancellationToken); 27 | } -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/Internal/EntityType.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Infrastructure; 3 | using Microsoft.EntityFrameworkCore.Metadata; 4 | using Microsoft.EntityFrameworkCore.Query; 5 | using Microsoft.EntityFrameworkCore.Storage; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq.Expressions; 9 | using System.Reflection; 10 | 11 | namespace EntityFrameworkCore.Parallel.Internal; 12 | 13 | /// 14 | /// This is a minimal implementation of to support the creation of 15 | /// queries without the need of a DbContext. Most of its methods will just throw exceptions. 16 | /// When the query is actually executed, the expression which is started with this class is 17 | /// replaced to contain an instance of the implementation from the real Entity Framework library. 18 | /// 19 | /// The type of the entities in the DbSet. 20 | public class EntityType : IEntityType 21 | { 22 | /// 23 | public IEntityType? BaseType => throw new NotImplementedException(); 24 | 25 | /// 26 | IReadOnlyEntityType? IReadOnlyEntityType.BaseType => throw new NotImplementedException(); 27 | 28 | /// 29 | public Type ClrType => typeof(TEntity); 30 | 31 | /// 32 | public InstantiationBinding? ConstructorBinding => throw new NotImplementedException(); 33 | 34 | /// 35 | public bool HasSharedClrType => throw new NotImplementedException(); 36 | 37 | /// 38 | public bool IsPropertyBag => throw new NotImplementedException(); 39 | 40 | /// 41 | public IModel Model => throw new NotImplementedException(); 42 | 43 | /// 44 | IReadOnlyModel IReadOnlyTypeBase.Model => throw new NotImplementedException(); 45 | 46 | /// 47 | public string Name => throw new NotImplementedException(); 48 | 49 | /// 50 | public InstantiationBinding? ServiceOnlyConstructorBinding => throw new NotImplementedException(); 51 | 52 | /// 53 | public object? this[string name] => throw new NotImplementedException(); 54 | 55 | /// 56 | public IAnnotation AddRuntimeAnnotation(string name, object? value) => throw new NotImplementedException(); 57 | 58 | /// 59 | public IAnnotation? FindAnnotation(string name) => throw new NotImplementedException(); 60 | 61 | /// 62 | public IEnumerable FindDeclaredForeignKeys(IReadOnlyList properties) => throw new NotImplementedException(); 63 | 64 | /// 65 | IEnumerable IReadOnlyEntityType.FindDeclaredForeignKeys(IReadOnlyList properties) => throw new NotImplementedException(); 66 | 67 | /// 68 | public INavigation? FindDeclaredNavigation(string name) => throw new NotImplementedException(); 69 | 70 | /// 71 | IReadOnlyNavigation? IReadOnlyEntityType.FindDeclaredNavigation(string name) => throw new NotImplementedException(); 72 | 73 | /// 74 | public IProperty? FindDeclaredProperty(string name) => throw new NotImplementedException(); 75 | 76 | /// 77 | public ITrigger? FindDeclaredTrigger(string name) => throw new NotImplementedException(); 78 | 79 | /// 80 | IReadOnlyTrigger? IReadOnlyEntityType.FindDeclaredTrigger(string name) => throw new NotImplementedException(); 81 | 82 | /// 83 | public IForeignKey? FindForeignKey(IReadOnlyList properties, IReadOnlyKey principalKey, IReadOnlyEntityType principalEntityType) => throw new NotImplementedException(); 84 | 85 | /// 86 | IReadOnlyForeignKey? IReadOnlyEntityType.FindForeignKey(IReadOnlyList properties, IReadOnlyKey principalKey, IReadOnlyEntityType principalEntityType) => throw new NotImplementedException(); 87 | 88 | /// 89 | public IEnumerable FindForeignKeys(IReadOnlyList properties) => throw new NotImplementedException(); 90 | 91 | /// 92 | IEnumerable IReadOnlyEntityType.FindForeignKeys(IReadOnlyList properties) => throw new NotImplementedException(); 93 | 94 | /// 95 | public IIndex? FindIndex(IReadOnlyList properties) => throw new NotImplementedException(); 96 | 97 | /// 98 | public IIndex? FindIndex(string name) => throw new NotImplementedException(); 99 | 100 | /// 101 | IReadOnlyIndex? IReadOnlyEntityType.FindIndex(IReadOnlyList properties) => throw new NotImplementedException(); 102 | 103 | /// 104 | IReadOnlyIndex? IReadOnlyEntityType.FindIndex(string name) => throw new NotImplementedException(); 105 | 106 | /// 107 | public PropertyInfo? FindIndexerPropertyInfo() => throw new NotImplementedException(); 108 | 109 | /// 110 | public IKey? FindKey(IReadOnlyList properties) => throw new NotImplementedException(); 111 | 112 | /// 113 | IReadOnlyKey? IReadOnlyEntityType.FindKey(IReadOnlyList properties) => throw new NotImplementedException(); 114 | 115 | /// 116 | public IKey? FindPrimaryKey() => throw new NotImplementedException(); 117 | 118 | /// 119 | IReadOnlyKey? IReadOnlyEntityType.FindPrimaryKey() => throw new NotImplementedException(); 120 | 121 | /// 122 | public IReadOnlyList? FindProperties(IReadOnlyList propertyNames) => throw new NotImplementedException(); 123 | 124 | /// 125 | public IProperty? FindProperty(string name) => throw new NotImplementedException(); 126 | 127 | /// 128 | public IAnnotation? FindRuntimeAnnotation(string name) => throw new NotImplementedException(); 129 | 130 | /// 131 | public IServiceProperty? FindServiceProperty(string name) => throw new NotImplementedException(); 132 | 133 | /// 134 | IReadOnlyServiceProperty? IReadOnlyEntityType.FindServiceProperty(string name) => throw new NotImplementedException(); 135 | 136 | /// 137 | public ISkipNavigation? FindSkipNavigation(string name) => throw new NotImplementedException(); 138 | 139 | /// 140 | IReadOnlySkipNavigation? IReadOnlyEntityType.FindSkipNavigation(string name) => throw new NotImplementedException(); 141 | 142 | /// 143 | public IEnumerable GetAnnotations() => throw new NotImplementedException(); 144 | 145 | /// 146 | public ChangeTrackingStrategy GetChangeTrackingStrategy() => throw new NotImplementedException(); 147 | 148 | /// 149 | public IEnumerable GetDeclaredForeignKeys() => throw new NotImplementedException(); 150 | 151 | /// 152 | IEnumerable IReadOnlyEntityType.GetDeclaredForeignKeys() => throw new NotImplementedException(); 153 | 154 | /// 155 | public IEnumerable GetDeclaredIndexes() => throw new NotImplementedException(); 156 | 157 | /// 158 | IEnumerable IReadOnlyEntityType.GetDeclaredIndexes() => throw new NotImplementedException(); 159 | 160 | /// 161 | public IEnumerable GetDeclaredKeys() => throw new NotImplementedException(); 162 | 163 | /// 164 | IEnumerable IReadOnlyEntityType.GetDeclaredKeys() => throw new NotImplementedException(); 165 | 166 | /// 167 | public IEnumerable GetDeclaredNavigations() => throw new NotImplementedException(); 168 | 169 | /// 170 | IEnumerable IReadOnlyEntityType.GetDeclaredNavigations() => throw new NotImplementedException(); 171 | 172 | /// 173 | public IEnumerable GetDeclaredProperties() => throw new NotImplementedException(); 174 | 175 | /// 176 | public IEnumerable GetDeclaredReferencingForeignKeys() => throw new NotImplementedException(); 177 | 178 | /// 179 | IEnumerable IReadOnlyEntityType.GetDeclaredReferencingForeignKeys() => throw new NotImplementedException(); 180 | 181 | /// 182 | public IEnumerable GetDeclaredServiceProperties() => throw new NotImplementedException(); 183 | 184 | /// 185 | IEnumerable IReadOnlyEntityType.GetDeclaredServiceProperties() => throw new NotImplementedException(); 186 | 187 | /// 188 | public IEnumerable GetDeclaredSkipNavigations() => throw new NotImplementedException(); 189 | 190 | /// 191 | public IEnumerable GetDeclaredTriggers() => throw new NotImplementedException(); 192 | 193 | /// 194 | IEnumerable IReadOnlyEntityType.GetDeclaredTriggers() => throw new NotImplementedException(); 195 | 196 | /// 197 | public IEnumerable GetDerivedForeignKeys() => throw new NotImplementedException(); 198 | 199 | /// 200 | IEnumerable IReadOnlyEntityType.GetDerivedForeignKeys() => throw new NotImplementedException(); 201 | 202 | /// 203 | public IEnumerable GetDerivedIndexes() => throw new NotImplementedException(); 204 | 205 | /// 206 | IEnumerable IReadOnlyEntityType.GetDerivedIndexes() => throw new NotImplementedException(); 207 | 208 | /// 209 | public IEnumerable GetDerivedNavigations() => throw new NotImplementedException(); 210 | 211 | /// 212 | public IEnumerable GetDerivedProperties() => throw new NotImplementedException(); 213 | 214 | /// 215 | public IEnumerable GetDerivedServiceProperties() => throw new NotImplementedException(); 216 | 217 | /// 218 | public IEnumerable GetDerivedSkipNavigations() => throw new NotImplementedException(); 219 | 220 | /// 221 | public IEnumerable GetDerivedTypes() => throw new NotImplementedException(); 222 | 223 | /// 224 | public IEnumerable GetDirectlyDerivedTypes() => throw new NotImplementedException(); 225 | 226 | /// 227 | IEnumerable IReadOnlyEntityType.GetDirectlyDerivedTypes() => throw new NotImplementedException(); 228 | 229 | /// 230 | public string? GetDiscriminatorPropertyName() => throw new NotImplementedException(); 231 | 232 | /// 233 | public IEnumerable GetForeignKeyProperties() => throw new NotImplementedException(); 234 | 235 | /// 236 | public IEnumerable GetForeignKeys() => throw new NotImplementedException(); 237 | 238 | /// 239 | IEnumerable IReadOnlyEntityType.GetForeignKeys() => throw new NotImplementedException(); 240 | 241 | /// 242 | public IEnumerable GetIndexes() => throw new NotImplementedException(); 243 | 244 | /// 245 | IEnumerable IReadOnlyEntityType.GetIndexes() => throw new NotImplementedException(); 246 | 247 | /// 248 | public IEnumerable GetKeys() => throw new NotImplementedException(); 249 | 250 | /// 251 | IEnumerable IReadOnlyEntityType.GetKeys() => throw new NotImplementedException(); 252 | 253 | /// 254 | public PropertyAccessMode GetNavigationAccessMode() => throw new NotImplementedException(); 255 | 256 | /// 257 | public IEnumerable GetNavigations() => throw new NotImplementedException(); 258 | 259 | /// 260 | IEnumerable IReadOnlyEntityType.GetNavigations() => throw new NotImplementedException(); 261 | 262 | /// 263 | public TValue GetOrAddRuntimeAnnotationValue(string name, Func valueFactory, TArg? factoryArgument) => throw new NotImplementedException(); 264 | 265 | /// 266 | public IEnumerable GetProperties() => throw new NotImplementedException(); 267 | 268 | /// 269 | public PropertyAccessMode GetPropertyAccessMode() => throw new NotImplementedException(); 270 | 271 | /// 272 | public LambdaExpression? GetQueryFilter() => throw new NotImplementedException(); 273 | 274 | /// 275 | public IEnumerable GetReferencingForeignKeys() => throw new NotImplementedException(); 276 | 277 | /// 278 | IEnumerable IReadOnlyEntityType.GetReferencingForeignKeys() => throw new NotImplementedException(); 279 | 280 | /// 281 | public IEnumerable GetRuntimeAnnotations() => throw new NotImplementedException(); 282 | 283 | /// 284 | public IEnumerable> GetSeedData(bool providerValues = false) => throw new NotImplementedException(); 285 | 286 | /// 287 | public IEnumerable GetServiceProperties() => throw new NotImplementedException(); 288 | 289 | /// 290 | IEnumerable IReadOnlyEntityType.GetServiceProperties() => throw new NotImplementedException(); 291 | 292 | /// 293 | public IEnumerable GetSkipNavigations() => throw new NotImplementedException(); 294 | 295 | /// 296 | IEnumerable IReadOnlyEntityType.GetSkipNavigations() => throw new NotImplementedException(); 297 | 298 | /// 299 | public IEnumerable GetValueGeneratingProperties() => throw new NotImplementedException(); 300 | 301 | /// 302 | public IAnnotation? RemoveRuntimeAnnotation(string name) => throw new NotImplementedException(); 303 | 304 | /// 305 | public IAnnotation SetRuntimeAnnotation(string name, object? value) => throw new NotImplementedException(); 306 | 307 | /// 308 | public bool HasServiceProperties() => throw new NotImplementedException(); 309 | 310 | /// 311 | public Func GetOrCreateMaterializer(IEntityMaterializerSource source) => throw new NotImplementedException(); 312 | 313 | /// 314 | public Func GetOrCreateEmptyMaterializer(IEntityMaterializerSource source) => throw new NotImplementedException(); 315 | 316 | /// 317 | public IComplexProperty? FindComplexProperty(string name) => throw new NotImplementedException(); 318 | 319 | /// 320 | public IEnumerable GetComplexProperties() => throw new NotImplementedException(); 321 | 322 | /// 323 | public IEnumerable GetDeclaredComplexProperties() => throw new NotImplementedException(); 324 | 325 | /// 326 | public IEnumerable GetMembers() => throw new NotImplementedException(); 327 | 328 | /// 329 | public IEnumerable GetDeclaredMembers() => throw new NotImplementedException(); 330 | 331 | /// 332 | public IPropertyBase? FindMember(string name) => throw new NotImplementedException(); 333 | 334 | /// 335 | public IEnumerable FindMembersInHierarchy(string name) => throw new NotImplementedException(); 336 | 337 | /// 338 | public IEnumerable GetSnapshottableMembers() => throw new NotImplementedException(); 339 | 340 | /// 341 | public IEnumerable GetFlattenedProperties() => throw new NotImplementedException(); 342 | 343 | /// 344 | public IEnumerable GetFlattenedComplexProperties() => throw new NotImplementedException(); 345 | 346 | /// 347 | public IEnumerable GetFlattenedDeclaredProperties() => throw new NotImplementedException(); 348 | 349 | /// 350 | IReadOnlyProperty? IReadOnlyTypeBase.FindProperty(string name) => throw new NotImplementedException(); 351 | 352 | /// 353 | IReadOnlyProperty? IReadOnlyTypeBase.FindDeclaredProperty(string name) => throw new NotImplementedException(); 354 | 355 | /// 356 | IEnumerable IReadOnlyTypeBase.GetDeclaredProperties() => throw new NotImplementedException(); 357 | 358 | /// 359 | IEnumerable IReadOnlyTypeBase.GetProperties() => throw new NotImplementedException(); 360 | 361 | /// 362 | IReadOnlyComplexProperty? IReadOnlyTypeBase.FindComplexProperty(string name) => throw new NotImplementedException(); 363 | 364 | /// 365 | public IReadOnlyComplexProperty? FindDeclaredComplexProperty(string name) => throw new NotImplementedException(); 366 | 367 | /// 368 | IEnumerable IReadOnlyTypeBase.GetComplexProperties() => throw new NotImplementedException(); 369 | 370 | /// 371 | IEnumerable IReadOnlyTypeBase.GetDeclaredComplexProperties() => throw new NotImplementedException(); 372 | 373 | /// 374 | public IEnumerable GetDerivedComplexProperties() => throw new NotImplementedException(); 375 | 376 | /// 377 | IEnumerable IReadOnlyTypeBase.GetMembers() => throw new NotImplementedException(); 378 | 379 | /// 380 | IEnumerable IReadOnlyTypeBase.GetDeclaredMembers() => throw new NotImplementedException(); 381 | 382 | /// 383 | IReadOnlyPropertyBase? IReadOnlyTypeBase.FindMember(string name) => throw new NotImplementedException(); 384 | 385 | /// 386 | IEnumerable IReadOnlyTypeBase.FindMembersInHierarchy(string name) => throw new NotImplementedException(); 387 | } -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/Internal/SharedTypeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace EntityFrameworkCore.Parallel.Internal; 7 | 8 | /// 9 | /// Contains extension methods to find the generic type parameter of a collection type. 10 | /// 11 | internal static class SharedTypeExtensions 12 | { 13 | public static Type GetSequenceType(this Type type) 14 | { 15 | var sequenceType = TryGetSequenceType(type) ?? throw new ArgumentException("The given type is not a collection type", nameof(type)); 16 | 17 | return sequenceType; 18 | } 19 | 20 | public static Type? TryGetSequenceType(this Type type) 21 | => type.TryGetElementType(typeof(IEnumerable<>)) 22 | ?? type.TryGetElementType(typeof(IAsyncEnumerable<>)); 23 | 24 | public static Type? TryGetElementType(this Type type, Type interfaceOrBaseType) 25 | { 26 | if (type.IsGenericTypeDefinition) 27 | { 28 | return null; 29 | } 30 | 31 | var types = GetGenericTypeImplementations(type, interfaceOrBaseType); 32 | 33 | Type? singleImplementation = null; 34 | foreach (var implementation in types) 35 | { 36 | if (singleImplementation == null) 37 | { 38 | singleImplementation = implementation; 39 | } 40 | else 41 | { 42 | singleImplementation = null; 43 | break; 44 | } 45 | } 46 | 47 | return singleImplementation?.GenericTypeArguments.FirstOrDefault(); 48 | } 49 | 50 | public static IEnumerable GetGenericTypeImplementations(this Type type, Type interfaceOrBaseType) 51 | { 52 | var typeInfo = type.GetTypeInfo(); 53 | if (!typeInfo.IsGenericTypeDefinition) 54 | { 55 | var baseTypes = interfaceOrBaseType.GetTypeInfo().IsInterface 56 | ? typeInfo.ImplementedInterfaces 57 | : type.GetBaseTypes(); 58 | foreach (var baseType in baseTypes) 59 | { 60 | if (baseType.IsGenericType 61 | && baseType.GetGenericTypeDefinition() == interfaceOrBaseType) 62 | { 63 | yield return baseType; 64 | } 65 | } 66 | 67 | if (type.IsGenericType 68 | && type.GetGenericTypeDefinition() == interfaceOrBaseType) 69 | { 70 | yield return type; 71 | } 72 | } 73 | } 74 | 75 | public static IEnumerable GetBaseTypes(this Type type) 76 | { 77 | var baseType = type.BaseType; 78 | 79 | while (baseType is not null) 80 | { 81 | yield return baseType; 82 | 83 | baseType = baseType.BaseType; 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/EntityFrameworkCore.Parallel/QueryProvider.cs: -------------------------------------------------------------------------------- 1 | using EntityFrameworkCore.Parallel.Internal; 2 | using Microsoft.EntityFrameworkCore.Query; 3 | using Microsoft.EntityFrameworkCore.Query.Internal; 4 | using System; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | using System.Reflection; 8 | using System.Threading; 9 | 10 | namespace EntityFrameworkCore.Parallel; 11 | 12 | /// 13 | /// A basic query provider which will pass the execution logic down the given . 14 | /// 15 | public class QueryProvider : IAsyncQueryProvider 16 | { 17 | private readonly IQueryContext _queryContext; 18 | 19 | private static readonly MethodInfo _genericCreateQueryMethod 20 | = typeof(QueryProvider) 21 | .GetRuntimeMethods() 22 | .Single(m => m.Name == nameof(CreateQuery) && m.IsGenericMethod); 23 | 24 | private readonly MethodInfo _genericExecuteMethod; 25 | 26 | /// 27 | /// Initializes a new instance of the class. 28 | /// 29 | /// The query context. 30 | /// queryContext 31 | public QueryProvider(IQueryContext queryContext) 32 | { 33 | _queryContext = queryContext ?? throw new ArgumentNullException(nameof(queryContext)); 34 | 35 | _genericExecuteMethod = _queryContext.GetType() 36 | .GetRuntimeMethods() 37 | .Single(m => m.Name == nameof(IQueryContext.Execute) && m.IsGenericMethod); 38 | } 39 | 40 | /// 41 | public virtual IQueryable CreateQuery(Expression expression) 42 | { 43 | ArgumentNullException.ThrowIfNull(expression); 44 | 45 | if (_genericCreateQueryMethod 46 | .MakeGenericMethod(expression.Type.GetSequenceType()) 47 | .Invoke(this, [expression]) is not IQueryable queryable) 48 | throw new InvalidOperationException("Unable to create an IQueryable from the given expression."); 49 | 50 | return queryable; 51 | } 52 | 53 | /// 54 | public virtual IQueryable CreateQuery(Expression expression) 55 | { 56 | ArgumentNullException.ThrowIfNull(expression); 57 | 58 | return new EntityQueryable(this, expression); 59 | } 60 | 61 | /// 62 | public virtual object Execute(Expression expression) 63 | { 64 | ArgumentNullException.ThrowIfNull(expression); 65 | 66 | var executeResult = _genericExecuteMethod 67 | .MakeGenericMethod(expression.Type) 68 | .Invoke(_queryContext, [expression]) ?? throw new InvalidOperationException("The execution of the given expression resulted in a null value."); 69 | 70 | return executeResult; 71 | } 72 | 73 | /// 74 | TResult IQueryProvider.Execute(Expression expression) 75 | { 76 | ArgumentNullException.ThrowIfNull(expression); 77 | 78 | return _queryContext.Execute(expression); 79 | } 80 | 81 | /// 82 | public TResult ExecuteAsync(Expression expression, CancellationToken cancellationToken = default) 83 | { 84 | ArgumentNullException.ThrowIfNull(expression); 85 | 86 | return _queryContext.ExecuteAsync(expression, cancellationToken); 87 | } 88 | } -------------------------------------------------------------------------------- /src/EntityFrameworkCore.Parallel/NuGet.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | --------------------------------------------------------------------------------