├── .gitignore ├── EFCore.CommonTools.Benchmarks ├── Context.cs ├── Entities.cs ├── EntityFrameworkCore.CommonTools.Benchmarks.csproj ├── Program.cs └── Querying │ ├── DatabaseQueryBenchmark.cs │ └── EnumerableQueryBenchmark.cs ├── EFCore.CommonTools.Tests ├── AssertExtensions.cs ├── Auditing │ ├── AuditableEntitiesTests.cs │ └── TrackableEntitiesTests.cs ├── Concurrency │ └── ConcurrentEntitiesTests.cs ├── EntityFrameworkCore.CommonTools.Tests.csproj ├── Expression │ └── ExpressionGetValueTests.cs ├── Json │ ├── JsonFieldIntegrationTests.cs │ └── JsonFieldTests.cs ├── Querying │ ├── AsQueryableExpanderTests.cs │ └── ExtensionExpanderTests.cs ├── Specification │ ├── SpecificationExpanderTests.cs │ └── SpecificationTests.cs ├── TestDbContext.cs ├── TestEntities.cs ├── TestInitializer.cs ├── TestLoggerProvider.cs └── TransactionLog │ ├── TransactionExtensionsTests.cs │ └── TransactionLogTests.cs ├── EFCore.CommonTools ├── Auditing │ ├── AuditableEntities.cs │ ├── AuditableEntitiesExtensions.cs │ ├── README.md │ ├── TrackableEntities.cs │ └── TrackableEntitiesExtensions.cs ├── Concurrency │ ├── ConcurrentEntities.cs │ ├── ConcurrentEntitiesExtensions.cs │ └── README.md ├── EntityFrameworkCore.CommonTools.csproj ├── Expression │ ├── ExpressionExtensions.cs │ └── README.md ├── Json │ ├── JsonField.cs │ └── README.md ├── Properties │ └── AssemblyInfo.cs ├── Querying │ ├── AsQueryableExpander.cs │ ├── DbAsyncEnumerator.cs │ ├── ExpandableAttribute.cs │ ├── ExtensionExpander.cs │ ├── ExtensionRebinder.cs │ ├── QueryableExtensions.cs │ ├── README.md │ ├── VisitableQuery.cs │ ├── VisitableQueryProvider.cs │ └── VisitorExtensions.cs ├── Specification │ ├── ParameterReplacer.cs │ ├── README.md │ ├── Specification.cs │ └── SpecificationExpander.cs └── TransactionLog │ ├── README.md │ ├── TransactionExtensions.cs │ ├── TransactionLog.cs │ ├── TransactionLogContext.cs │ └── TransactionLogExtensions.cs ├── EntityFramework.CommonTools.Benchmarks ├── EntityFramework.CommonTools.Benchmarks.csproj ├── Properties │ └── AssemblyInfo.cs ├── app.config └── packages.config ├── EntityFramework.CommonTools.Tests ├── EntityFramework.CommonTools.Tests.csproj ├── Extensions │ ├── ChangeTrackingExtensionsTests.cs │ └── TableNameExtensionsTests.cs ├── Properties │ └── AssemblyInfo.cs ├── TestDbContext.cs ├── TestEntities.cs ├── TestInitializer.cs ├── app.config └── packages.config ├── EntityFramework.CommonTools.sln ├── EntityFramework.CommonTools ├── EntityFramework.CommonTools.csproj ├── EntityFramework.CommonTools.nuspec ├── Extensions │ ├── ChangeTrackingExtensions.cs │ ├── README.md │ └── TableNameExtensions.cs ├── Properties │ └── AssemblyInfo.cs └── packages.config ├── LICENSE ├── README.md ├── appveyor.yml └── icon.png /.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 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Benchmarks/Context.cs: -------------------------------------------------------------------------------- 1 | #if EF_CORE 2 | using Microsoft.Data.Sqlite; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace EntityFrameworkCore.CommonTools.Benchmarks 6 | #else 7 | using System.Data.Common; 8 | using System.Data.Entity; 9 | using System.Data.SQLite; 10 | 11 | namespace EntityFramework.CommonTools.Benchmarks 12 | #endif 13 | { 14 | public class Context : DbContext 15 | { 16 | public DbSet Users { get; set; } 17 | public DbSet Posts { get; set; } 18 | 19 | #if EF_CORE 20 | public Context(SqliteConnection connection) 21 | : base(new DbContextOptionsBuilder().UseSqlite(connection).Options) 22 | { 23 | } 24 | 25 | public static SqliteConnection CreateConnection() 26 | { 27 | var connection = new SqliteConnection("data source=:memory:"); 28 | 29 | connection.Open(); 30 | 31 | using (var context = new Context(connection)) 32 | { 33 | context.Database.EnsureCreated(); 34 | } 35 | 36 | return connection; 37 | } 38 | #else 39 | public Context(DbConnection connection) 40 | : base(connection, false) 41 | { 42 | Database.SetInitializer(null); 43 | } 44 | 45 | public static DbConnection CreateConnection() 46 | { 47 | var connection = new SQLiteConnection("Data Source=:memory:;Version=3;New=True;"); 48 | 49 | connection.Open(); 50 | 51 | using (var context = new Context(connection)) 52 | { 53 | context.Database.ExecuteSqlCommand(@" 54 | CREATE TABLE Users ( 55 | Id INTEGER PRIMARY KEY AUTOINCREMENT, 56 | Login TEXT 57 | ); 58 | 59 | CREATE TABLE Posts ( 60 | Id INTEGER PRIMARY KEY AUTOINCREMENT, 61 | AuthorId INTEGER, 62 | Date DATETIME, 63 | Title TEXT, 64 | Content TEXT 65 | );"); 66 | } 67 | 68 | return connection; 69 | } 70 | #endif 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Benchmarks/Entities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | using System.Linq; 5 | 6 | #if EF_CORE 7 | namespace EntityFrameworkCore.CommonTools.Benchmarks 8 | #else 9 | namespace EntityFramework.CommonTools.Benchmarks 10 | #endif 11 | { 12 | public class User 13 | { 14 | public int Id { get; set; } 15 | public string Login { get; set; } 16 | 17 | [InverseProperty(nameof(Post.Author))] 18 | public virtual ICollection Posts { get; set; } = new HashSet(); 19 | } 20 | 21 | public class Post 22 | { 23 | public int Id { get; set; } 24 | public int AuthorId { get; set; } 25 | public DateTime Date { get; set; } 26 | public string Title { get; set; } 27 | public string Content { get; set; } 28 | 29 | [ForeignKey(nameof(AuthorId))] 30 | public virtual User Author { get; set; } 31 | } 32 | 33 | public static class Extenisons 34 | { 35 | [Expandable] 36 | public static IQueryable FilterToday(this IEnumerable posts) 37 | { 38 | DateTime today = DateTime.Now.Date; 39 | 40 | return posts.AsQueryable().Where(p => p.Date > today); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Benchmarks/EntityFrameworkCore.CommonTools.Benchmarks.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp2.0 6 | 7 | 8 | 9 | TRACE;DEBUG;EF_CORE 10 | 11 | 12 | 13 | TRACE;EF_CORE 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Benchmarks/Program.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Running; 2 | 3 | #if EF_CORE 4 | namespace EntityFrameworkCore.CommonTools.Benchmarks 5 | #else 6 | namespace EntityFramework.CommonTools.Benchmarks 7 | #endif 8 | 9 | { 10 | class Program 11 | { 12 | static void Main(string[] args) 13 | { 14 | new BenchmarkSwitcher(new[] { 15 | typeof(EnumerableQueryBenchmark), 16 | typeof(DatabaseQueryBenchmark), 17 | }).Run(args); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Benchmarks/Querying/DatabaseQueryBenchmark.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using BenchmarkDotNet.Attributes; 4 | 5 | #if EF_CORE 6 | using Microsoft.Data.Sqlite; 7 | 8 | namespace EntityFrameworkCore.CommonTools.Benchmarks 9 | #else 10 | using System.Data.Common; 11 | 12 | namespace EntityFramework.CommonTools.Benchmarks 13 | #endif 14 | { 15 | public class DatabaseQueryBenchmark 16 | { 17 | #if EF_CORE 18 | private readonly SqliteConnection _connection = Context.CreateConnection(); 19 | #else 20 | private readonly DbConnection _connection = Context.CreateConnection(); 21 | #endif 22 | 23 | [Benchmark(Baseline = true)] 24 | public object RawQuery() 25 | { 26 | using (var context = new Context(_connection)) 27 | { 28 | DateTime today = DateTime.Now.Date; 29 | 30 | return context.Users 31 | .Where(u => u.Posts.Any(p => p.Date > today)) 32 | .FirstOrDefault(); 33 | } 34 | } 35 | 36 | [Benchmark] 37 | public object ExpandableQuery() 38 | { 39 | using (var context = new Context(_connection)) 40 | { 41 | return context.Users 42 | .AsExpandable() 43 | .Where(u => u.Posts.FilterToday().Any()) 44 | .ToList(); 45 | } 46 | } 47 | 48 | private readonly Random _random = new Random(); 49 | 50 | [Benchmark] 51 | public object NotCachedQuery() 52 | { 53 | using (var context = new Context(_connection)) 54 | { 55 | int[] postIds = new[] { _random.Next(), _random.Next() }; 56 | 57 | return context.Users 58 | .Where(u => u.Posts.Any(p => postIds.Contains(p.Id))) 59 | .ToList(); 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Benchmarks/Querying/EnumerableQueryBenchmark.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using BenchmarkDotNet.Attributes; 4 | 5 | #if EF_CORE 6 | namespace EntityFrameworkCore.CommonTools.Benchmarks 7 | #else 8 | namespace EntityFramework.CommonTools.Benchmarks 9 | #endif 10 | { 11 | public class EnumerableQueryBenchmark 12 | { 13 | [Benchmark(Baseline = true)] 14 | public object RawQuery() 15 | { 16 | DateTime today = DateTime.Now.Date; 17 | 18 | return Enumerable.Empty() 19 | .AsQueryable() 20 | .Where(u => u.Posts.Any(p => p.Date > today)) 21 | .ToList(); 22 | } 23 | 24 | [Benchmark] 25 | public object ExpandableQuery() 26 | { 27 | return Enumerable.Empty() 28 | .AsQueryable() 29 | .AsExpandable() 30 | .Where(u => u.Posts.FilterToday().Any()) 31 | .ToList(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/AssertExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | 6 | #if EF_CORE 7 | namespace EntityFrameworkCore.CommonTools.Tests 8 | #elif EF_6 9 | namespace EntityFramework.CommonTools.Tests 10 | #endif 11 | { 12 | public static class AssertExtensions 13 | { 14 | private class Visitor : ExpressionVisitor 15 | { 16 | public List Expressions = new List(); 17 | 18 | public override Expression Visit(Expression node) 19 | { 20 | Expressions.Add(node); 21 | return base.Visit(node); 22 | } 23 | } 24 | 25 | public static void MethodCallsAreMatch(this Assert assert, Expression expexted, Expression actual) 26 | { 27 | var expectedVisitor = new Visitor(); 28 | expectedVisitor.Visit(expexted); 29 | var expectedList = expectedVisitor.Expressions; 30 | 31 | var actualVisitor = new Visitor(); 32 | actualVisitor.Visit(actual); 33 | var actualList = actualVisitor.Expressions; 34 | 35 | Assert.AreEqual(expectedList.Count, actualList.Count); 36 | 37 | for (int i = 0; i < expectedList.Count; i++) 38 | { 39 | if (expectedList[i] != null && expectedList[i].NodeType == ExpressionType.Call) 40 | { 41 | Assert.AreEqual(ExpressionType.Call, actualList[i].NodeType); 42 | 43 | var expectedCall = (MethodCallExpression)expectedList[i]; 44 | var actualCall = (MethodCallExpression)actualList[i]; 45 | 46 | Assert.AreEqual(expectedCall.Method, actualCall.Method); 47 | } 48 | } 49 | } 50 | 51 | public static void SequenceEqual(this Assert assert, IEnumerable expexted, IEnumerable actual) 52 | { 53 | expexted = expexted.ToList(); 54 | actual = actual.ToList(); 55 | 56 | Assert.AreEqual(expexted.Count(), actual.Count()); 57 | Assert.IsTrue(expexted.SequenceEqual(actual)); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/Auditing/TrackableEntitiesTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | #if EF_CORE 5 | namespace EntityFrameworkCore.CommonTools.Tests 6 | #elif EF_6 7 | namespace EntityFramework.CommonTools.Tests 8 | #endif 9 | { 10 | [TestClass] 11 | public class TrackableEntitiesTests : TestInitializer 12 | { 13 | [TestMethod] 14 | public void TestTrackableEntities() 15 | { 16 | using (var context = CreateInMemoryDbContext()) 17 | { 18 | // insert 19 | var user = new User(); 20 | context.Users.Add(user); 21 | 22 | context.SaveChanges(); 23 | 24 | context.Entry(user).Reload(); 25 | Assert.AreEqual(DateTime.UtcNow.Date, user.CreatedUtc.ToUniversalTime().Date); 26 | 27 | // update 28 | user.Login = "admin"; 29 | 30 | context.SaveChanges(); 31 | 32 | context.Entry(user).Reload(); 33 | Assert.IsNotNull(user.UpdatedUtc); 34 | Assert.AreEqual(DateTime.UtcNow.Date, user.UpdatedUtc?.ToUniversalTime().Date); 35 | 36 | // delete 37 | context.Users.Remove(user); 38 | 39 | context.SaveChanges(); 40 | 41 | context.Entry(user).Reload(); 42 | Assert.AreEqual(true, user.IsDeleted); 43 | Assert.IsNotNull(user.DeletedUtc); 44 | Assert.AreEqual(DateTime.UtcNow.Date, user.DeletedUtc?.ToUniversalTime().Date); 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/Concurrency/ConcurrentEntitiesTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | 6 | #if EF_CORE 7 | using Microsoft.EntityFrameworkCore; 8 | 9 | namespace EntityFrameworkCore.CommonTools.Tests 10 | #elif EF_6 11 | using System.Data.Entity.Infrastructure; 12 | 13 | namespace EntityFramework.CommonTools.Tests 14 | #endif 15 | { 16 | [TestClass] 17 | public class ConcurrentEntitiesTests : TestInitializer 18 | { 19 | [TestMethod, ExpectedException(typeof(DbUpdateConcurrencyException))] 20 | public void TestConcurrencyCheckableGuidEntities() 21 | { 22 | using (var context = CreateSqliteDbContext()) 23 | { 24 | var user = new User(); 25 | context.Users.Add(user); 26 | 27 | // insert 28 | var post = new Post { Title = "first", Author = user }; 29 | context.Posts.Add(post); 30 | 31 | context.SaveChanges(); 32 | 33 | context.Entry(post).Reload(); 34 | Assert.AreEqual(default(Guid), post.RowVersion); 35 | 36 | // update 37 | Guid oldRowVersion = post.RowVersion; 38 | post.Title = "second"; 39 | 40 | try 41 | { 42 | context.SaveChanges(); 43 | 44 | context.Entry(post).Reload(); 45 | Assert.AreNotEqual(oldRowVersion, post.RowVersion); 46 | } 47 | catch (DbUpdateConcurrencyException) 48 | { 49 | Assert.Fail(); 50 | } 51 | 52 | // RowVersion is changed by client code 53 | post.Title = "third"; 54 | post.RowVersion = oldRowVersion; 55 | 56 | // should throw DbUpdateConcurrencyException 57 | context.SaveChanges(); 58 | } 59 | } 60 | 61 | [TestMethod, ExpectedException(typeof(DbUpdateConcurrencyException))] 62 | public void TestConcurrencyCheckableLongEntities() 63 | { 64 | using (var context = CreateSqliteDbContext()) 65 | { 66 | // insert 67 | var settings = new Settings { Key = "first", Value = "first" }; 68 | context.Settings.Add(settings); 69 | 70 | context.SaveChanges(); 71 | 72 | context.Entry(settings).Reload(); 73 | Assert.AreEqual(default(long), settings.RowVersion); 74 | 75 | // update 76 | long oldRowVersion = settings.RowVersion; 77 | settings.Value = "second"; 78 | 79 | try 80 | { 81 | context.SaveChanges(); 82 | 83 | context.Entry(settings).Reload(); 84 | Assert.AreNotEqual(oldRowVersion, settings.RowVersion); 85 | } 86 | catch (DbUpdateConcurrencyException) 87 | { 88 | Assert.Fail(); 89 | } 90 | 91 | // RowVersion is changed by client code 92 | settings.Value = "third"; 93 | settings.RowVersion = oldRowVersion; 94 | 95 | // should throw DbUpdateConcurrencyException 96 | context.SaveChanges(); 97 | } 98 | } 99 | 100 | [TestMethod, ExpectedException(typeof(DbUpdateConcurrencyException))] 101 | public void TestConcurrencyCheckableDelete() 102 | { 103 | using (var context = CreateSqliteDbContext()) 104 | { 105 | var first = new Role { Name = "first" }; 106 | var second = new Role { Name = "second" }; 107 | 108 | try 109 | { 110 | context.Roles.Add(first); 111 | context.Roles.Add(second); 112 | context.SaveChanges(); 113 | 114 | first.Name = "changed"; 115 | second.Name = "changed"; 116 | context.SaveChanges(); 117 | } 118 | catch (DbUpdateConcurrencyException) 119 | { 120 | Assert.Fail(); 121 | } 122 | } 123 | 124 | using (var context = CreateSqliteDbContext()) 125 | { 126 | var role = context.Roles.First(); 127 | 128 | context.Roles.Remove(role); 129 | 130 | try 131 | { 132 | context.SaveChanges(); 133 | } 134 | catch (DbUpdateConcurrencyException) 135 | { 136 | Assert.Fail(); 137 | } 138 | } 139 | 140 | using (var context = CreateSqliteDbContext()) 141 | { 142 | var role = context.Roles.Single(); 143 | 144 | // RowVersion is changed by client code 145 | role.RowVersion = Guid.NewGuid(); 146 | 147 | context.Roles.Remove(role); 148 | 149 | // should throw DbUpdateConcurrencyException 150 | context.SaveChanges(); 151 | } 152 | } 153 | 154 | [TestMethod] 155 | public void TestSaveChangesIgnoreConcurrency() 156 | { 157 | Guid rowVersionFromClient = Guid.NewGuid(); 158 | 159 | using (var context = CreateSqliteDbContext()) 160 | { 161 | var user = new User(); 162 | context.Users.Add(user); 163 | 164 | // insert 165 | var post = new Post { Title = "first", Author = user }; 166 | context.Posts.Add(post); 167 | 168 | context.SaveChanges(); 169 | 170 | // update 171 | post.RowVersion = rowVersionFromClient; 172 | post.Title = "second"; 173 | 174 | context.SaveChangesIgnoreConcurrency(); 175 | 176 | context.Entry(post).Reload(); 177 | Assert.AreEqual("second", post.Title); 178 | Assert.AreNotEqual(rowVersionFromClient, post.RowVersion); 179 | } 180 | } 181 | 182 | [TestMethod] 183 | public async Task TestSaveChangesIgnoreConcurrencyAsync() 184 | { 185 | Guid rowVersionFromClient = Guid.NewGuid(); 186 | 187 | using (var context = CreateSqliteDbContext()) 188 | { 189 | var user = new User(); 190 | context.Users.Add(user); 191 | 192 | // insert 193 | var post = new Post { Title = "first", Author = user }; 194 | context.Posts.Add(post); 195 | 196 | await context.SaveChangesAsync(); 197 | 198 | // update 199 | post.RowVersion = rowVersionFromClient; 200 | post.Title = "second"; 201 | 202 | await context.SaveChangesIgnoreConcurrencyAsync(); 203 | 204 | context.Entry(post).Reload(); 205 | Assert.AreEqual("second", post.Title); 206 | Assert.AreNotEqual(rowVersionFromClient, post.RowVersion); 207 | } 208 | } 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/EntityFrameworkCore.CommonTools.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp2.0 5 | 6 | 7 | 8 | TRACE;DEBUG;EF_CORE 9 | 10 | 11 | 12 | TRACE;EF_CORE 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/Expression/ExpressionGetValueTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System.Collections.Generic; 5 | 6 | #if EF_CORE 7 | namespace EntityFrameworkCore.CommonTools.Tests 8 | #elif EF_6 9 | namespace EntityFramework.CommonTools.Tests 10 | #endif 11 | { 12 | [TestClass] 13 | public class ExpressionGetValueTests 14 | { 15 | [TestMethod] 16 | public void ShouldAcceptConstant() 17 | { 18 | Expression> expression = () => 123; 19 | 20 | object value = expression.Body.GetValue(); 21 | 22 | Assert.AreEqual(123, value); 23 | } 24 | 25 | [TestMethod] 26 | public void ShouldAcceptClosure() 27 | { 28 | int expected = 123; 29 | 30 | Expression> expression = () => expected; 31 | 32 | object value = expression.Body.GetValue(); 33 | 34 | Assert.AreEqual(expected, value); 35 | } 36 | 37 | public int ClassField = 123; 38 | 39 | [TestMethod] 40 | public void ShouldAcceptClassField() 41 | { 42 | Expression> expression = () => ClassField; 43 | 44 | object value = expression.Body.GetValue(); 45 | 46 | Assert.AreEqual(ClassField, value); 47 | } 48 | 49 | public int ClassProperty { get; set; } = 456; 50 | 51 | [TestMethod] 52 | public void ShouldAcceptClassProperty() 53 | { 54 | Expression> expression = () => ClassProperty; 55 | 56 | object value = expression.Body.GetValue(); 57 | 58 | Assert.AreEqual(ClassProperty, value); 59 | } 60 | 61 | class TestObject 62 | { 63 | public int Field; 64 | public int Property { get; set; } 65 | public int? Nullable { get; set; } 66 | public int this[int i, int j] => i * j; 67 | } 68 | 69 | [TestMethod] 70 | public void ShouldAcceptObjectField() 71 | { 72 | var obj = new TestObject { Field = 123 }; 73 | 74 | Expression> expression = () => obj.Field; 75 | 76 | object value = expression.Body.GetValue(); 77 | 78 | Assert.AreEqual(obj.Field, value); 79 | } 80 | 81 | [TestMethod] 82 | public void ShouldAcceptObjectProperty() 83 | { 84 | var obj = new TestObject { Property = 456 }; 85 | 86 | Expression> expression = () => obj.Property; 87 | 88 | object value = expression.Body.GetValue(); 89 | 90 | Assert.AreEqual(obj.Property, value); 91 | } 92 | 93 | [TestMethod] 94 | public void ShouldAcceptNullableConversion() 95 | { 96 | var obj = new TestObject { Nullable = 456 }; 97 | 98 | Expression> expression = () => obj.Nullable; 99 | 100 | object value = expression.Body.GetValue(); 101 | 102 | Assert.AreEqual(obj.Nullable, value); 103 | } 104 | 105 | [TestMethod] 106 | public void ShouldAcceptObjectConversion() 107 | { 108 | var expected = new TestObject(); 109 | 110 | Expression> expression = () => expected; 111 | 112 | object value = expression.Body.GetValue(); 113 | 114 | Assert.AreEqual(expected, value); 115 | } 116 | 117 | [TestMethod] 118 | public void ShouldAcceptObjectIndexer() 119 | { 120 | var obj = new TestObject(); 121 | int i = 123; 122 | int j = 456; 123 | 124 | Expression> expression = () => obj[i, j]; 125 | 126 | object value = expression.Body.GetValue(); 127 | 128 | Assert.AreEqual(i * j, value); 129 | } 130 | 131 | [TestMethod] 132 | public void ShouldAcceptListIndexer() 133 | { 134 | IReadOnlyList list = new List { 1, 2, 3 }; 135 | int i = 1; 136 | 137 | Expression> expression = () => list[i]; 138 | 139 | object value = expression.Body.GetValue(); 140 | 141 | Assert.AreEqual(list[i], value); 142 | } 143 | 144 | [TestMethod] 145 | public void ShouldAcceptArrayIndexer() 146 | { 147 | var arr = new[] { 1, 2, 3 }; 148 | int i = 1; 149 | 150 | Expression> expression = () => arr[i]; 151 | 152 | object value = expression.Body.GetValue(); 153 | 154 | Assert.AreEqual(arr[i], value); 155 | } 156 | 157 | [TestMethod] 158 | public void ShouldAcceptArrayLength() 159 | { 160 | var arr = new[] { 1, 2, 3 }; 161 | 162 | Expression> expression = () => arr.Length; 163 | 164 | object value = expression.Body.GetValue(); 165 | 166 | Assert.AreEqual(arr.Length, value); 167 | } 168 | 169 | [TestMethod] 170 | public void ShouldAcceptComplexExpressions() 171 | { 172 | var obj = new TestObject { Field = 123, Nullable = 123 }; 173 | var list = new List { 1, 2, 3 }; 174 | 175 | int expected = obj[list[2], (int)obj.Nullable]; 176 | 177 | Expression> expression = () => obj[list[2], (int)obj.Nullable]; 178 | 179 | object value = expression.Body.GetValue(); 180 | 181 | Assert.AreEqual(expected, value); 182 | } 183 | 184 | [TestMethod] 185 | public void ShouldFallBackToExpressionCompile() 186 | { 187 | int expected = 123; 188 | 189 | Expression> expression = () => expected * expected; 190 | 191 | object value = expression.Body.GetValue(); 192 | 193 | Assert.AreEqual(expected * expected, value); 194 | } 195 | 196 | [TestMethod, ExpectedException(typeof(InvalidOperationException))] 197 | public void ShouldFailWithOpenParams() 198 | { 199 | int expected = 123; 200 | 201 | Expression> expression = num => num * expected; 202 | 203 | object value = expression.Body.GetValue(); 204 | } 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/Json/JsonFieldIntegrationTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | 3 | #if EF_CORE 4 | namespace EntityFrameworkCore.CommonTools.Tests 5 | #elif EF_6 6 | namespace EntityFramework.CommonTools.Tests 7 | #endif 8 | { 9 | [TestClass] 10 | public class JsonFieldIntegrationTests : TestInitializer 11 | { 12 | [TestMethod] 13 | public void TestJsonFieldWithDbContext() 14 | { 15 | using (var context = CreateSqliteDbContext()) 16 | { 17 | var settings = new Settings 18 | { 19 | Key = "first", 20 | Value = new { Number = 123, String = "test" }, 21 | }; 22 | 23 | context.Settings.Add(settings); 24 | 25 | context.SaveChanges(); 26 | } 27 | 28 | using (var context = CreateSqliteDbContext()) 29 | { 30 | var settings = context.Settings.Find("first"); 31 | 32 | Assert.IsNotNull(settings); 33 | Assert.IsNotNull(settings.Value); 34 | Assert.AreEqual(123, (int)settings.Value.Number); 35 | Assert.AreEqual("test", (string)settings.Value.String); 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/Querying/AsQueryableExpanderTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | #if EF_CORE 5 | namespace EntityFrameworkCore.CommonTools.Tests 6 | #elif EF_6 7 | namespace EntityFramework.CommonTools.Tests 8 | #endif 9 | { 10 | [TestClass] 11 | public class AsQueryableExpanderTests 12 | { 13 | [TestMethod] 14 | public void ShouldExpandAsQueryable() 15 | { 16 | var query = Enumerable.Empty() 17 | .AsQueryable() 18 | .AsVisitable(new AsQueryableExpander()) 19 | .Where(u => u.Posts 20 | .AsQueryable() 21 | .OfType() 22 | .OrderBy(p => p.CreatedUtc) 23 | .ThenBy(p => p.UpdatedUtc) 24 | .ThenByDescending(p => p.Id) 25 | .Select(p => p.Tags 26 | .AsQueryable() 27 | .Count()) 28 | .Average() > 10) 29 | .SelectMany(u => u.Posts 30 | .AsQueryable() 31 | .Where(p => !p.IsDeleted) 32 | .SelectMany(p => p.Author.Posts 33 | .Where(ap => ap.Title == "test") 34 | .AsQueryable() 35 | .Select(ap => ap.Author))); 36 | 37 | var expected = Enumerable.Empty() 38 | .AsQueryable() 39 | .Where(u => u.Posts 40 | .OfType() 41 | .OrderBy(p => p.CreatedUtc) 42 | .ThenBy(p => p.UpdatedUtc) 43 | .ThenByDescending(p => p.Id) 44 | .Select(p => p.Tags 45 | .Count()) 46 | .Average() > 10) 47 | .SelectMany(u => u.Posts 48 | .Where(p => !p.IsDeleted) 49 | .SelectMany(p => p.Author.Posts 50 | .Where(ap => ap.Title == "test") 51 | .Select(ap => ap.Author))); 52 | 53 | Assert.AreNotSame(expected.Expression, query.Expression); 54 | 55 | Assert.That.MethodCallsAreMatch(expected.Expression, query.Expression); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/Specification/SpecificationTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | #if EF_CORE 6 | namespace EntityFrameworkCore.CommonTools.Tests 7 | #elif EF_6 8 | namespace EntityFramework.CommonTools.Tests 9 | #endif 10 | { 11 | [TestClass] 12 | public class SpecificationTests : TestInitializer 13 | { 14 | public class UserActiveSpec : Specification 15 | { 16 | public UserActiveSpec() 17 | { 18 | Predicate = u => !u.IsDeleted; 19 | } 20 | } 21 | 22 | public class UserByLoginSpec : Specification 23 | { 24 | public UserByLoginSpec(string login) 25 | { 26 | Predicate = u => u.Login == login; 27 | } 28 | } 29 | 30 | public class UserAndSpec : Specification 31 | { 32 | public UserAndSpec(string login) 33 | : base(new UserActiveSpec() && new UserByLoginSpec(login)) { } 34 | } 35 | 36 | public class UserOrSpec : Specification 37 | { 38 | public UserOrSpec(string login) 39 | { 40 | Predicate = new UserActiveSpec() || new UserByLoginSpec(login); 41 | } 42 | } 43 | 44 | [TestMethod] 45 | public void SouldConsumePlainObjects() 46 | { 47 | var activeUser = new User { IsDeleted = false }; 48 | var deletedUser = new User { IsDeleted = true }; 49 | 50 | var spec = new UserActiveSpec(); 51 | 52 | Assert.IsTrue(spec.IsSatisfiedBy(activeUser)); 53 | Assert.IsFalse(spec.IsSatisfiedBy(deletedUser)); 54 | } 55 | 56 | [TestMethod] 57 | public void SouldAcceptParameters() 58 | { 59 | var admin = new User { Login = "admin" }; 60 | 61 | var spec = new UserByLoginSpec("admin"); 62 | 63 | Assert.IsTrue(spec.IsSatisfiedBy(admin)); 64 | } 65 | 66 | [TestMethod] 67 | public void ShouldSupportComposition() 68 | { 69 | var activeAdmin = new User { Login = "admin", IsDeleted = false }; 70 | var deletedAdmin = new User { Login = "admin", IsDeleted = true }; 71 | 72 | var andSpec = new UserAndSpec("admin"); 73 | 74 | Assert.IsTrue(andSpec.IsSatisfiedBy(activeAdmin)); 75 | Assert.IsFalse(andSpec.IsSatisfiedBy(deletedAdmin)); 76 | 77 | var orSpec = new UserOrSpec("admin"); 78 | 79 | Assert.IsTrue(orSpec.IsSatisfiedBy(activeAdmin)); 80 | Assert.IsTrue(orSpec.IsSatisfiedBy(deletedAdmin)); 81 | } 82 | 83 | [TestMethod] 84 | public void ShouldSupportConditionalLogic() 85 | { 86 | var activeAdmin = new User { Login = "admin", IsDeleted = false }; 87 | var deletedAdmin = new User { Login = "admin", IsDeleted = true }; 88 | 89 | var andSpec = new UserActiveSpec() && new UserByLoginSpec("admin"); 90 | 91 | Assert.IsTrue(andSpec.IsSatisfiedBy(activeAdmin)); 92 | Assert.IsFalse(andSpec.IsSatisfiedBy(deletedAdmin)); 93 | 94 | var orSpec = new UserActiveSpec() || new UserByLoginSpec("admin"); 95 | 96 | Assert.IsTrue(orSpec.IsSatisfiedBy(activeAdmin)); 97 | Assert.IsTrue(orSpec.IsSatisfiedBy(deletedAdmin)); 98 | 99 | var notSpec = !new UserByLoginSpec("admin"); 100 | 101 | Assert.IsFalse(notSpec.IsSatisfiedBy(activeAdmin)); 102 | Assert.IsFalse(notSpec.IsSatisfiedBy(deletedAdmin)); 103 | } 104 | 105 | [TestMethod] 106 | public void ShouldSupportComplexExpressions() 107 | { 108 | var user = new User 109 | { 110 | IsDeleted = false, 111 | Posts = new List 112 | { 113 | new Post { IsDeleted = false }, 114 | }, 115 | }; 116 | 117 | var activeUserSpec = new Specification(u => !u.IsDeleted); 118 | var hasPostsSpec = new Specification(u => u.Posts.Any(p => !p.IsDeleted)); 119 | var validUserSpec = activeUserSpec && hasPostsSpec; 120 | 121 | Assert.IsTrue(validUserSpec.IsSatisfiedBy(user)); 122 | } 123 | 124 | [TestMethod] 125 | public void ShouldWorkWithEnumerable() 126 | { 127 | var users = new[] 128 | { 129 | new User { Login = "admin", IsDeleted = false }, 130 | new User { Login = "admin", IsDeleted = true }, 131 | }; 132 | 133 | var andSpec = new UserAndSpec("admin"); 134 | 135 | users.Where(andSpec.IsSatisfiedBy).Single(); 136 | 137 | users.Where(andSpec).Single(); 138 | } 139 | 140 | [TestMethod] 141 | public void ShouldWorkWithQueryable() 142 | { 143 | using (var context = CreateSqliteDbContext()) 144 | { 145 | context.Users.AddRange(new[] 146 | { 147 | new User { Login = "admin", IsDeleted = false }, 148 | new User { Login = "admin", IsDeleted = true }, 149 | }); 150 | 151 | context.SaveChanges(); 152 | 153 | var andSpec = new UserAndSpec("admin"); 154 | 155 | context.Users.Where(andSpec.ToExpression()).Single(); 156 | 157 | context.Users.Where(andSpec).Single(); 158 | 159 | } 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/TestDbContext.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | using Microsoft.Data.Sqlite; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Diagnostics; 6 | 7 | namespace EntityFrameworkCore.CommonTools.Tests 8 | { 9 | public class TestDbContext : DbContext 10 | { 11 | public DbSet Roles { get; set; } 12 | public DbSet Users { get; set; } 13 | public DbSet Posts { get; set; } 14 | public DbSet Settings { get; set; } 15 | 16 | public DbSet TransactionLogs { get; set; } 17 | 18 | public TestDbContext(string databaseName) 19 | : base(new DbContextOptionsBuilder() 20 | .UseInMemoryDatabase(databaseName) 21 | .UseLoggerFactory(TestLoggerProvider.MakeLoggerFactory()) 22 | .ConfigureWarnings(warnings => 23 | { 24 | warnings.Log(InMemoryEventId.TransactionIgnoredWarning); 25 | }) 26 | .Options) 27 | { 28 | Database.EnsureCreated(); 29 | } 30 | 31 | public TestDbContext(SqliteConnection connection) 32 | : base(new DbContextOptionsBuilder() 33 | .UseSqlite(connection) 34 | .UseLoggerFactory(TestLoggerProvider.MakeLoggerFactory()) 35 | .ConfigureWarnings(warnings => 36 | { 37 | warnings.Log(InMemoryEventId.TransactionIgnoredWarning); 38 | }) 39 | .Options) 40 | { 41 | Database.EnsureCreated(); 42 | 43 | Database.ExecuteSqlCommand(@" 44 | CREATE TRIGGER IF NOT EXISTS TRG_Settings_UPD 45 | AFTER UPDATE ON Settings 46 | WHEN old.RowVersion = new.RowVersion 47 | BEGIN 48 | UPDATE Settings 49 | SET RowVersion = RowVersion + 1; 50 | END;"); 51 | } 52 | 53 | protected override void OnModelCreating(ModelBuilder modelBuilder) 54 | { 55 | modelBuilder.UseTransactionLog(); 56 | 57 | modelBuilder.Entity() 58 | .Property(s => s.RowVersion) 59 | .HasDefaultValue(0); 60 | } 61 | 62 | public override int SaveChanges(bool acceptAllChangesOnSuccess) 63 | { 64 | this.UpdateTrackableEntities(); 65 | this.UpdateConcurrentEntities(); 66 | 67 | return this.SaveChangesWithTransactionLog(base.SaveChanges, acceptAllChangesOnSuccess); 68 | } 69 | 70 | public override Task SaveChangesAsync( 71 | bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken)) 72 | { 73 | this.UpdateTrackableEntities(); 74 | this.UpdateConcurrentEntities(); 75 | 76 | return this.SaveChangesWithTransactionLogAsync( 77 | base.SaveChangesAsync, acceptAllChangesOnSuccess, cancellationToken); 78 | } 79 | 80 | public int SaveChanges(int editorUserId) 81 | { 82 | this.UpdateAuditableEntities(editorUserId); 83 | 84 | return SaveChanges(); 85 | } 86 | 87 | public Task SaveChangesAsync(string editorUserId) 88 | { 89 | this.UpdateAuditableEntities(editorUserId); 90 | 91 | return SaveChangesAsync(); 92 | } 93 | 94 | public void OriginalSaveChanges() 95 | { 96 | base.SaveChanges(true); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/TestEntities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | using System.Runtime.Serialization; 6 | 7 | namespace EntityFrameworkCore.CommonTools.Tests 8 | { 9 | public abstract class Entity 10 | { 11 | public int Id { get; set; } 12 | } 13 | 14 | public class Role : Entity, IConcurrencyCheckable, ITransactionLoggable 15 | { 16 | public string Name { get; set; } 17 | 18 | [ConcurrencyCheck] 19 | public Guid RowVersion { get; set; } 20 | } 21 | 22 | public class User : Entity, IFullTrackable, ITransactionLoggable 23 | { 24 | public string Login { get; set; } 25 | 26 | [Column("UserContacts")] 27 | public string Contacts { get; set; } 28 | 29 | public bool IsDeleted { get; set; } 30 | public DateTime CreatedUtc { get; set; } 31 | public DateTime? UpdatedUtc { get; set; } 32 | public DateTime? DeletedUtc { get; set; } 33 | 34 | [InverseProperty(nameof(Post.Author))] 35 | public virtual ICollection Posts { get; set; } = new HashSet(); 36 | } 37 | 38 | public class Post : Entity, IFullAuditable, IConcurrencyCheckable, ITransactionLoggable 39 | { 40 | public string Title { get; set; } 41 | public string Content { get; set; } 42 | 43 | private JsonField> _tags = new HashSet(); 44 | 45 | public bool ShouldSerializeTagsJson() => false; 46 | 47 | public string TagsJson 48 | { 49 | get { return _tags.Json; } 50 | set { _tags.Json = value; } 51 | } 52 | 53 | [NotMapped] 54 | public ICollection Tags 55 | { 56 | get { return _tags.Object; } 57 | set { _tags.Object = value; } 58 | } 59 | 60 | public bool IsDeleted { get; set; } 61 | public int CreatorUserId { get; set; } 62 | public DateTime CreatedUtc { get; set; } 63 | public int? UpdaterUserId { get; set; } 64 | public DateTime? UpdatedUtc { get; set; } 65 | public int? DeleterUserId { get; set; } 66 | public DateTime? DeletedUtc { get; set; } 67 | 68 | [ConcurrencyCheck] 69 | public Guid RowVersion { get; set; } 70 | 71 | [ForeignKey(nameof(CreatorUserId))] 72 | public virtual User Author { get; set; } 73 | } 74 | 75 | [Table("Settings")] 76 | public class Settings : IFullAuditable, IConcurrencyCheckable 77 | { 78 | [Key] 79 | public string Key { get; set; } 80 | 81 | private JsonField _value; 82 | 83 | [Column("Value"), IgnoreDataMember] 84 | public string ValueJson 85 | { 86 | get { return _value.Json; } 87 | set { _value.Json = value; } 88 | } 89 | 90 | [NotMapped] 91 | public dynamic Value 92 | { 93 | get { return _value.Object; } 94 | set { _value.Object = value; } 95 | } 96 | 97 | public bool IsDeleted { get; set; } 98 | public string CreatorUserId { get; set; } 99 | public DateTime CreatedUtc { get; set; } 100 | public string UpdaterUserId { get; set; } 101 | public DateTime? UpdatedUtc { get; set; } 102 | public string DeleterUserId { get; set; } 103 | public DateTime? DeletedUtc { get; set; } 104 | 105 | [ConcurrencyCheck] 106 | [DatabaseGenerated(DatabaseGeneratedOption.Computed)] 107 | public long RowVersion { get; set; } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/TestInitializer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Data.Sqlite; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | namespace EntityFrameworkCore.CommonTools.Tests 5 | { 6 | [TestClass] 7 | public abstract class TestInitializer 8 | { 9 | private SqliteConnection _connection; 10 | 11 | public TestContext TestContext { get; set; } 12 | 13 | protected string GetInMemoryDbName() 14 | { 15 | return $"{TestContext.FullyQualifiedTestClassName}.{TestContext.TestName}"; 16 | } 17 | 18 | protected TestDbContext CreateInMemoryDbContext() 19 | { 20 | return new TestDbContext(GetInMemoryDbName()); 21 | } 22 | 23 | protected TestDbContext CreateSqliteDbContext() 24 | { 25 | return new TestDbContext(_connection); 26 | } 27 | 28 | [TestInitialize] 29 | public void TestInitialize() 30 | { 31 | _connection = new SqliteConnection("data source=:memory:"); 32 | 33 | _connection.Open(); 34 | } 35 | 36 | [TestCleanup] 37 | public void TestCleanup() 38 | { 39 | _connection.Close(); 40 | 41 | using (var context = CreateInMemoryDbContext()) 42 | { 43 | context.Database.EnsureDeleted(); 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/TestLoggerProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using Microsoft.Extensions.Logging; 4 | 5 | namespace EntityFrameworkCore.CommonTools.Tests 6 | { 7 | public class TestLoggerProvider : ILoggerProvider 8 | { 9 | public ILogger CreateLogger(string categoryName) 10 | { 11 | return new DebugLogger(); 12 | } 13 | 14 | public void Dispose() { } 15 | 16 | private class DebugLogger : ILogger 17 | { 18 | public bool IsEnabled(LogLevel logLevel) 19 | { 20 | return true; 21 | } 22 | 23 | public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) 24 | { 25 | Debug.WriteLine(formatter(state, exception)); 26 | } 27 | 28 | public IDisposable BeginScope(TState state) 29 | { 30 | return null; 31 | } 32 | } 33 | 34 | public static LoggerFactory MakeLoggerFactory() 35 | { 36 | var factory = new LoggerFactory(); 37 | factory.AddProvider(new TestLoggerProvider()); 38 | return factory; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /EFCore.CommonTools.Tests/TransactionLog/TransactionExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | #if EF_CORE 5 | namespace EntityFrameworkCore.CommonTools.Tests 6 | #elif EF_6 7 | namespace EntityFramework.CommonTools.Tests 8 | #endif 9 | { 10 | [TestClass] 11 | public class TransactionExtensionsTests : TestInitializer 12 | { 13 | [TestMethod] 14 | public void ShouldCreateNewTransaction() 15 | { 16 | using (var context = CreateSqliteDbContext()) 17 | { 18 | Assert.IsNull(context.Database.CurrentTransaction); 19 | 20 | int methodCalls = 0; 21 | 22 | context.ExecuteInTransaction(() => 23 | { 24 | methodCalls++; 25 | 26 | Assert.IsNotNull(context.Database.CurrentTransaction); 27 | 28 | return 0; 29 | }); 30 | 31 | Assert.IsNull(context.Database.CurrentTransaction); 32 | Assert.AreEqual(1, methodCalls); 33 | } 34 | } 35 | 36 | [TestMethod] 37 | public async Task ShouldCreateNewTransactionAsync() 38 | { 39 | using (var context = CreateSqliteDbContext()) 40 | { 41 | Assert.IsNull(context.Database.CurrentTransaction); 42 | 43 | int methodCalls = 0; 44 | 45 | await context.ExecuteInTransaction(async () => 46 | { 47 | methodCalls++; 48 | 49 | Assert.IsNotNull(context.Database.CurrentTransaction); 50 | 51 | await Task.Delay(1); 52 | 53 | return 0; 54 | }); 55 | 56 | Assert.IsNull(context.Database.CurrentTransaction); 57 | Assert.AreEqual(1, methodCalls); 58 | } 59 | } 60 | 61 | [TestMethod] 62 | public void ShouldPreserveExistingTransaction() 63 | { 64 | using (var context = CreateSqliteDbContext()) 65 | using (var transaction = context.Database.BeginTransaction()) 66 | { 67 | int methodCalls = 0; 68 | 69 | context.ExecuteInTransaction(() => 70 | { 71 | methodCalls++; 72 | 73 | Assert.AreEqual(transaction, context.Database.CurrentTransaction); 74 | 75 | return 0; 76 | }); 77 | 78 | Assert.AreEqual(transaction, context.Database.CurrentTransaction); 79 | Assert.AreEqual(1, methodCalls); 80 | } 81 | } 82 | 83 | [TestMethod] 84 | public async Task ShouldPreserveExistingTransactionAsync() 85 | { 86 | using (var context = CreateSqliteDbContext()) 87 | using (var transaction = context.Database.BeginTransaction()) 88 | { 89 | int methodCalls = 0; 90 | 91 | await context.ExecuteInTransaction(async () => 92 | { 93 | methodCalls++; 94 | 95 | Assert.AreEqual(transaction, context.Database.CurrentTransaction); 96 | 97 | await Task.Delay(1); 98 | 99 | return 0; 100 | }); 101 | 102 | Assert.AreEqual(transaction, context.Database.CurrentTransaction); 103 | Assert.AreEqual(1, methodCalls); 104 | } 105 | } 106 | } 107 | } -------------------------------------------------------------------------------- /EFCore.CommonTools/Auditing/AuditableEntities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | #if EF_CORE 4 | namespace EntityFrameworkCore.CommonTools 5 | #elif EF_6 6 | namespace EntityFramework.CommonTools 7 | #endif 8 | { 9 | /// 10 | /// This interface is implemented by entities that is wanted 11 | /// to store creation information (who and when created). 12 | /// Creation time and creator user are automatically set when saving Entity to database. 13 | /// 14 | public interface ICreationAuditable : ICreationTrackable 15 | where TUserId : struct 16 | { 17 | TUserId CreatorUserId { get; set; } 18 | } 19 | 20 | /// 21 | /// This interface is implemented by entities that is wanted 22 | /// to store creation information (who and when created). 23 | /// Creation time and creator user are automatically set when saving Entity to database. 24 | /// 25 | public interface ICreationAuditable : ICreationTrackable 26 | { 27 | string CreatorUserId { get; set; } 28 | } 29 | 30 | [Obsolete("Use ICreationAuditable instead")] 31 | public interface ICreationAuditableV1 : ICreationTrackable 32 | { 33 | string CreatorUser { get; set; } 34 | } 35 | 36 | /// 37 | /// This interface is implemented by entities that is wanted 38 | /// to store modification information (who and when modified lastly). 39 | /// Properties are automatically set when updating the Entity. 40 | /// 41 | public interface IModificationAuditable : IModificationTrackable 42 | where TUserId : struct 43 | { 44 | TUserId? UpdaterUserId { get; set; } 45 | } 46 | 47 | /// 48 | /// This interface is implemented by entities that is wanted 49 | /// to store modification information (who and when modified lastly). 50 | /// Properties are automatically set when updating the Entity. 51 | /// 52 | public interface IModificationAuditable : IModificationTrackable 53 | { 54 | string UpdaterUserId { get; set; } 55 | } 56 | 57 | [Obsolete("Use IModificationAuditable instead")] 58 | public interface IModificationAuditableV1 : IModificationTrackable 59 | { 60 | string UpdaterUser { get; set; } 61 | } 62 | 63 | /// 64 | /// This interface is implemented by entities which wanted 65 | /// to store deletion information (who and when deleted). 66 | /// 67 | public interface IDeletionAuditable : IDeletionTrackable 68 | where TUserId : struct 69 | { 70 | TUserId? DeleterUserId { get; set; } 71 | } 72 | 73 | /// 74 | /// This interface is implemented by entities which wanted 75 | /// to store deletion information (who and when deleted). 76 | /// 77 | public interface IDeletionAuditable : IDeletionTrackable 78 | { 79 | string DeleterUserId { get; set; } 80 | } 81 | 82 | [Obsolete("Use IDeletionAuditable instead")] 83 | public interface IDeletionAuditableV1 : IDeletionTrackable 84 | { 85 | string DeleterUser { get; set; } 86 | } 87 | 88 | /// 89 | /// This interface is implemented by entities which must be audited. 90 | /// Related properties automatically set when saving/updating/deleting Entity objects. 91 | /// 92 | public interface IFullAuditable : IFullTrackable, 93 | ICreationAuditable, IModificationAuditable, IDeletionAuditable 94 | where TUserId : struct 95 | { 96 | } 97 | 98 | /// 99 | /// This interface is implemented by entities which must be audited. 100 | /// Related properties automatically set when saving/updating/deleting Entity objects. 101 | /// 102 | public interface IFullAuditable : IFullTrackable, 103 | ICreationAuditable, IModificationAuditable, IDeletionAuditable 104 | { 105 | } 106 | 107 | [Obsolete("Use IFullAuditable instead")] 108 | public interface IFullAuditableV1 : IFullTrackable, 109 | ICreationAuditableV1, IModificationAuditableV1, IDeletionAuditableV1 110 | { 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Auditing/AuditableEntitiesExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | #if EF_CORE 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.ChangeTracking; 7 | 8 | namespace EntityFrameworkCore.CommonTools 9 | #elif EF_6 10 | using System.Data.Entity; 11 | using EntityEntry = System.Data.Entity.Infrastructure.DbEntityEntry; 12 | 13 | namespace EntityFramework.CommonTools 14 | #endif 15 | { 16 | public static partial class DbContextExtensions 17 | { 18 | /// 19 | /// Populate special properties for all Auditable Entities in context. 20 | /// 21 | public static void UpdateAuditableEntities(this DbContext context, TUserId editorUserId) 22 | where TUserId : struct 23 | { 24 | DateTime utcNow = DateTime.UtcNow; 25 | 26 | var changedEntries = context.ChangeTracker.Entries() 27 | .Where(e => e.State == EntityState.Added 28 | || e.State == EntityState.Modified 29 | || e.State == EntityState.Deleted); 30 | 31 | foreach (var dbEntry in changedEntries) 32 | { 33 | UpdateAuditableEntity(dbEntry, utcNow, editorUserId); 34 | } 35 | } 36 | 37 | /// 38 | /// Populate special properties for all Auditable Entities in context. 39 | /// 40 | public static void UpdateAuditableEntities(this DbContext context, string editorUserId) 41 | { 42 | DateTime utcNow = DateTime.UtcNow; 43 | 44 | var changedEntries = context.ChangeTracker.Entries() 45 | .Where(e => e.State == EntityState.Added 46 | || e.State == EntityState.Modified 47 | || e.State == EntityState.Deleted); 48 | 49 | foreach (var dbEntry in changedEntries) 50 | { 51 | UpdateAuditableEntity(dbEntry, utcNow, editorUserId); 52 | } 53 | } 54 | 55 | private static void UpdateAuditableEntity( 56 | EntityEntry dbEntry, DateTime utcNow, TUserId editorUserId) 57 | where TUserId : struct 58 | { 59 | object entity = dbEntry.Entity; 60 | 61 | switch (dbEntry.State) 62 | { 63 | case EntityState.Added: 64 | if (entity is ICreationAuditable creationAuditable) 65 | { 66 | UpdateTrackableEntity(dbEntry, utcNow); 67 | creationAuditable.CreatorUserId = editorUserId; 68 | } 69 | break; 70 | 71 | case EntityState.Modified: 72 | if (entity is IModificationAuditable modificationAuditable) 73 | { 74 | UpdateTrackableEntity(dbEntry, utcNow); 75 | modificationAuditable.UpdaterUserId = editorUserId; 76 | dbEntry.CurrentValues[nameof(IModificationAuditable.UpdaterUserId)] = editorUserId; 77 | 78 | if (entity is ICreationAuditable) 79 | { 80 | PreventPropertyOverwrite( 81 | dbEntry, nameof(ICreationAuditable.CreatorUserId)); 82 | } 83 | } 84 | break; 85 | 86 | case EntityState.Deleted: 87 | if (entity is IDeletionAuditable deletionAuditable) 88 | { 89 | UpdateTrackableEntity(dbEntry, utcNow); 90 | // change CurrentValues after dbEntry.State becomes EntityState.Unchanged 91 | deletionAuditable.DeleterUserId = editorUserId; 92 | dbEntry.CurrentValues[nameof(IDeletionAuditable.DeleterUserId)] = editorUserId; 93 | } 94 | break; 95 | 96 | default: 97 | throw new NotSupportedException(); 98 | } 99 | } 100 | 101 | private static void UpdateAuditableEntity( 102 | EntityEntry dbEntry, DateTime utcNow, string editorUserId) 103 | { 104 | object entity = dbEntry.Entity; 105 | 106 | switch (dbEntry.State) 107 | { 108 | case EntityState.Added: 109 | if (entity is ICreationAuditable creationAuditable) 110 | { 111 | UpdateTrackableEntity(dbEntry, utcNow); 112 | creationAuditable.CreatorUserId = editorUserId; 113 | } 114 | else if (entity is ICreationAuditableV1 creationAuditableV1) 115 | { 116 | UpdateTrackableEntity(dbEntry, utcNow); 117 | creationAuditableV1.CreatorUser = editorUserId; 118 | } 119 | break; 120 | 121 | case EntityState.Modified: 122 | if (entity is IModificationAuditable modificationAuditable) 123 | { 124 | UpdateTrackableEntity(dbEntry, utcNow); 125 | modificationAuditable.UpdaterUserId = editorUserId; 126 | dbEntry.CurrentValues[nameof(IModificationAuditable.UpdaterUserId)] = editorUserId; 127 | 128 | if (entity is ICreationAuditable) 129 | { 130 | PreventPropertyOverwrite(dbEntry, nameof(ICreationAuditable.CreatorUserId)); 131 | } 132 | } 133 | else if (entity is IModificationAuditableV1 modificationAuditableV1) 134 | { 135 | UpdateTrackableEntity(dbEntry, utcNow); 136 | modificationAuditableV1.UpdaterUser = editorUserId; 137 | dbEntry.CurrentValues[nameof(IModificationAuditableV1.UpdaterUser)] = editorUserId; 138 | 139 | if (entity is ICreationAuditableV1) 140 | { 141 | PreventPropertyOverwrite(dbEntry, nameof(ICreationAuditableV1.CreatorUser)); 142 | } 143 | } 144 | break; 145 | 146 | case EntityState.Deleted: 147 | if (entity is IDeletionAuditable deletionAuditable) 148 | { 149 | UpdateTrackableEntity(dbEntry, utcNow); 150 | // change CurrentValues after dbEntry.State becomes EntityState.Unchanged 151 | deletionAuditable.DeleterUserId = editorUserId; 152 | dbEntry.CurrentValues[nameof(IDeletionAuditable.DeleterUserId)] = editorUserId; 153 | } 154 | else if (entity is IDeletionAuditableV1 deletionAuditableV1) 155 | { 156 | UpdateTrackableEntity(dbEntry, utcNow); 157 | deletionAuditableV1.DeleterUser = editorUserId; 158 | dbEntry.CurrentValues[nameof(IDeletionAuditableV1.DeleterUser)] = editorUserId; 159 | } 160 | break; 161 | 162 | default: 163 | throw new NotSupportedException(); 164 | } 165 | } 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Auditing/README.md: -------------------------------------------------------------------------------- 1 | ## Auditable Entities 2 | Automatically update info about who and when create / modify / delete the entity during `context.SaveCahnges()` 3 | 4 | ```cs 5 | class User 6 | { 7 | public int Id { get;set; } 8 | public string Login { get; set; } 9 | } 10 | 11 | class Post : IFullAuditable 12 | { 13 | public int Id { get; set; } 14 | public string Content { get; set; } 15 | 16 | // IFullAuditable members 17 | public bool IsDeleted { get; set; } 18 | public int CreatorUserId { get; set; } 19 | public DateTime CreatedUtc { get; set; } 20 | public int? UpdaterUserId { get; set; } 21 | public DateTime? UpdatedUtc { get; set; } 22 | public int? DeleterUserId { get; set; } 23 | public DateTime? DeletedUtc { get; set; } 24 | } 25 | 26 | class MyContext : DbContext 27 | { 28 | public DbSet Users { get; set; } 29 | public DbSet Posts { get; set; } 30 | 31 | public void SaveChanges(int editorUserId) 32 | { 33 | this.UpdateAuditableEntities(editorUserId); 34 | base.SaveChanges(); 35 | } 36 | } 37 | ``` 38 | 39 |
40 | 41 | Also you can track only the creation, deletion and so on by implementing the following interfaces: 42 | 43 | #### `ISoftDeletable` 44 | Used to standardize soft deleting entities. Soft-delete entities are not actually deleted, 45 | marked as `IsDeleted == true` in the database, but can not be retrieved to the application. 46 | 47 | ```cs 48 | interface ISoftDeletable 49 | { 50 | bool IsDeleted { get; set; } 51 | } 52 | ``` 53 | 54 | #### `ICreationTrackable` 55 | An entity can implement this interface if `CreatedUtc` of this entity must be stored. 56 | `CreatedUtc` is automatically set when saving Entity to database. 57 | 58 | ```cs 59 | interface ICreationTrackable 60 | { 61 | DateTime CreatedUtc { get; set; } 62 | } 63 | ``` 64 | 65 | #### `ICreationAuditable` 66 | This interface is implemented by entities that is wanted to store creation information (who and when created). 67 | Creation time and creator user are automatically set when saving Entity to database. 68 | 69 | ```cs 70 | interface ICreationAuditable : ICreationTrackable 71 | where TUserId : struct 72 | { 73 | TUserId CreatorUserId { get; set; } 74 | } 75 | // or 76 | interface ICreationAuditable : ICreationTrackable 77 | { 78 | string CreatorUserId { get; set; } 79 | } 80 | ``` 81 | 82 | #### `IModificationTrackable` 83 | An entity can implement this interface if `UpdatedUtc` of this entity must be stored. 84 | `UpdatedUtc` automatically set when updating the Entity. 85 | 86 | ```cs 87 | interface IModificationTrackable 88 | { 89 | DateTime? UpdatedUtc { get; set; } 90 | } 91 | ``` 92 | 93 | #### `IModificationAuditable` 94 | This interface is implemented by entities that is wanted 95 | to store modification information (who and when modified lastly). 96 | Properties are automatically set when updating the Entity. 97 | 98 | ```cs 99 | interface IModificationAuditable : IModificationTrackable 100 | where TUserId : struct 101 | { 102 | TUserId? UpdaterUserId { get; set; } 103 | } 104 | // or 105 | interface IModificationAuditable : IModificationTrackable 106 | { 107 | string UpdaterUserId { get; set; } 108 | } 109 | ``` 110 | 111 | #### `IDeletionTrackable` 112 | An entity can implement this interface if `DeletedUtc` of this entity must be stored. 113 | `DeletedUtc` is automatically set when deleting Entity. 114 | 115 | ```cs 116 | interface IDeletionTrackable : ISoftDeletable 117 | { 118 | DateTime? DeletedUtc { get; set; } 119 | } 120 | ``` 121 | 122 | #### `IDeletionAuditable` 123 | This interface is implemented by entities which wanted to store deletion information (who and when deleted). 124 | 125 | ```cs 126 | public interface IDeletionAuditable : IDeletionTrackable 127 | where TUserId : struct 128 | { 129 | TUserId? DeleterUserId { get; set; } 130 | } 131 | // or 132 | public interface IDeletionAuditable : IDeletionTrackable 133 | { 134 | string DeleterUserId { get; set; } 135 | } 136 | ``` 137 | 138 | #### `IFullTrackable` 139 | This interface is implemented by entities which modification times must be tracked. 140 | Related properties automatically set when saving/updating/deleting Entity objects. 141 | 142 | ```cs 143 | interface IFullTrackable : ICreationTrackable, IModificationTrackable, IDeletionTrackable { } 144 | ``` 145 | 146 | #### `IFullAuditable` 147 | This interface is implemented by entities which must be audited. 148 | Related properties automatically set when saving/updating/deleting Entity objects. 149 | 150 | ```cs 151 | interface IFullAuditable : IFullTrackable, 152 | ICreationAuditable, IModificationAuditable, IDeletionAuditable 153 | where TUserId : struct { } 154 | // or 155 | interface IFullAuditable : IFullTrackable, ICreationAuditable, IModificationAuditable, IDeletionAuditable { } 156 | ``` 157 | 158 |
159 | 160 | You can choose between saving the user `Id` or the user `Login`. 161 | So there are two overloadings for `DbContext.UpdateAudiatbleEntities()`: 162 | ```cs 163 | static void UpdateAuditableEntities(this DbContext context, TUserId editorUserId); 164 | static void UpdateAuditableEntities(this DbContext context, string editorUserId); 165 | ``` 166 | and also the separate extension to update only `Trackable` entities: 167 | ```cs 168 | static void UpdateTrackableEntities(this DbContext context); 169 | ``` 170 | 171 |
172 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Auditing/TrackableEntities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | #if EF_CORE 4 | namespace EntityFrameworkCore.CommonTools 5 | #elif EF_6 6 | namespace EntityFramework.CommonTools 7 | #endif 8 | { 9 | /// 10 | /// Used to standardize soft deleting entities. Soft-delete entities are not actually deleted, 11 | /// marked as IsDeleted = true in the database, but can not be retrieved to the application. 12 | /// 13 | public interface ISoftDeletable 14 | { 15 | bool IsDeleted { get; set; } 16 | } 17 | 18 | /// 19 | /// An entity can implement this interface if of this entity must be stored. 20 | /// is automatically set when saving Entity to database. 21 | /// 22 | public interface ICreationTrackable 23 | { 24 | DateTime CreatedUtc { get; set; } 25 | } 26 | 27 | /// 28 | /// An entity can implement this interface if of this entity must be stored. 29 | /// is automatically set when updating Entity. 30 | /// 31 | public interface IModificationTrackable 32 | { 33 | DateTime? UpdatedUtc { get; set; } 34 | } 35 | 36 | /// 37 | /// An entity can implement this interface if of this entity must be stored. 38 | /// is automatically set when deleting Entity. 39 | /// 40 | public interface IDeletionTrackable : ISoftDeletable 41 | { 42 | DateTime? DeletedUtc { get; set; } 43 | } 44 | 45 | /// 46 | /// This interface is implemented by entities which modification times must be tracked. 47 | /// Related properties automatically set when saving/updating/deleting Entity objects. 48 | /// 49 | public interface IFullTrackable : ICreationTrackable, IModificationTrackable, IDeletionTrackable 50 | { 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Auditing/TrackableEntitiesExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | #if EF_CORE 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.ChangeTracking; 7 | 8 | namespace EntityFrameworkCore.CommonTools 9 | #elif EF_6 10 | using System.Data.Entity; 11 | using EntityEntry = System.Data.Entity.Infrastructure.DbEntityEntry; 12 | 13 | namespace EntityFramework.CommonTools 14 | #endif 15 | { 16 | public static partial class DbContextExtensions 17 | { 18 | /// 19 | /// Populate special properties for all Trackable Entities in context. 20 | /// 21 | public static void UpdateTrackableEntities(this DbContext context) 22 | { 23 | DateTime utcNow = DateTime.UtcNow; 24 | 25 | var changedEntries = context.ChangeTracker.Entries() 26 | .Where(e => e.State == EntityState.Added 27 | || e.State == EntityState.Modified 28 | || e.State == EntityState.Deleted); 29 | 30 | foreach (var dbEntry in changedEntries) 31 | { 32 | UpdateTrackableEntity(dbEntry, utcNow); 33 | } 34 | } 35 | 36 | private static void UpdateTrackableEntity(EntityEntry dbEntry, DateTime utcNow) 37 | { 38 | object entity = dbEntry.Entity; 39 | 40 | switch (dbEntry.State) 41 | { 42 | case EntityState.Added: 43 | if (entity is ICreationTrackable creationTrackable) 44 | { 45 | creationTrackable.CreatedUtc = utcNow; 46 | } 47 | break; 48 | 49 | case EntityState.Modified: 50 | if (entity is IModificationTrackable modificatonTrackable) 51 | { 52 | modificatonTrackable.UpdatedUtc = utcNow; 53 | dbEntry.CurrentValues[nameof(IModificationTrackable.UpdatedUtc)] = utcNow; 54 | 55 | if (entity is ICreationTrackable) 56 | { 57 | PreventPropertyOverwrite(dbEntry, nameof(ICreationTrackable.CreatedUtc)); 58 | } 59 | } 60 | break; 61 | 62 | case EntityState.Deleted: 63 | if (entity is ISoftDeletable softDeletable) 64 | { 65 | dbEntry.State = EntityState.Unchanged; 66 | softDeletable.IsDeleted = true; 67 | dbEntry.CurrentValues[nameof(ISoftDeletable.IsDeleted)] = true; 68 | 69 | if (entity is IDeletionTrackable deletionTrackable) 70 | { 71 | deletionTrackable.DeletedUtc = utcNow; 72 | dbEntry.CurrentValues[nameof(IDeletionTrackable.DeletedUtc)] = utcNow; 73 | } 74 | } 75 | break; 76 | 77 | default: 78 | throw new NotSupportedException(); 79 | } 80 | } 81 | 82 | /// 83 | /// If we set to on entity with 84 | /// empty or 85 | /// we should not overwrite database values. 86 | /// https://github.com/gnaeus/EntityFramework.CommonTools/issues/4 87 | /// 88 | private static void PreventPropertyOverwrite(EntityEntry dbEntry, string propertyName) 89 | { 90 | var propertyEntry = dbEntry.Property(propertyName); 91 | 92 | if (propertyEntry.IsModified && Equals(dbEntry.CurrentValues[propertyName], default(TProperty))) 93 | { 94 | propertyEntry.IsModified = false; 95 | } 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Concurrency/ConcurrentEntities.cs: -------------------------------------------------------------------------------- 1 | #if EF_CORE 2 | namespace EntityFrameworkCore.CommonTools 3 | #elif EF_6 4 | namespace EntityFramework.CommonTools 5 | #endif 6 | { 7 | /// 8 | /// An entity can implement this interface if it should use Optimistic Concurrency Check 9 | /// with populating from client-side. Allowed types: 10 | /// 11 | /// is : 12 | /// RowVersion property should be decorated by [Timestamp] attribute. 13 | /// RowVersion column should have ROWVERSION type in SQL Server. 14 | /// 15 | /// 16 | /// is : 17 | /// RowVersion property should be decorated by [ConcurrencyCheck] attribute. 18 | /// It's value is generated by during each save. 19 | /// 20 | /// is : 21 | /// RowVersion property should be decorated by [ConcurrencyCheck] 22 | /// and [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attributes. 23 | /// RowVersion column should be updated by trigger in DB: 24 | /// 25 | /// CREATE TRIGGER TRG_MyTable_UPD 26 | /// AFTER UPDATE ON MyTable 27 | /// WHEN old.RowVersion = new.RowVersion 28 | /// BEGIN 29 | /// UPDATE MyTable 30 | /// SET RowVersion = RowVersion + 1; 31 | /// END; 32 | /// 33 | /// 34 | public interface IConcurrencyCheckable 35 | { 36 | TRowVersion RowVersion { get; set; } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Concurrency/ConcurrentEntitiesExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | 5 | #if EF_CORE 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.EntityFrameworkCore.ChangeTracking; 8 | 9 | namespace EntityFrameworkCore.CommonTools 10 | #elif EF_6 11 | using System.Data.Entity; 12 | using System.Data.Entity.Infrastructure; 13 | using EntityEntry = System.Data.Entity.Infrastructure.DbEntityEntry; 14 | 15 | namespace EntityFramework.CommonTools 16 | #endif 17 | { 18 | public static partial class DbContextExtensions 19 | { 20 | private const string ROW_VERSION = nameof(IConcurrencyCheckable.RowVersion); 21 | 22 | /// 23 | /// Populate RowVersion propertiy of 24 | /// Entities in context from client-side values. 25 | /// 26 | /// 27 | /// EF automatically detects if byde[] RowVersion is changed by reference (not only by value) 28 | /// and gentrates code like 'DECLARE @p int; UPDATE [Table] SET @p = 0 WHERE RowWersion = ...' 29 | /// 30 | public static void UpdateConcurrentEntities(this DbContext dbContext) 31 | { 32 | DateTime utcNow = DateTime.UtcNow; 33 | 34 | var changedEntries = dbContext.ChangeTracker.Entries() 35 | .Where(e => e.State == EntityState.Modified 36 | || e.State == EntityState.Deleted); 37 | 38 | foreach (var dbEntry in changedEntries) 39 | { 40 | object entity = dbEntry.Entity; 41 | 42 | if (entity is IConcurrencyCheckable concurrencyCheckableTimestamp) 43 | { 44 | // take row version from entity that modified by client 45 | dbEntry.OriginalValues[ROW_VERSION] = concurrencyCheckableTimestamp.RowVersion; 46 | } 47 | else if (entity is IConcurrencyCheckable concurrencyCheckableLong) 48 | { 49 | // take row version from entity that modified by client 50 | dbEntry.OriginalValues[ROW_VERSION] = concurrencyCheckableLong.RowVersion; 51 | } 52 | else if (entity is IConcurrencyCheckable concurrencyCheckableGuid) 53 | { 54 | // take row version from entity that modified by client 55 | dbEntry.OriginalValues[ROW_VERSION] = concurrencyCheckableGuid.RowVersion; 56 | // generate new row version 57 | concurrencyCheckableGuid.RowVersion = Guid.NewGuid(); 58 | } 59 | } 60 | #if !EF_CORE 61 | if (!dbContext.Configuration.AutoDetectChangesEnabled) 62 | { 63 | dbContext.ChangeTracker.DetectChanges(); 64 | } 65 | #endif 66 | } 67 | 68 | /// 69 | /// Save changes regardless of . 70 | /// http://msdn.microsoft.com/en-us/data/jj592904.aspx 71 | /// 72 | /// 73 | public static void SaveChangesIgnoreConcurrency( 74 | this DbContext dbContext, int retryCount = 3) 75 | { 76 | int errorCount = 0; 77 | for (;;) 78 | { 79 | try 80 | { 81 | dbContext.SaveChanges(); 82 | break; 83 | } 84 | catch (DbUpdateConcurrencyException ex) 85 | { 86 | if (++errorCount > retryCount) 87 | { 88 | throw; 89 | } 90 | // update original values from the database 91 | EntityEntry dbEntry = ex.Entries.Single(); 92 | dbEntry.OriginalValues.SetValues(dbEntry.GetDatabaseValues()); 93 | 94 | UpdateRowVersionFromDb(dbEntry); 95 | } 96 | }; 97 | } 98 | 99 | /// 100 | /// Save changes regardless of . 101 | /// http://msdn.microsoft.com/en-us/data/jj592904.aspx 102 | /// 103 | /// 104 | public static async Task SaveChangesIgnoreConcurrencyAsync( 105 | this DbContext dbContext, int retryCount = 3) 106 | { 107 | int errorCount = 0; 108 | for (;;) 109 | { 110 | try 111 | { 112 | await dbContext.SaveChangesAsync(); 113 | break; 114 | } 115 | catch (DbUpdateConcurrencyException ex) 116 | { 117 | if (++errorCount > retryCount) 118 | { 119 | throw; 120 | } 121 | // update original values from the database 122 | EntityEntry dbEntry = ex.Entries.Single(); 123 | dbEntry.OriginalValues.SetValues(await dbEntry.GetDatabaseValuesAsync()); 124 | 125 | UpdateRowVersionFromDb(dbEntry); 126 | } 127 | }; 128 | } 129 | 130 | private static void UpdateRowVersionFromDb(EntityEntry dbEntry) 131 | { 132 | object entity = dbEntry.Entity; 133 | 134 | if (entity is IConcurrencyCheckable concurrencyCheckableTimestamp) 135 | { 136 | concurrencyCheckableTimestamp.RowVersion = (byte[])dbEntry.OriginalValues[ROW_VERSION]; 137 | } 138 | else if (entity is IConcurrencyCheckable concurrencyCheckableLong) 139 | { 140 | concurrencyCheckableLong.RowVersion = (long)dbEntry.OriginalValues[ROW_VERSION]; 141 | } 142 | else if (entity is IConcurrencyCheckable concurrencyCheckableGuid) 143 | { 144 | concurrencyCheckableGuid.RowVersion = (Guid)dbEntry.OriginalValues[ROW_VERSION]; 145 | } 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Concurrency/README.md: -------------------------------------------------------------------------------- 1 | ## Concurrency Checks 2 | By default EF and EFCore uses `EntityEntry.OriginalValues["RowVersion"]` for concurrency checks 3 | ([see docs](https://docs.microsoft.com/en-us/ef/core/saving/concurrency)). 4 | 5 | With this behaviour the concurrency conflict may occur only between the `SELECT` statement 6 | that loads entities to the `DbContext` and the `UPDATE` statement from `DbContext.SaveChanges()`. 7 | 8 | But sometimes we want check concurrency conflicts between two or more edit operations that comes from client-side. For example: 9 | 10 | * user_1 loads the editor form 11 | * user_2 loads the same editor form 12 | * user_1 saves his changes 13 | * user_2 saves his changes __and gets concurrency conflict__. 14 | 15 | To provide this behaviour, an entity should implement the following interface: 16 | ```cs 17 | interface IConcurrencyCheckable 18 | { 19 | TRowVersion RowVersion { get; set; } 20 | } 21 | ``` 22 | And the `DbContext` should overload `SaveChanges()` method with `UpdateConcurrentEntities()` extension: 23 | ```cs 24 | class MyDbContext : DbContext 25 | { 26 | public override int SaveChanges() 27 | { 28 | this.UpdateConcurrentEntities(); 29 | return base.SaveChanges(); 30 | } 31 | } 32 | ``` 33 | 34 |
35 | 36 | There are also three different behaviours for `IConcurrencyCheckable`: 37 | 38 | #### `IConcurrencyCheckable` 39 | `RowVersion` property should be decorated by `[Timestamp]` attribute. 40 | `RowVersion` column should have `ROWVERSION` type in SQL Server. 41 | The default behaviour. Supported only by Microsoft SQL Server. 42 | 43 | ```cs 44 | class MyEntity : IConcurrencyCheckable 45 | { 46 | [Timestamp] 47 | public byte[] RowVersion { get; set; } 48 | } 49 | ``` 50 | 51 | #### `IConcurrencyCheckable` 52 | `RowVersion` property should be decorated by `[ConcurrencyCheck]` attribute. 53 | It's value is populated by `Guid.NewGuid()` during each `DbContext.SaveChanges()` call at client-side. 54 | No specific database support is needed. 55 | 56 | ```cs 57 | class MyEntity : IConcurrencyCheckable 58 | { 59 | [ConcurrencyCheck] 60 | public Guid RowVersion { get; set; } 61 | } 62 | ``` 63 | 64 | #### `IConcurrencyCheckable` 65 | `RowVersion` property should be decorated by `[ConcurrencyCheck]` and `[DatabaseGenerated(DatabaseGeneratedOption.Computed)]` attributes. 66 | 67 | ```cs 68 | class MyEntity : IConcurrencyCheckable 69 | { 70 | [ConcurrencyCheck] 71 | [DatabaseGenerated(DatabaseGeneratedOption.Computed)] 72 | public long RowVersion { get; set; } 73 | } 74 | ``` 75 | 76 | `RowVersion` column should be updated by trigger in DB. Example for SQLite: 77 | ```sql 78 | CREATE TABLE MyEntities ( RowVersion INTEGER DEFAULT 0 ); 79 | 80 | CREATE TRIGGER TRG_MyEntities_UPD 81 | AFTER UPDATE ON MyEntities 82 | WHEN old.RowVersion = new.RowVersion 83 | BEGIN 84 | UPDATE MyEntities 85 | SET RowVersion = RowVersion + 1; 86 | END; 87 | ``` 88 | 89 |
90 | 91 | But sometimes we want to ignore `DbUpdateConcurrencyException`. 92 | And there are two extension methods for this. 93 | 94 | __`static void SaveChangesIgnoreConcurrency(this DbContext dbContext, int retryCount = 3)`__ 95 | Save changes regardless of `DbUpdateConcurrencyException`. 96 | 97 | __`static async Task SaveChangesIgnoreConcurrencyAsync(this DbContext dbContext, int retryCount = 3)`__ 98 | Save changes regardless of `DbUpdateConcurrencyException`. 99 | 100 |
101 | -------------------------------------------------------------------------------- /EFCore.CommonTools/EntityFrameworkCore.CommonTools.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | EntityFrameworkCore.CommonTools 6 | 2.0.2 7 | An extension for EntityFrameworkCore that provides Auditing, Concurrency Checks, JSON Complex Types and writing history to Transaction Log. 8 | Dmitry Panyushkin 9 | 10 | https://github.com/gnaeus/EntityFramework.CommonTools/blob/master/LICENSE 11 | https://github.com/gnaeus/EntityFramework.CommonTools 12 | https://raw.githubusercontent.com/gnaeus/EntityFramework.CommonTools/master/icon.png 13 | https://github.com/gnaeus/EntityFramework.CommonTools.git 14 | git 15 | false 16 | context.Update(entity) does not reset CreatedUtc and CreatorUserId 17 | Copyright © Dmitry Panyushkin 2017 18 | EF EFCore EntityFrameworkCore EntityFramework Entity Framework ChangeTracking Change Tracking Auditing Audit TransactionLog Transaction Log ComplexType Complex Type JSON 19 | True 20 | 21 | 22 | 23 | TRACE;DEBUG;EF_CORE 24 | bin\Debug\ 25 | $(NoWarn);1591 26 | bin\Debug\netstandard2.0\EntityFrameworkCore.CommonTools.xml 27 | 28 | 29 | 30 | TRACE;EF_CORE 31 | bin\Release\ 32 | $(NoWarn);1591 33 | bin\Release\netstandard2.0\EntityFrameworkCore.CommonTools.xml 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Expression/ExpressionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using System.Reflection; 4 | 5 | #if EF_CORE 6 | namespace EntityFrameworkCore.CommonTools 7 | #elif EF_6 8 | namespace EntityFramework.CommonTools 9 | #else 10 | namespace System.Linq.CommonTools 11 | #endif 12 | { 13 | public static class ExpressionExtensions 14 | { 15 | /// 16 | /// Get computed value of Expression. 17 | /// 18 | /// 19 | public static object GetValue(this Expression expression) 20 | { 21 | if (expression == null) throw new ArgumentNullException(nameof(expression)); 22 | 23 | switch (expression.NodeType) 24 | { 25 | case ExpressionType.Constant: 26 | return ((ConstantExpression)expression).Value; 27 | 28 | case ExpressionType.MemberAccess: 29 | var memberExpr = (MemberExpression)expression; 30 | { 31 | object instance = memberExpr.Expression.GetValue(); 32 | switch (memberExpr.Member) 33 | { 34 | case FieldInfo field: 35 | return field.GetValue(instance); 36 | 37 | case PropertyInfo property: 38 | return property.GetValue(instance); 39 | } 40 | } 41 | break; 42 | 43 | case ExpressionType.Convert: 44 | var convertExpr = (UnaryExpression)expression; 45 | { 46 | if (convertExpr.Method == null) 47 | { 48 | Type type = Nullable.GetUnderlyingType(convertExpr.Type) ?? convertExpr.Type; 49 | object value = convertExpr.Operand.GetValue(); 50 | return Convert.ChangeType(value, type); 51 | } 52 | } 53 | break; 54 | 55 | case ExpressionType.ArrayIndex: 56 | var indexExpr = (BinaryExpression)expression; 57 | { 58 | var array = (Array)indexExpr.Left.GetValue(); 59 | var index = (int)indexExpr.Right.GetValue(); 60 | return array.GetValue(index); 61 | } 62 | 63 | case ExpressionType.ArrayLength: 64 | var lengthExpr = (UnaryExpression)expression; 65 | { 66 | var array = (Array)lengthExpr.Operand.GetValue(); 67 | return array.Length; 68 | } 69 | 70 | case ExpressionType.Call: 71 | var callExpr = (MethodCallExpression)expression; 72 | { 73 | if (callExpr.Method.Name == "get_Item") 74 | { 75 | object instance = callExpr.Object.GetValue(); 76 | object[] arguments = new object[callExpr.Arguments.Count]; 77 | for (int i = 0; i < arguments.Length; i++) 78 | { 79 | arguments[i] = callExpr.Arguments[i].GetValue(); 80 | } 81 | return callExpr.Method.Invoke(instance, arguments); 82 | } 83 | } 84 | break; 85 | 86 | case ExpressionType.Quote: 87 | var quoteExpression = (UnaryExpression)expression; 88 | { 89 | return GetValue(quoteExpression.Operand); 90 | } 91 | 92 | case ExpressionType.Lambda: 93 | return expression; 94 | } 95 | 96 | // we can't interpret the expression but we can compile and run it 97 | var objectMember = Expression.Convert(expression, typeof(object)); 98 | var getterLambda = Expression.Lambda>(objectMember); 99 | 100 | return getterLambda.Compile().Invoke(); 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Expression/README.md: -------------------------------------------------------------------------------- 1 | ## ExpressionExtensions 2 | 3 | Get computed value of `Expression` 4 | ```cs 5 | public static object GetValue(this Expression expression); 6 | ``` 7 | 8 |
9 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Json/JsonField.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Jil; 3 | 4 | #if EF_CORE 5 | namespace EntityFrameworkCore.CommonTools 6 | #elif EF_6 7 | namespace EntityFramework.CommonTools 8 | #else 9 | namespace System.Linq.CommonTools 10 | #endif 11 | { 12 | /// 13 | /// Utility structure for storing complex types as JSON strings in DB table. 14 | /// 15 | public struct JsonField 16 | where TObject : class 17 | { 18 | private TObject _object; 19 | private string _json; 20 | private bool _isMaterialized; 21 | private bool _hasDefault; 22 | 23 | public string Json 24 | { 25 | get 26 | { 27 | if (_isMaterialized) 28 | { 29 | _json = _object == null 30 | ? null : JSON.Serialize(_object, Options.IncludeInherited); 31 | } 32 | return _json; 33 | } 34 | set 35 | { 36 | _json = value; 37 | _isMaterialized = false; 38 | } 39 | } 40 | 41 | public TObject Object 42 | { 43 | get 44 | { 45 | if (!_isMaterialized) 46 | { 47 | if (String.IsNullOrEmpty(_json) || _json == "null") 48 | { 49 | if (_hasDefault) 50 | { 51 | _hasDefault = false; 52 | } 53 | else 54 | { 55 | _object = null; 56 | } 57 | } 58 | else 59 | { 60 | _object = JSON.Deserialize(_json); 61 | } 62 | _isMaterialized = true; 63 | } 64 | return _object; 65 | } 66 | set 67 | { 68 | _object = value; 69 | _isMaterialized = true; 70 | } 71 | } 72 | 73 | public static implicit operator JsonField(TObject defaultValue) 74 | { 75 | var field = new JsonField(); 76 | 77 | field._object = defaultValue; 78 | field._hasDefault = true; 79 | 80 | return field; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Json/README.md: -------------------------------------------------------------------------------- 1 | ## JSON Complex Types 2 | There is an utility struct named `JsonField`, that helps to persist any Complex Type as JSON string in single table column. 3 | 4 | ```cs 5 | struct JsonField 6 | where TObject : class 7 | { 8 | public string Json { get; set; } 9 | public TObject Object { get; set; } 10 | } 11 | ``` 12 | 13 | Usage: 14 | ```cs 15 | class User 16 | { 17 | public int Id { get; set; } 18 | public string Name { get; set; } 19 | public string Login { get; set; } 20 | 21 | private JsonField
_address; 22 | // used by EntityFramework 23 | public string AddressJson 24 | { 25 | get { return _address.Json; } 26 | set { _address.Json = value; } 27 | } 28 | // used by application code 29 | public Address Address 30 | { 31 | get { return _address.Object; } 32 | set { _address.Object = value; } 33 | } 34 | 35 | // collection initialization by default 36 | private JsonField> _phones = new HashSet(); 37 | public string PhonesJson 38 | { 39 | get { return _phones.Json; } 40 | set { _phones.Json = value; } 41 | } 42 | public ICollection Phones 43 | { 44 | get { return _phones.Object; } 45 | set { _phones.Object = value; } 46 | } 47 | } 48 | 49 | [NotMapped] 50 | class Address 51 | { 52 | public string City { get; set; } 53 | public string Street { get; set; } 54 | public string Building { get; set; } 55 | } 56 | ``` 57 | 58 | If we update these Complex Type properties, the following SQL is generated during `SaveChanges`: 59 | ```sql 60 | UPDATE Users 61 | SET AddressJson = '{"City":"Moscow","Street":"Arbat","Building":"10"}', 62 | PhonesJson = '["+7 (123) 456-7890","+7 (098) 765-4321"]' 63 | WHERE Id = 1; 64 | ``` 65 | 66 | The `AddressJson` property is serialized from `Address` only when it accessed by EntityFramework. 67 | And the `Address` property is materialized from `AddressJson` only when EntityFramework writes to `AddressJson`. 68 | 69 | If we want to initialize some JSON collection in entity consctuctor, for example: 70 | ```cs 71 | class MyEntity 72 | { 73 | public ICollection MyObjects { get; set; } = new HashSet(); 74 | } 75 | ``` 76 | We can use the following implicit conversion: 77 | ```cs 78 | class MyEntity 79 | { 80 | private JsonField> _myObjects = new HashSet(); 81 | } 82 | ``` 83 | It uses the following implicit operator: 84 | ```cs 85 | struct JsonField 86 | { 87 | public static implicit operator JsonField(TObject defaultValue); 88 | } 89 | ``` 90 | 91 | The only caveat is that `TObject` object should not contain reference loops. 92 | Because `JsonField` uses [Jil](https://github.com/kevin-montrose/Jil) (the fastest .NET JSON serializer) behind the scenes. 93 | 94 |
95 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly: InternalsVisibleTo("EntityFrameworkCore.CommonTools.Tests")] 4 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Querying/AsQueryableExpander.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | using System.Reflection; 7 | using System.Runtime.CompilerServices; 8 | using System.Text; 9 | 10 | #if EF_CORE 11 | namespace EntityFrameworkCore.CommonTools 12 | #elif EF_6 13 | namespace EntityFramework.CommonTools 14 | #else 15 | namespace System.Linq.CommonTools 16 | #endif 17 | { 18 | /// 19 | /// that expands 20 | /// inside Expression. 21 | /// 22 | public class AsQueryableExpander : ExpressionVisitor 23 | { 24 | private readonly ExpressionVisitor _expressionExpander = new AsQueryableExpressionExpander(); 25 | 26 | protected override Expression VisitUnary(UnaryExpression node) 27 | { 28 | if (node.NodeType == ExpressionType.Quote) 29 | { 30 | return _expressionExpander.Visit(node); 31 | } 32 | return base.VisitUnary(node); 33 | } 34 | } 35 | 36 | internal class AsQueryableExpressionExpander : ExpressionVisitor 37 | { 38 | protected override Expression VisitMethodCall(MethodCallExpression node) 39 | { 40 | MethodInfo originalMethod = node.Method; 41 | 42 | if (originalMethod.DeclaringType == typeof(Queryable) 43 | && originalMethod.IsDefined(typeof(ExtensionAttribute), true)) 44 | { 45 | if (originalMethod.Name == nameof(Queryable.AsQueryable)) 46 | { 47 | return Visit(node.Arguments[0]); 48 | } 49 | 50 | ParameterInfo[] originalParams = originalMethod.GetParameters(); 51 | 52 | Type[] genericArguments = null; 53 | 54 | if (originalMethod.IsGenericMethod) 55 | { 56 | genericArguments = originalMethod.GetGenericArguments(); 57 | originalMethod = originalMethod.GetGenericMethodDefinition(); 58 | } 59 | 60 | MethodInfo replacementMethod; 61 | 62 | if (MethodReplacements.TryGetValue(originalMethod, out replacementMethod)) 63 | { 64 | if (genericArguments != null) 65 | { 66 | replacementMethod = replacementMethod.MakeGenericMethod(genericArguments); 67 | } 68 | 69 | Expression[] expandedArguments = new Expression[node.Arguments.Count]; 70 | 71 | for (int i = 0; i < node.Arguments.Count; i++) 72 | { 73 | Expression argument = node.Arguments[i]; 74 | 75 | if (argument.NodeType == ExpressionType.Quote) 76 | { 77 | expandedArguments[i] = ((UnaryExpression)argument).Operand; 78 | } 79 | else 80 | { 81 | expandedArguments[i] = argument; 82 | } 83 | } 84 | 85 | if (typeof(IOrderedQueryable).IsAssignableFrom(expandedArguments[0].Type)) 86 | { 87 | expandedArguments[0] = Visit(expandedArguments[0]); 88 | } 89 | 90 | return Visit(Expression.Call(replacementMethod, expandedArguments)); 91 | } 92 | } 93 | return base.VisitMethodCall(node); 94 | } 95 | 96 | /// 97 | /// Key is method from , Value is method from 98 | /// 99 | static readonly Dictionary MethodReplacements; 100 | 101 | static AsQueryableExpressionExpander() 102 | { 103 | MethodReplacements = new Dictionary(); 104 | 105 | var queryableMethods = typeof(Queryable) 106 | .GetMethods(BindingFlags.Static | BindingFlags.Public) 107 | .Where(method => method.IsDefined(typeof(ExtensionAttribute), true)) 108 | .Select(method => new 109 | { 110 | Name = method.Name, 111 | Method = method, 112 | Signature = GetMethodSignature(method), 113 | }); 114 | 115 | var enumerableLookup = typeof(Enumerable) 116 | .GetMethods(BindingFlags.Static | BindingFlags.Public) 117 | .Where(method => method.IsDefined(typeof(ExtensionAttribute), true)) 118 | .ToLookup(method => method.Name, method => new 119 | { 120 | Method = method, 121 | Signature = GetMethodSignature(method), 122 | }); 123 | 124 | foreach (var queryable in queryableMethods) 125 | { 126 | var enumerableMethods = enumerableLookup[queryable.Name]; 127 | 128 | if (enumerableMethods != null) 129 | { 130 | var enumerable = enumerableMethods 131 | .FirstOrDefault(method => method.Signature == queryable.Signature); 132 | 133 | if (enumerable != null) 134 | { 135 | MethodReplacements[queryable.Method] = enumerable.Method; 136 | } 137 | } 138 | } 139 | } 140 | 141 | private static string GetMethodSignature(MethodInfo method) 142 | { 143 | var sb = new StringBuilder(); 144 | 145 | foreach (ParameterInfo param in method.GetParameters()) 146 | { 147 | AddTypeSignature(sb, param.ParameterType); 148 | } 149 | 150 | return sb.ToString(); 151 | } 152 | 153 | private static void AddTypeSignature(StringBuilder sb, Type type) 154 | { 155 | if (type == typeof(IQueryable)) 156 | { 157 | type = typeof(IEnumerable); 158 | } 159 | 160 | if (type.GetTypeInfo().IsGenericType) 161 | { 162 | Type generic = type.GetGenericTypeDefinition(); 163 | 164 | if (generic == typeof(Expression<>)) 165 | { 166 | type = type.GetGenericArguments().First(); 167 | } 168 | else if (generic == typeof(IQueryable<>)) 169 | { 170 | type = typeof(IEnumerable<>).MakeGenericType(type.GetGenericArguments()); 171 | } 172 | else if (generic == typeof(IOrderedQueryable<>)) 173 | { 174 | type = typeof(IOrderedEnumerable<>).MakeGenericType(type.GetGenericArguments()); 175 | } 176 | } 177 | 178 | sb.Append(type.Name); 179 | 180 | if (type.GetTypeInfo().IsGenericType) 181 | { 182 | sb.Append("[ "); 183 | 184 | foreach (Type argument in type.GetGenericArguments()) 185 | { 186 | AddTypeSignature(sb, argument); 187 | } 188 | 189 | sb.Append("]"); 190 | } 191 | 192 | sb.Append(" "); 193 | } 194 | } 195 | } -------------------------------------------------------------------------------- /EFCore.CommonTools/Querying/DbAsyncEnumerator.cs: -------------------------------------------------------------------------------- 1 | // The MIT License 2 | // Based on https://github.com/scottksmith95/LINQKit 3 | // Original work: Copyright (c) 2007-2009 Joseph Albahari, Tomas Petricek 4 | // Copyright (c) 2013-2017 Scott Smith, Stef Heyenrath, Tuomas Hietanen 5 | // Modified work: Copyright (c) 2017 Dmitry Panyushkin 6 | 7 | #if EF_6 8 | using System; 9 | using System.Collections.Generic; 10 | using System.Linq; 11 | using System.Data.Entity.Infrastructure; 12 | using System.Threading.Tasks; 13 | using System.Threading; 14 | 15 | namespace EntityFramework.CommonTools 16 | { 17 | /// 18 | /// Class for async-await style list enumeration support 19 | /// (e.g. ) 20 | /// 21 | internal class DbAsyncEnumerator : IDisposable, IDbAsyncEnumerator 22 | { 23 | private readonly IEnumerator _inner; 24 | 25 | public DbAsyncEnumerator(IEnumerator inner) 26 | { 27 | _inner = inner; 28 | } 29 | 30 | public void Dispose() 31 | { 32 | _inner.Dispose(); 33 | } 34 | 35 | public Task MoveNextAsync(CancellationToken cancellationToken) 36 | { 37 | return Task.FromResult(_inner.MoveNext()); 38 | } 39 | 40 | public T Current 41 | { 42 | get { return _inner.Current; } 43 | } 44 | 45 | object IDbAsyncEnumerator.Current 46 | { 47 | get { return Current; } 48 | } 49 | } 50 | } 51 | #endif 52 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Querying/ExpandableAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | #if EF_CORE 4 | namespace EntityFrameworkCore.CommonTools 5 | #elif EF_6 6 | namespace EntityFramework.CommonTools 7 | #else 8 | namespace System.Linq.CommonTools 9 | #endif 10 | { 11 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] 12 | public class ExpandableAttribute : Attribute 13 | { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Querying/ExtensionExpander.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | using System.Runtime.CompilerServices; 7 | 8 | #if EF_CORE 9 | namespace EntityFrameworkCore.CommonTools 10 | #elif EF_6 11 | namespace EntityFramework.CommonTools 12 | #else 13 | namespace System.Linq.CommonTools 14 | #endif 15 | { 16 | /// 17 | /// that expands extension methods inside Expression. 18 | /// 19 | public class ExtensionExpander : ExpressionVisitor 20 | { 21 | protected override Expression VisitMethodCall(MethodCallExpression node) 22 | { 23 | MethodInfo method = node.Method; 24 | 25 | if (method.IsDefined(typeof(ExtensionAttribute), true) 26 | && method.IsDefined(typeof(ExpandableAttribute), true)) 27 | { 28 | ParameterInfo[] methodParams = method.GetParameters(); 29 | Type queryableType = methodParams.First().ParameterType; 30 | Type entityType = queryableType.GetGenericArguments().Single(); 31 | 32 | object inputQueryable = MakeEnumerableQuery(entityType); 33 | 34 | object[] arguments = new object[methodParams.Length]; 35 | 36 | arguments[0] = inputQueryable; 37 | 38 | var argumentReplacements = new List>(); 39 | 40 | for (int i = 1; i < methodParams.Length; i++) 41 | { 42 | try 43 | { 44 | arguments[i] = node.Arguments[i].GetValue(); 45 | } 46 | catch (InvalidOperationException) 47 | { 48 | ParameterInfo paramInfo = methodParams[i]; 49 | Type paramType = paramInfo.GetType(); 50 | 51 | arguments[i] = paramType.GetTypeInfo().IsValueType 52 | ? Activator.CreateInstance(paramType) : null; 53 | 54 | argumentReplacements.Add( 55 | new KeyValuePair(paramInfo.Name, node.Arguments[i])); 56 | } 57 | } 58 | 59 | object outputQueryable = method.Invoke(null, arguments); 60 | 61 | Expression expression = ((IQueryable)outputQueryable).Expression; 62 | 63 | Expression realQueryable = node.Arguments[0]; 64 | 65 | if (!typeof(IQueryable).IsAssignableFrom(realQueryable.Type)) 66 | { 67 | MethodInfo asQueryable = _asQueryable.MakeGenericMethod(entityType); 68 | realQueryable = Expression.Call(asQueryable, realQueryable); 69 | } 70 | 71 | expression = new ExtensionRebinder( 72 | inputQueryable, realQueryable, argumentReplacements).Visit(expression); 73 | 74 | return Visit(expression); 75 | } 76 | return base.VisitMethodCall(node); 77 | } 78 | 79 | private static object MakeEnumerableQuery(Type entityType) 80 | { 81 | return _queryableEmpty.MakeGenericMethod(entityType).Invoke(null, null); 82 | } 83 | 84 | private static readonly MethodInfo _asQueryable = typeof(Queryable) 85 | .GetMethods(BindingFlags.Static | BindingFlags.Public) 86 | .First(m => m.Name == nameof(Queryable.AsQueryable) && m.IsGenericMethod); 87 | 88 | private static readonly MethodInfo _queryableEmpty = (typeof(ExtensionExpander)) 89 | .GetMethod(nameof(QueryableEmpty), BindingFlags.Static | BindingFlags.NonPublic); 90 | 91 | private static IQueryable QueryableEmpty() 92 | { 93 | return Enumerable.Empty().AsQueryable(); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Querying/ExtensionRebinder.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | using System.Runtime.CompilerServices; 6 | 7 | #if EF_CORE 8 | namespace EntityFrameworkCore.CommonTools 9 | #elif EF_6 10 | namespace EntityFramework.CommonTools 11 | #else 12 | namespace System.Linq.CommonTools 13 | #endif 14 | { 15 | internal class ExtensionRebinder : ExpressionVisitor 16 | { 17 | private readonly object _originalQueryable; 18 | private readonly Expression _replacementQueryable; 19 | private readonly List> _argumentReplacements; 20 | 21 | public ExtensionRebinder( 22 | object originalQueryable, Expression replacementQueryable, 23 | List> argumentReplacements) 24 | { 25 | _originalQueryable = originalQueryable; 26 | _replacementQueryable = replacementQueryable; 27 | _argumentReplacements = argumentReplacements; 28 | } 29 | 30 | protected override Expression VisitConstant(ConstantExpression node) 31 | { 32 | return node.Value == _originalQueryable ? _replacementQueryable : node; 33 | } 34 | 35 | protected override Expression VisitMember(MemberExpression node) 36 | { 37 | if (node.NodeType == ExpressionType.MemberAccess 38 | && node.Expression.NodeType == ExpressionType.Constant 39 | && node.Expression.Type.GetTypeInfo().IsDefined(typeof(CompilerGeneratedAttribute))) 40 | { 41 | string argumentName = node.Member.Name; 42 | 43 | Expression replacement = _argumentReplacements 44 | .Where(p => p.Key == argumentName) 45 | .Select(p => p.Value) 46 | .FirstOrDefault(); 47 | 48 | if (replacement != null) 49 | { 50 | return replacement; 51 | } 52 | } 53 | return base.VisitMember(node); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Querying/QueryableExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | 5 | #if EF_CORE 6 | namespace EntityFrameworkCore.CommonTools 7 | #elif EF_6 8 | namespace EntityFramework.CommonTools 9 | #else 10 | namespace System.Linq.CommonTools 11 | #endif 12 | { 13 | public static partial class QueryableExtensions 14 | { 15 | /// 16 | /// Expand all extension methods that marked by . 17 | /// 18 | public static IQueryable AsExpandable(this IQueryable queryable) 19 | { 20 | if (queryable == null) throw new ArgumentNullException(nameof(queryable)); 21 | 22 | #if EF_CORE 23 | return queryable.AsVisitable(new ExtensionExpander(), new AsQueryableExpander()); 24 | #else 25 | return queryable.AsVisitable(new ExtensionExpander()); 26 | #endif 27 | } 28 | 29 | /// 30 | /// Wrap to decorator that intercepts 31 | /// IQueryable.Expression with provided . 32 | /// 33 | public static IQueryable AsVisitable( 34 | this IQueryable queryable, params ExpressionVisitor[] visitors) 35 | { 36 | if (queryable == null) throw new ArgumentNullException(nameof(queryable)); 37 | if (visitors == null) throw new ArgumentNullException(nameof(visitors)); 38 | 39 | return queryable as VisitableQuery 40 | ?? VisitableQueryFactory.Create(queryable, visitors); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Querying/README.md: -------------------------------------------------------------------------------- 1 | ## Attaching ExpressionVisitor to IQueryable 2 | 3 | With `.AsVisitable()` extension we can attach any `ExpressionVisitor` to `IQueryable`. 4 | 5 | ```cs 6 | public static IQueryable AsVisitable( 7 | this IQueryable queryable, params ExpressionVisitor[] visitors); 8 | ``` 9 | 10 | ## Expandable extension methods for IQueryable 11 | 12 | We can use extension methods for `IQueryable` to incapsulate custom buisiness logic. 13 | But if we call these methods from `Expression`, we get runtime error. 14 | 15 | ```cs 16 | public static IQueryable FilterByAuthor(this IQueryable posts, int authorId) 17 | { 18 | return posts.Where(p => p.AuthorId = authorId); 19 | } 20 | 21 | public static IQueryable FilterTodayComments(this IQueryable comments) 22 | { 23 | DateTime today = DateTime.Now.Date; 24 | 25 | return comments.Where(c => c.CreationTime > today) 26 | } 27 | 28 | Comment[] comments = context.Posts 29 | .FilterByAuthor(authorId) // it's OK 30 | .SelectMany(p => p.Comments 31 | .AsQueryable() 32 | .FilterTodayComments()) // will throw Error 33 | .ToArray(); 34 | ``` 35 | 36 | With `.AsExpandable()` extension we can use extension methods everywhere. 37 | 38 | ```cs 39 | Comment[] comments = context.Posts 40 | .AsExpandable() 41 | .FilterByAuthor(authorId) // it's OK 42 | .SelectMany(p => p.Comments 43 | .FilterTodayComments()) // it's OK too 44 | .ToArray(); 45 | ``` 46 | 47 | Expandable extension methods should return `IQueryable` and should have `[Expandable]` attribute. 48 | 49 | ```cs 50 | [Expandable] 51 | public static IQueryable FilterByAuthor(this IEnumerable posts, int authorId) 52 | { 53 | return posts.AsQueryable().Where(p => p.AuthorId = authorId); 54 | } 55 | 56 | [Expandable] 57 | public static IQueryable FilterTodayComments(this IEnumerable comments) 58 | { 59 | DateTime today = DateTime.Now.Date; 60 | 61 | return comments.AsQueryable().Where(c => c.CreationTime > today) 62 | } 63 | ``` 64 | 65 |
66 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Querying/VisitableQuery.cs: -------------------------------------------------------------------------------- 1 | // The MIT License 2 | // Based on https://github.com/scottksmith95/LINQKit 3 | // Original work: Copyright (c) 2007-2009 Joseph Albahari, Tomas Petricek 4 | // Copyright (c) 2013-2017 Scott Smith, Stef Heyenrath, Tuomas Hietanen 5 | // Modified work: Copyright (c) 2017 Dmitry Panyushkin 6 | 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Linq.Expressions; 11 | using System.Collections; 12 | using System.Reflection; 13 | 14 | #if EF_CORE 15 | using Microsoft.EntityFrameworkCore; 16 | using Microsoft.EntityFrameworkCore.Query.Internal; 17 | 18 | namespace EntityFrameworkCore.CommonTools 19 | #elif EF_6 20 | using System.Data.Entity; 21 | using System.Data.Entity.Infrastructure; 22 | 23 | namespace EntityFramework.CommonTools 24 | #else 25 | namespace System.Linq.CommonTools 26 | #endif 27 | { 28 | /// 29 | /// An wrapper that allows us to visit 30 | /// the query's expression tree just before LINQ to SQL gets to it. 31 | /// 32 | internal class VisitableQuery : IQueryable, IOrderedQueryable, IOrderedQueryable 33 | #if EF_CORE 34 | , IAsyncEnumerable 35 | #elif EF_6 36 | , IDbAsyncEnumerable 37 | #endif 38 | { 39 | private readonly ExpressionVisitor[] _visitors; 40 | private readonly IQueryable _queryable; 41 | private readonly VisitableQueryProvider _provider; 42 | 43 | internal ExpressionVisitor[] Visitors => _visitors; 44 | internal IQueryable InnerQuery => _queryable; 45 | 46 | public VisitableQuery(IQueryable queryable, ExpressionVisitor[] visitors) 47 | { 48 | _queryable = queryable; 49 | _visitors = visitors; 50 | _provider = new VisitableQueryProvider(this); 51 | } 52 | 53 | Expression IQueryable.Expression => _queryable.Expression; 54 | 55 | Type IQueryable.ElementType => typeof(T); 56 | 57 | IQueryProvider IQueryable.Provider => _provider; 58 | 59 | public IEnumerator GetEnumerator() 60 | { 61 | return _queryable.GetEnumerator(); 62 | } 63 | 64 | IEnumerator IEnumerable.GetEnumerator() 65 | { 66 | return _queryable.GetEnumerator(); 67 | } 68 | 69 | public override string ToString() 70 | { 71 | return _queryable.ToString(); 72 | } 73 | 74 | #if EF_CORE 75 | IAsyncEnumerator IAsyncEnumerable.GetEnumerator() 76 | { 77 | return (_queryable as IAsyncEnumerable)?.GetEnumerator() 78 | ?? (_queryable as IAsyncEnumerableAccessor)?.AsyncEnumerable.GetEnumerator(); 79 | } 80 | #elif EF_6 81 | public IDbAsyncEnumerator GetAsyncEnumerator() 82 | { 83 | return (_queryable as IDbAsyncEnumerable)?.GetAsyncEnumerator() 84 | ?? new DbAsyncEnumerator(_queryable.GetEnumerator()); 85 | } 86 | 87 | IDbAsyncEnumerator IDbAsyncEnumerable.GetAsyncEnumerator() 88 | { 89 | return GetAsyncEnumerator(); 90 | } 91 | #endif 92 | } 93 | 94 | #if EF_CORE || EF_6 95 | internal class VisitableQueryOfClass : VisitableQuery 96 | where T : class 97 | { 98 | public VisitableQueryOfClass(IQueryable queryable, ExpressionVisitor[] visitors) 99 | : base(queryable, visitors) 100 | { 101 | } 102 | 103 | #if EF_CORE 104 | public IQueryable Include(Expression> navigationPropertyPath) 105 | { 106 | return InnerQuery.Include(navigationPropertyPath).AsVisitable(Visitors); 107 | } 108 | #elif EF_6 109 | public IQueryable Include(string path) 110 | { 111 | return InnerQuery.Include(path).AsVisitable(Visitors); 112 | } 113 | #endif 114 | } 115 | 116 | internal static class VisitableQueryFactory 117 | { 118 | public static readonly Func, ExpressionVisitor[], VisitableQuery> Create; 119 | 120 | static VisitableQueryFactory() 121 | { 122 | if (!typeof(T).GetTypeInfo().IsClass) 123 | { 124 | Create = (query, visitors) => new VisitableQuery(query, visitors); 125 | return; 126 | } 127 | 128 | var queryType = typeof(IQueryable); 129 | var visitorsType = typeof(ExpressionVisitor[]); 130 | var ctorInfo = typeof(VisitableQueryOfClass<>) 131 | .MakeGenericType(typeof(T)) 132 | .GetConstructor(new[] { queryType, visitorsType }); 133 | 134 | var queryParam = Expression.Parameter(queryType); 135 | var visitorsParam = Expression.Parameter(visitorsType); 136 | var newExpr = Expression.New(ctorInfo, queryParam, visitorsParam); 137 | var createExpr = Expression.Lambda, ExpressionVisitor[], VisitableQuery>>( 138 | newExpr, queryParam, visitorsParam); 139 | 140 | Create = createExpr.Compile(); 141 | } 142 | } 143 | #endif 144 | } 145 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Querying/VisitableQueryProvider.cs: -------------------------------------------------------------------------------- 1 | // The MIT License 2 | // Based on https://github.com/scottksmith95/LINQKit 3 | // Original work: Copyright (c) 2007-2009 Joseph Albahari, Tomas Petricek 4 | // Copyright (c) 2013-2017 Scott Smith, Stef Heyenrath, Tuomas Hietanen 5 | // Modified work: Copyright (c) 2017 Dmitry Panyushkin 6 | 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Linq.Expressions; 10 | using System.Threading; 11 | using System.Threading.Tasks; 12 | 13 | #if EF_CORE 14 | using Microsoft.EntityFrameworkCore.Query.Internal; 15 | 16 | namespace EntityFrameworkCore.CommonTools 17 | #elif EF_6 18 | using System.Data.Entity; 19 | using System.Data.Entity.Infrastructure; 20 | 21 | namespace EntityFramework.CommonTools 22 | #else 23 | namespace System.Linq.CommonTools 24 | #endif 25 | { 26 | internal class VisitableQueryProvider : IQueryProvider 27 | #if EF_CORE 28 | , IAsyncQueryProvider 29 | #elif EF_6 30 | , IDbAsyncQueryProvider 31 | #endif 32 | { 33 | private readonly VisitableQuery _query; 34 | 35 | public VisitableQueryProvider(VisitableQuery query) 36 | { 37 | _query = query; 38 | } 39 | 40 | /// 41 | /// The following four methods first call ExpressionExpander to visit the expression tree, 42 | /// then call upon the inner query to do the remaining work. 43 | /// 44 | IQueryable IQueryProvider.CreateQuery(Expression expression) 45 | { 46 | expression = _query.Visitors.Visit(expression); 47 | return _query.InnerQuery.Provider.CreateQuery(expression).AsVisitable(_query.Visitors); 48 | } 49 | 50 | IQueryable IQueryProvider.CreateQuery(Expression expression) 51 | { 52 | expression = _query.Visitors.Visit(expression); 53 | return _query.InnerQuery.Provider.CreateQuery(expression); 54 | } 55 | 56 | TResult IQueryProvider.Execute(Expression expression) 57 | { 58 | expression = _query.Visitors.Visit(expression); 59 | return _query.InnerQuery.Provider.Execute(expression); 60 | } 61 | 62 | object IQueryProvider.Execute(Expression expression) 63 | { 64 | expression = _query.Visitors.Visit(expression); 65 | return _query.InnerQuery.Provider.Execute(expression); 66 | } 67 | 68 | #if EF_CORE 69 | public IAsyncEnumerable ExecuteAsync(Expression expression) 70 | { 71 | expression = _query.Visitors.Visit(expression); 72 | var asyncProvider = (IAsyncQueryProvider)_query.InnerQuery.Provider; 73 | return asyncProvider.ExecuteAsync(expression); 74 | } 75 | 76 | public Task ExecuteAsync(Expression expression, CancellationToken cancellationToken) 77 | { 78 | expression = _query.Visitors.Visit(expression); 79 | var asyncProvider = _query.InnerQuery.Provider as IAsyncQueryProvider; 80 | return asyncProvider?.ExecuteAsync(expression, cancellationToken) 81 | ?? Task.FromResult(_query.InnerQuery.Provider.Execute(expression)); 82 | } 83 | #elif EF_6 84 | public Task ExecuteAsync(Expression expression, CancellationToken cancellationToken) 85 | { 86 | expression = _query.Visitors.Visit(expression); 87 | var asyncProvider = _query.InnerQuery.Provider as IDbAsyncQueryProvider; 88 | return asyncProvider?.ExecuteAsync(expression, cancellationToken) 89 | ?? Task.FromResult(_query.InnerQuery.Provider.Execute(expression)); 90 | } 91 | 92 | public Task ExecuteAsync(Expression expression, CancellationToken cancellationToken) 93 | { 94 | expression = _query.Visitors.Visit(expression); 95 | var asyncProvider = _query.InnerQuery.Provider as IDbAsyncQueryProvider; 96 | return asyncProvider?.ExecuteAsync(expression, cancellationToken) 97 | ?? Task.FromResult(_query.InnerQuery.Provider.Execute(expression)); 98 | } 99 | #endif 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Querying/VisitorExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq.Expressions; 3 | 4 | #if EF_CORE 5 | namespace EntityFrameworkCore.CommonTools 6 | #elif EF_6 7 | namespace EntityFramework.CommonTools 8 | #else 9 | namespace System.Linq.CommonTools 10 | #endif 11 | { 12 | public static class VisitorExtensions 13 | { 14 | /// 15 | /// Apply all to Expression one by one. 16 | /// 17 | public static Expression Visit(this IEnumerable visitors, Expression node) 18 | { 19 | if (visitors != null) 20 | { 21 | foreach (ExpressionVisitor visitor in visitors) 22 | { 23 | node = visitor.Visit(node); 24 | } 25 | } 26 | return node; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Specification/ParameterReplacer.cs: -------------------------------------------------------------------------------- 1 | using System.Linq.Expressions; 2 | 3 | #if EF_CORE 4 | namespace EntityFrameworkCore.CommonTools 5 | #elif EF_6 6 | namespace EntityFramework.CommonTools 7 | #else 8 | namespace System.Linq.CommonTools 9 | #endif 10 | { 11 | internal class ParameterReplacer : ExpressionVisitor 12 | { 13 | private readonly ParameterExpression _parameter; 14 | private readonly ParameterExpression _replacement; 15 | 16 | public ParameterReplacer(ParameterExpression parameter, ParameterExpression replacement) 17 | { 18 | _parameter = parameter; 19 | _replacement = replacement; 20 | } 21 | 22 | protected override Expression VisitParameter(ParameterExpression node) 23 | { 24 | return base.VisitParameter(_parameter == node ? _replacement : node); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Specification/README.md: -------------------------------------------------------------------------------- 1 | ## Specification Pattern 2 | 3 | Generic implementation of [Specification Pattern](https://en.wikipedia.org/wiki/Specification_pattern). 4 | 5 | ```cs 6 | public interface ISpecification 7 | { 8 | bool IsSatisfiedBy(T entity); 9 | 10 | Expression> ToExpression(); 11 | } 12 | 13 | public class Specification : ISpecification 14 | { 15 | public Specification(Expression> predicate); 16 | } 17 | ``` 18 | 19 | We can define named specifications: 20 | ```cs 21 | class UserIsActiveSpec : Specification 22 | { 23 | public UserIsActiveSpec() 24 | : base(u => !u.IsDeleted) { } 25 | } 26 | 27 | class UserByLoginSpec : Specification 28 | { 29 | public UserByLoginSpec(string login) 30 | : base(u => u.Login == login) { } 31 | } 32 | ``` 33 | 34 | Then we can combine specifications with conditional logic operators `&&`, `||` and `!`: 35 | ```cs 36 | class CombinedSpec 37 | { 38 | public CombinedSpec(string login) 39 | : base(new UserIsActiveSpec() && new UserByLoginSpec(login)) { } 40 | } 41 | ``` 42 | 43 | Also we can test it: 44 | ```cs 45 | var user = new User { Login = "admin", IsDeleted = false }; 46 | var spec = new CombinedSpec("admin"); 47 | 48 | Assert.IsTrue(spec.IsSatisfiedBy(user)); 49 | ``` 50 | 51 | And use with `IEnumerable`: 52 | 53 | ```cs 54 | var users = Enumerable.Empty(); 55 | var spec = new UserByLoginSpec("admin"); 56 | 57 | var admin = users.FirstOrDefault(spec.IsSatisfiedBy); 58 | 59 | // or even 60 | var admin = users.FirstOrDefault(spec); 61 | ``` 62 | 63 | Or even with `IQueryable`: 64 | ```cs 65 | var spec = new UserByLoginSpec("admin"); 66 | 67 | var admin = context.Users.FirstOrDefault(spec.ToExpression()); 68 | 69 | // or even 70 | var admin = context.Users.FirstOrDefault(spec); 71 | 72 | // and also inside Expression 73 | var adminFiends = context.Users 74 | .AsVisitable(new SpecificationExpander()) 75 | .Where(u => u.Firends.Any(spec.ToExpression())) 76 | .ToList(); 77 | 78 | // or even 79 | var adminFiends = context.Users 80 | .AsVisitable(new SpecificationExpander()) 81 | .Where(u => u.Firends.Any(spec)) 82 | .ToList(); 83 | ``` 84 | 85 |
86 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Specification/Specification.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | 6 | #if EF_CORE 7 | namespace EntityFrameworkCore.CommonTools 8 | #elif EF_6 9 | namespace EntityFramework.CommonTools 10 | #else 11 | namespace System.Linq.CommonTools 12 | #endif 13 | { 14 | /// 15 | /// Specification pattern https://en.wikipedia.org/wiki/Specification_pattern. 16 | /// 17 | /// 18 | public interface ISpecification 19 | { 20 | bool IsSatisfiedBy(T entity); 21 | 22 | Expression> ToExpression(); 23 | } 24 | 25 | /// 26 | /// Implementation of Specification pattern, that can be used with expressions. 27 | /// 28 | [DebuggerDisplay("{Predicate}")] 29 | public class Specification : ISpecification 30 | { 31 | private Func _function; 32 | 33 | private Func Function => _function ?? (_function = Predicate.Compile()); 34 | 35 | protected Expression> Predicate; 36 | 37 | protected Specification() { } 38 | 39 | public Specification(Expression> predicate) 40 | { 41 | Predicate = predicate; 42 | } 43 | 44 | public bool IsSatisfiedBy(T entity) 45 | { 46 | return Function.Invoke(entity); 47 | } 48 | 49 | public Expression> ToExpression() 50 | { 51 | return Predicate; 52 | } 53 | 54 | public static implicit operator Func(Specification spec) 55 | { 56 | if (spec == null) throw new ArgumentNullException(nameof(spec)); 57 | 58 | return spec.Function; 59 | } 60 | 61 | public static implicit operator Expression>(Specification spec) 62 | { 63 | if (spec == null) throw new ArgumentNullException(nameof(spec)); 64 | 65 | return spec.Predicate; 66 | } 67 | 68 | /// 69 | /// 70 | /// For user-defined conditional logical operators. 71 | /// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/true-false-operators 72 | /// 73 | /// 74 | public static bool operator true(Specification spec) 75 | { 76 | return false; 77 | } 78 | 79 | 80 | /// 81 | /// 82 | /// For user-defined conditional logical operators. 83 | /// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/true-false-operators 84 | /// 85 | /// 86 | public static bool operator false(Specification spec) 87 | { 88 | return false; 89 | } 90 | 91 | public static Specification operator !(Specification spec) 92 | { 93 | if (spec == null) throw new ArgumentNullException(nameof(spec)); 94 | 95 | return new Specification( 96 | Expression.Lambda>( 97 | Expression.Not(spec.Predicate.Body), 98 | spec.Predicate.Parameters)); 99 | } 100 | 101 | public static Specification operator &(Specification left, Specification right) 102 | { 103 | if (left == null) throw new ArgumentNullException(nameof(left)); 104 | if (right == null) throw new ArgumentNullException(nameof(right)); 105 | 106 | var leftExpr = left.Predicate; 107 | var rightExpr = right.Predicate; 108 | var leftParam = leftExpr.Parameters[0]; 109 | var rightParam = rightExpr.Parameters[0]; 110 | 111 | return new Specification( 112 | Expression.Lambda>( 113 | Expression.AndAlso( 114 | leftExpr.Body, 115 | new ParameterReplacer(rightParam, leftParam).Visit(rightExpr.Body)), 116 | leftParam)); 117 | } 118 | 119 | public static Specification operator |(Specification left, Specification right) 120 | { 121 | if (left == null) throw new ArgumentNullException(nameof(left)); 122 | if (right == null) throw new ArgumentNullException(nameof(right)); 123 | 124 | var leftExpr = left.Predicate; 125 | var rightExpr = right.Predicate; 126 | var leftParam = leftExpr.Parameters[0]; 127 | var rightParam = rightExpr.Parameters[0]; 128 | 129 | return new Specification( 130 | Expression.Lambda>( 131 | Expression.OrElse( 132 | leftExpr.Body, 133 | new ParameterReplacer(rightParam, leftParam).Visit(rightExpr.Body)), 134 | leftParam)); 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /EFCore.CommonTools/Specification/SpecificationExpander.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | 6 | #if EF_CORE 7 | namespace EntityFrameworkCore.CommonTools 8 | #elif EF_6 9 | namespace EntityFramework.CommonTools 10 | #else 11 | namespace System.Linq.CommonTools 12 | #endif 13 | { 14 | /// 15 | /// that expands inside Expression. 16 | /// 17 | public class SpecificationExpander : ExpressionVisitor 18 | { 19 | protected override Expression VisitUnary(UnaryExpression node) 20 | { 21 | if (node.NodeType == ExpressionType.Convert) 22 | { 23 | MethodInfo method = node.Method; 24 | 25 | if (method != null && method.Name == "op_Implicit") 26 | { 27 | Type declaringType = method.DeclaringType; 28 | 29 | if (declaringType.GetTypeInfo().IsGenericType 30 | && declaringType.GetGenericTypeDefinition() == typeof(Specification<>)) 31 | { 32 | const string name = nameof(Specification.ToExpression); 33 | 34 | MethodInfo toExpression = declaringType.GetMethod(name); 35 | 36 | return ExpandSpecification(node.Operand, toExpression); 37 | } 38 | } 39 | } 40 | 41 | return base.VisitUnary(node); 42 | } 43 | 44 | protected override Expression VisitMethodCall(MethodCallExpression node) 45 | { 46 | MethodInfo method = node.Method; 47 | 48 | if (method.Name == nameof(ISpecification.ToExpression)) 49 | { 50 | Type declaringType = method.DeclaringType; 51 | Type[] interfaces = declaringType.GetTypeInfo().GetInterfaces(); 52 | 53 | if (interfaces.Any(i => i.GetTypeInfo().IsGenericType 54 | && i.GetGenericTypeDefinition() == typeof(ISpecification<>))) 55 | { 56 | return ExpandSpecification(node.Object, method); 57 | } 58 | } 59 | 60 | return base.VisitMethodCall(node); 61 | } 62 | 63 | private Expression ExpandSpecification(Expression specification, MethodInfo toExpression) 64 | { 65 | object expression = Expression.Call(specification, toExpression).GetValue(); 66 | 67 | return Visit((Expression)expression); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /EFCore.CommonTools/TransactionLog/README.md: -------------------------------------------------------------------------------- 1 | ## Transaction Logs 2 | Write all inserted / updated / deleted entities (serialized to JSON) to the separete table named `TransactionLog`. 3 | 4 | To capture transaction logs an entity must inherit from empty `ITransactionLoggable { }` interface. 5 | 6 | And the `DbContext` should overload `SaveChanges()` method with `SaveChangesWithTransactionLog()` wrapper, 7 | and register the `TransactionLog` entity in `ModelBuilder`. 8 | 9 | ```cs 10 | class Post : ITransactionLoggable 11 | { 12 | public string Content { get; set; } 13 | } 14 | 15 | // for EntityFramework 6 16 | class MyDbContext : DbContext 17 | { 18 | public DbSet Posts { get; set; } 19 | 20 | protected override void OnModelCreating(DbModelBuilder modelBuilder) 21 | { 22 | modelBuilder.UseTransactionLog(); 23 | } 24 | 25 | public override int SaveChanges() 26 | { 27 | return this.SaveChangesWithTransactionLog(base.SaveChanges); 28 | } 29 | 30 | // override the most general SaveChangesAsync 31 | public override Task SaveChangesAsync(CancellationToken cancellationToken) 32 | { 33 | return this.SaveChangesWithTransactionLogAsync(base.SaveChangesAsync, cancellationToken); 34 | } 35 | } 36 | 37 | // for EntityFramework Core 38 | class MyCoreDbContext : DbContext 39 | { 40 | public DbSet Posts { get; set; } 41 | 42 | protected override void OnModelCreating(DbModelBuilder modelBuilder) 43 | { 44 | modelBuilder.UseTransactionLog(); 45 | } 46 | 47 | // override the most general SaveChanges 48 | public override int SaveChanges(bool acceptAllChangesOnSuccess) 49 | { 50 | return this.SaveChangesWithTransactionLog(base.SaveChanges, acceptAllChangesOnSuccess); 51 | } 52 | 53 | // override the most general SaveChangesAsync 54 | public override Task SaveChangesAsync( 55 | bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken)) 56 | { 57 | return this.SaveChangesWithTransactionLogAsync( 58 | base.SaveChangesAsync, acceptAllChangesOnSuccess, cancellationToken); 59 | } 60 | } 61 | 62 | ``` 63 | 64 | After that the transaction logs can be accessed via `TransactionLog` entity: 65 | 66 | ```cs 67 | class TransactionLog 68 | { 69 | // Auto incremented primary key. 70 | public long Id { get; set; } 71 | 72 | // An ID of all changes that captured during single DbContext.SaveChanges() call. 73 | public Guid TransactionId { get; set; } 74 | 75 | // UTC timestamp of DbContext.SaveChanges() call. 76 | public DateTime CreatedUtc { get; set; } 77 | 78 | // "INS", "UPD" or "DEL". Not null. 79 | public string Operation { get; set; } 80 | 81 | // Schema for captured entity. Can be null for SQLite. 82 | public string Schema { get; set; } 83 | 84 | // Table for captured entity. Not null. 85 | public string TableName { get; set; } 86 | 87 | // Assembly qualified type name of captured entity. Not null. 88 | public string EntityType { get; set; } 89 | 90 | // The captured entity serialized to JSON by Jil serializer. Not null. 91 | public string EntityJson { get; set; } 92 | 93 | // Lazily deserialized entity object. 94 | // Type for deserialization is taken from EntityType property. 95 | // All navigation properties and collections will be empty. 96 | public object Entity { get; } 97 | 98 | // Get strongly typed entity from transaction log. 99 | // Can be null if TEntity and type from EntityType property are incompatible. 100 | // All navigation properties and collections will be empty. 101 | public TEntity GetEntity(); 102 | } 103 | ``` 104 | 105 |
106 | -------------------------------------------------------------------------------- /EFCore.CommonTools/TransactionLog/TransactionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | 4 | #if EF_CORE 5 | using Microsoft.EntityFrameworkCore; 6 | 7 | namespace EntityFrameworkCore.CommonTools 8 | #elif EF_6 9 | using System.Data.Entity; 10 | 11 | namespace EntityFramework.CommonTools 12 | #endif 13 | { 14 | public static partial class DbContextExtensions 15 | { 16 | /// 17 | /// Execute in existing transaction or create and use new transaction. 18 | /// 19 | internal static T ExecuteInTransaction(this DbContext context, Func method) 20 | { 21 | var currentTransaction = context.Database.CurrentTransaction; 22 | var transaction = currentTransaction ?? context.Database.BeginTransaction(); 23 | 24 | try 25 | { 26 | T result = method.Invoke(); 27 | if (transaction != currentTransaction) 28 | { 29 | transaction.Commit(); 30 | } 31 | return result; 32 | } 33 | catch 34 | { 35 | if (transaction != currentTransaction) 36 | { 37 | transaction.Rollback(); 38 | } 39 | throw; 40 | } 41 | finally 42 | { 43 | if (transaction != currentTransaction) 44 | { 45 | transaction.Dispose(); 46 | } 47 | } 48 | } 49 | 50 | /// 51 | /// Execute in existing transaction or create and use new transaction. 52 | /// 53 | internal static async Task ExecuteInTransaction(this DbContext context, Func> asyncMethod) 54 | { 55 | var currentTransaction = context.Database.CurrentTransaction; 56 | var transaction = currentTransaction ?? context.Database.BeginTransaction(); 57 | 58 | try 59 | { 60 | T result = await asyncMethod.Invoke(); 61 | if (transaction != currentTransaction) 62 | { 63 | transaction.Commit(); 64 | } 65 | return result; 66 | } 67 | catch 68 | { 69 | if (transaction != currentTransaction) 70 | { 71 | transaction.Rollback(); 72 | } 73 | throw; 74 | } 75 | finally 76 | { 77 | if (transaction != currentTransaction) 78 | { 79 | transaction.Dispose(); 80 | } 81 | } 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /EFCore.CommonTools/TransactionLog/TransactionLog.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using Jil; 4 | 5 | #if EF_CORE 6 | using Microsoft.EntityFrameworkCore; 7 | 8 | namespace EntityFrameworkCore.CommonTools 9 | #elif EF_6 10 | using System.Data.Entity; 11 | 12 | namespace EntityFramework.CommonTools 13 | #endif 14 | { 15 | /// 16 | /// This interface is implemented by entities which wanted 17 | /// to store all modifications in . 18 | /// 19 | public interface ITransactionLoggable { } 20 | 21 | [DebuggerDisplay("{TableName} {CreatedUtc}", Name = "{Id} {Operation}")] 22 | public class TransactionLog 23 | { 24 | public const string INSERT = "INS"; 25 | public const string UPDATE = "UPD"; 26 | public const string DELETE = "DEL"; 27 | 28 | /// 29 | /// Auto incremented primary key. 30 | /// 31 | public long Id { get; set; } 32 | 33 | /// 34 | /// An ID of all changes that captured during single call. 35 | /// 36 | public Guid TransactionId { get; set; } 37 | 38 | /// 39 | /// UTC timestamp of call. 40 | /// 41 | public DateTime CreatedUtc { get; set; } 42 | 43 | /// 44 | /// "INS", "UPD" or "DEL". Not null. 45 | /// 46 | public string Operation { get; set; } 47 | 48 | /// 49 | /// Schema for captured entity. Can be null for SQLite. 50 | /// 51 | public string Schema { get; set; } 52 | 53 | /// 54 | /// Table for captured entity. Not null. 55 | /// 56 | public string TableName { get; set; } 57 | 58 | /// 59 | /// Assembly qualified type name of captured entity. Not null. 60 | /// 61 | public string EntityType { get; set; } 62 | 63 | /// 64 | /// The captured entity serialized to JSON by Jil serializer. Not null. 65 | /// 66 | public string EntityJson { get; set; } 67 | 68 | private object _entity; 69 | /// 70 | /// Lazily deserialized entity object. 71 | /// Type for deserialization is taken from property. 72 | /// All navigation properties and collections will be empty. 73 | /// 74 | public object Entity => _entity 75 | ?? (_entity = JSON.Deserialize(EntityJson, Type.GetType(EntityType))); 76 | 77 | /// 78 | /// Get strongly typed entity from transaction log. 79 | /// Can be null if TEntity and type from property are incompatible. 80 | /// All navigation properties and collections will be empty. 81 | /// 82 | public TEntity GetEntity() 83 | where TEntity : class 84 | { 85 | return Entity as TEntity; 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /EFCore.CommonTools/TransactionLog/TransactionLogContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Jil; 5 | 6 | #if EF_CORE 7 | using Microsoft.EntityFrameworkCore; 8 | using Microsoft.EntityFrameworkCore.ChangeTracking; 9 | 10 | namespace EntityFrameworkCore.CommonTools 11 | #elif EF_6 12 | using System.Data.Entity; 13 | using System.Data.Entity.Core.Objects; 14 | using System.Data.Entity.Infrastructure; 15 | using EntityEntry = System.Data.Entity.Infrastructure.DbEntityEntry; 16 | 17 | namespace EntityFramework.CommonTools 18 | #endif 19 | { 20 | /// 21 | /// Utility for capturing transaction logs from . 22 | /// Tracked entities must implement interface. 23 | /// 24 | internal class TransactionLogContext 25 | { 26 | private readonly DbContext _context; 27 | private readonly Guid _transactionId = Guid.NewGuid(); 28 | private readonly DateTime _createdUtc = DateTime.UtcNow; 29 | 30 | private readonly List _insertedEntries = new List(); 31 | private readonly List _updatedEntries = new List(); 32 | private readonly List _deletedLogs = new List(); 33 | 34 | public TransactionLogContext(DbContext context) 35 | { 36 | _context = context; 37 | 38 | StoreChangedEntries(); 39 | } 40 | 41 | private void StoreChangedEntries() 42 | { 43 | var changedEntries = _context.ChangeTracker.Entries() 44 | .Where(e => e.State == EntityState.Added 45 | || e.State == EntityState.Modified 46 | || e.State == EntityState.Deleted); 47 | 48 | foreach (var entry in changedEntries) 49 | { 50 | if (entry.Entity is ITransactionLoggable) 51 | { 52 | switch (entry.State) 53 | { 54 | case EntityState.Added: 55 | _insertedEntries.Add(entry); 56 | break; 57 | 58 | case EntityState.Modified: 59 | _updatedEntries.Add(entry); 60 | break; 61 | 62 | case EntityState.Deleted: 63 | _deletedLogs.Add(CreateTransactionLog(entry, TransactionLog.DELETE)); 64 | break; 65 | } 66 | } 67 | } 68 | } 69 | 70 | public void AddTransactionLogEntities() 71 | { 72 | foreach (TransactionLog transactionLog in CreateTransactionLogs()) 73 | { 74 | _context.Entry(transactionLog).State = EntityState.Added; 75 | } 76 | } 77 | 78 | private IEnumerable CreateTransactionLogs() 79 | { 80 | foreach (EntityEntry insertedEntry in _insertedEntries) 81 | { 82 | yield return CreateTransactionLog(insertedEntry, TransactionLog.INSERT); 83 | } 84 | foreach (EntityEntry updateEntry in _updatedEntries) 85 | { 86 | yield return CreateTransactionLog(updateEntry, TransactionLog.UPDATE); 87 | } 88 | foreach (TransactionLog deletedLog in _deletedLogs) 89 | { 90 | yield return deletedLog; 91 | } 92 | } 93 | 94 | private TransactionLog CreateTransactionLog(EntityEntry entry, string operation) 95 | { 96 | object entity = entry.Entity; 97 | 98 | Type entityType = entity.GetType(); 99 | #if EF_CORE 100 | var tableAndSchema = entry.Metadata.Relational(); 101 | #elif EF_6 102 | if (_context.Configuration.ProxyCreationEnabled) 103 | { 104 | entityType = ObjectContext.GetObjectType(entityType); 105 | } 106 | 107 | var tableAndSchema = _context.GetTableAndSchemaName(entityType); 108 | #endif 109 | var log = new TransactionLog 110 | { 111 | TransactionId = _transactionId, 112 | CreatedUtc = _createdUtc, 113 | Operation = operation, 114 | Schema = tableAndSchema.Schema, 115 | TableName = tableAndSchema.TableName, 116 | EntityType = GetTypeName(entityType), 117 | }; 118 | 119 | if (operation == TransactionLog.DELETE) 120 | { 121 | #if EF_CORE 122 | var primaryKey = entry.Metadata 123 | .FindPrimaryKey() 124 | .Properties 125 | .Select(p => entry.Property(p.Name)) 126 | .ToDictionary(p => p.Metadata.Name, p => p.CurrentValue); 127 | #elif EF_6 128 | var primaryKey = ((IObjectContextAdapter)_context) 129 | .ObjectContext.ObjectStateManager 130 | .GetObjectStateEntry(entity) 131 | .EntityKey.EntityKeyValues 132 | .ToDictionary(k => k.Key, k => k.Value); 133 | #endif 134 | log.EntityJson = JSON.SerializeDynamic(primaryKey); 135 | } 136 | else 137 | { 138 | log.EntityJson = JSON.SerializeDynamic( 139 | entry.CurrentValues.ToObject(), Options.IncludeInherited); 140 | } 141 | 142 | return log; 143 | } 144 | 145 | private string GetTypeName(Type type) 146 | { 147 | string name = type.AssemblyQualifiedName; 148 | 149 | return name.Substring(0, name.IndexOf(", Version=")); 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /EFCore.CommonTools/TransactionLog/TransactionLogExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | #if EF_CORE 6 | using Microsoft.EntityFrameworkCore; 7 | 8 | namespace EntityFrameworkCore.CommonTools 9 | #elif EF_6 10 | using System.Data.Entity; 11 | using ModelBuilder = System.Data.Entity.DbModelBuilder; 12 | 13 | namespace EntityFramework.CommonTools 14 | #endif 15 | { 16 | public static partial class DbContextExtensions 17 | { 18 | /// 19 | /// Wrapper for that saves to DB. 20 | /// 21 | public static int SaveChangesWithTransactionLog( 22 | #if EF_CORE 23 | this DbContext dbContext, Func baseSaveChanges, bool acceptAllChangesOnSuccess = true) 24 | #elif EF_6 25 | this DbContext dbContext, Func baseSaveChanges) 26 | #endif 27 | { 28 | return dbContext.ExecuteInTransaction(() => 29 | { 30 | var logContext = new TransactionLogContext(dbContext); 31 | #if EF_CORE 32 | // save main entities 33 | int count = baseSaveChanges.Invoke(acceptAllChangesOnSuccess); 34 | #elif EF_6 35 | // save main entities 36 | int count = baseSaveChanges.Invoke(); 37 | #endif 38 | logContext.AddTransactionLogEntities(); 39 | #if EF_CORE 40 | // save TransactionLog entities 41 | baseSaveChanges.Invoke(acceptAllChangesOnSuccess); 42 | #elif EF_6 43 | // save TransactionLog entities 44 | baseSaveChanges.Invoke(); 45 | #endif 46 | return count; 47 | }); 48 | } 49 | 50 | /// 51 | /// Wrapper for 52 | /// that saves to DB. 53 | /// 54 | public static Task SaveChangesWithTransactionLogAsync( 55 | #if EF_CORE 56 | this DbContext dbContext, 57 | Func> baseSaveChangesAsync, 58 | bool acceptAllChangesOnSuccess = true, 59 | CancellationToken cancellationToken = default(CancellationToken)) 60 | #elif EF_6 61 | this DbContext dbContext, 62 | Func> baseSaveChangesAsync, 63 | CancellationToken cancellationToken = default(CancellationToken)) 64 | #endif 65 | { 66 | return dbContext.ExecuteInTransaction(async () => 67 | { 68 | var logContext = new TransactionLogContext(dbContext); 69 | #if EF_CORE 70 | // save main entities 71 | int count = await baseSaveChangesAsync.Invoke(acceptAllChangesOnSuccess, cancellationToken); 72 | #elif EF_6 73 | // save main entities 74 | int count = await baseSaveChangesAsync.Invoke(cancellationToken); 75 | #endif 76 | logContext.AddTransactionLogEntities(); 77 | #if EF_CORE 78 | // save TransactionLog entities 79 | await baseSaveChangesAsync.Invoke(acceptAllChangesOnSuccess, cancellationToken); 80 | #elif EF_6 81 | // save TransactionLog entities 82 | await baseSaveChangesAsync.Invoke(cancellationToken); 83 | #endif 84 | return count; 85 | }); 86 | } 87 | } 88 | 89 | public static partial class ModelBuilderExtensions 90 | { 91 | /// 92 | /// Register table in . 93 | /// 94 | public static ModelBuilder UseTransactionLog( 95 | this ModelBuilder modelBuilder, 96 | string tableName = "_TransactionLog", 97 | string schemaName = null) 98 | { 99 | var transactionLog = modelBuilder.Entity(); 100 | 101 | if (schemaName == null) 102 | { 103 | transactionLog.ToTable(tableName); 104 | } 105 | else 106 | { 107 | transactionLog.ToTable(tableName, schemaName); 108 | } 109 | 110 | transactionLog 111 | .HasKey(e => e.Id); 112 | 113 | transactionLog 114 | .Property(e => e.Operation) 115 | .IsRequired() 116 | .HasMaxLength(3); 117 | 118 | transactionLog 119 | .Property(e => e.TableName) 120 | .IsRequired(); 121 | 122 | transactionLog 123 | .Property(e => e.EntityType) 124 | .IsRequired(); 125 | 126 | transactionLog 127 | .Property(e => e.EntityJson) 128 | .IsRequired(); 129 | 130 | return modelBuilder; 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Benchmarks/EntityFramework.CommonTools.Benchmarks.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {01646964-497E-43A0-897C-267A3D04F429} 8 | Exe 9 | EntityFramework.CommonTools.Benchmarks 10 | EntityFramework.CommonTools.Benchmarks 11 | v4.5 12 | 512 13 | 14 | 15 | AnyCPU 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | AnyCPU 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | ..\packages\BenchmarkDotNet.0.9.9\lib\net45\BenchmarkDotNet.dll 36 | 37 | 38 | ..\packages\BenchmarkDotNet.Core.0.9.9\lib\net45\BenchmarkDotNet.Core.dll 39 | 40 | 41 | ..\packages\BenchmarkDotNet.Toolchains.Roslyn.0.9.9\lib\net45\BenchmarkDotNet.Toolchains.Roslyn.dll 42 | 43 | 44 | ..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll 45 | 46 | 47 | ..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll 48 | 49 | 50 | ..\packages\Microsoft.CodeAnalysis.Common.1.3.2\lib\net45\Microsoft.CodeAnalysis.dll 51 | 52 | 53 | ..\packages\Microsoft.CodeAnalysis.CSharp.1.3.2\lib\net45\Microsoft.CodeAnalysis.CSharp.dll 54 | 55 | 56 | 57 | 58 | ..\packages\System.Collections.Immutable.1.1.37\lib\dotnet\System.Collections.Immutable.dll 59 | 60 | 61 | 62 | 63 | 64 | ..\packages\System.Data.SQLite.Core.1.0.108.0\lib\net45\System.Data.SQLite.dll 65 | 66 | 67 | ..\packages\System.Data.SQLite.EF6.1.0.108.0\lib\net45\System.Data.SQLite.EF6.dll 68 | 69 | 70 | ..\packages\System.Data.SQLite.Linq.1.0.108.0\lib\net45\System.Data.SQLite.Linq.dll 71 | 72 | 73 | 74 | ..\packages\System.Reflection.Metadata.1.2.0\lib\portable-net45+win8\System.Reflection.Metadata.dll 75 | 76 | 77 | 78 | ..\packages\System.Threading.Tasks.Extensions.4.0.0\lib\portable-net45+win8+wp8+wpa81\System.Threading.Tasks.Extensions.dll 79 | 80 | 81 | 82 | 83 | 84 | 85 | %(RecursiveDir)%(Filename)%(Extension) 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | {1760a172-08a0-4232-b507-55e08971e87d} 96 | EntityFramework.CommonTools 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Benchmarks/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("EntityFramework.CommonTools.Benchmarks")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("Microsoft")] 9 | [assembly: AssemblyProduct("EntityFramework.CommonTools.Benchmarks")] 10 | [assembly: AssemblyCopyright("Copyright © Dmitry Panyushkin 2017")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("01646964-497e-43a0-897c-267a3d04f429")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Benchmarks/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 |
5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Benchmarks/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Tests/Extensions/ChangeTrackingExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity; 2 | using System.Linq; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | namespace EntityFramework.CommonTools.Tests 6 | { 7 | [TestClass] 8 | public class ChangeTrackingExtensionsTests : TestInitializer 9 | { 10 | [TestMethod] 11 | public void ShouldNotDetectChangesInsideUsingBlock() 12 | { 13 | using (var context = CreateInMemoryDbContext()) 14 | { 15 | var user = new User(); 16 | context.Users.Add(user); 17 | context.SaveChanges(); 18 | 19 | using (context.WithoutChangeTracking()) 20 | { 21 | user.Login = "admin"; 22 | 23 | var changedEntries = context.ChangeTracker.Entries() 24 | .Where(e => e.State == EntityState.Modified) 25 | .ToArray(); 26 | 27 | Assert.AreEqual(0, changedEntries.Length); 28 | } 29 | } 30 | } 31 | 32 | [TestMethod] 33 | public void ShouldDetectChangesOutsideOfUsingBlock() 34 | { 35 | using (var context = CreateInMemoryDbContext()) 36 | { 37 | var user = new User(); 38 | context.Users.Add(user); 39 | context.SaveChanges(); 40 | 41 | using (context.WithoutChangeTracking()) 42 | { 43 | user.Login = "admin"; 44 | } 45 | 46 | var changedEntries = context.ChangeTracker.Entries() 47 | .Where(e => e.State == EntityState.Modified) 48 | .ToArray(); 49 | 50 | Assert.AreEqual(1, changedEntries.Length); 51 | } 52 | } 53 | 54 | [TestMethod] 55 | public void ShouldDetectChangesOnceInsideUsingBlock() 56 | { 57 | using (var context = CreateInMemoryDbContext()) 58 | { 59 | var first = new User(); 60 | var second = new User(); 61 | context.Users.Add(first); 62 | context.Users.Add(second); 63 | context.SaveChanges(); 64 | 65 | first.Login = "first"; 66 | 67 | using (context.WithChangeTrackingOnce()) 68 | { 69 | second.Login = "second"; 70 | 71 | var changedEntries = context.ChangeTracker.Entries() 72 | .Where(e => e.State == EntityState.Modified) 73 | .ToArray(); 74 | 75 | Assert.AreEqual(1, changedEntries.Length); 76 | } 77 | } 78 | } 79 | 80 | [TestMethod] 81 | public void ShouldDetectChangesAnyTimesOutsideOfUsingBlock() 82 | { 83 | using (var context = CreateInMemoryDbContext()) 84 | { 85 | var first = new User(); 86 | var second = new User(); 87 | context.Users.Add(first); 88 | context.Users.Add(second); 89 | context.SaveChanges(); 90 | 91 | first.Login = "first"; 92 | 93 | using (context.WithChangeTrackingOnce()) 94 | { 95 | second.Login = "second"; 96 | } 97 | 98 | var changedEntries = context.ChangeTracker.Entries() 99 | .Where(e => e.State == EntityState.Modified) 100 | .ToArray(); 101 | 102 | Assert.AreEqual(2, changedEntries.Length); 103 | } 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Tests/Extensions/TableNameExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | 3 | namespace EntityFramework.CommonTools.Tests 4 | { 5 | [TestClass] 6 | public class TableNameExtensionsTests : TestInitializer 7 | { 8 | [TestMethod] 9 | public void ShouldReturnTableAndSchemaName() 10 | { 11 | using (var context = CreateSqliteDbContext()) 12 | { 13 | var tableAndSchema = context.GetTableAndSchemaName(typeof(User)); 14 | 15 | Assert.AreEqual("Users", tableAndSchema.TableName); 16 | Assert.AreEqual("dbo", tableAndSchema.Schema); 17 | } 18 | } 19 | 20 | [TestMethod] 21 | public void ShouldReturnTableAndSchemaNames() 22 | { 23 | using (var context = CreateSqliteDbContext()) 24 | { 25 | var tableAndSchemas = context.GetTableAndSchemaNames(typeof(Post)); 26 | 27 | Assert.IsNotNull(tableAndSchemas); 28 | Assert.AreEqual(1, tableAndSchemas.Length); 29 | Assert.AreEqual("Posts", tableAndSchemas[0].TableName); 30 | Assert.AreEqual("dbo", tableAndSchemas[0].Schema); 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("EntityFramework.CommonTools.Tests")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("EntityFramework.CommonTools.Tests")] 10 | [assembly: AssemblyCopyright("Copyright © Dmitry Panyushkin 2017")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("b0eb94e6-c524-472f-b276-c8b992bb5092")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Tests/TestDbContext.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Common; 2 | using System.Data.Entity; 3 | using System.Diagnostics; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace EntityFramework.CommonTools.Tests 8 | { 9 | public class TestDbContext : DbContext 10 | { 11 | public DbSet Roles { get; set; } 12 | public DbSet Users { get; set; } 13 | public DbSet Posts { get; set; } 14 | public DbSet Settings { get; set; } 15 | 16 | public DbSet TransactionLogs { get; set; } 17 | 18 | public TestDbContext(DbConnection connection) 19 | : base(connection, false) 20 | { 21 | Database.Log = s => Debug.WriteLine(s); 22 | Database.SetInitializer(null); 23 | } 24 | 25 | protected override void OnModelCreating(DbModelBuilder modelBuilder) 26 | { 27 | modelBuilder.UseTransactionLog(); 28 | } 29 | 30 | public override int SaveChanges() 31 | { 32 | using (this.WithChangeTrackingOnce()) 33 | { 34 | this.UpdateTrackableEntities(); 35 | this.UpdateConcurrentEntities(); 36 | 37 | return this.SaveChangesWithTransactionLog(base.SaveChanges); 38 | } 39 | } 40 | 41 | public int SaveChanges(int editorUserId) 42 | { 43 | using (this.WithChangeTrackingOnce()) 44 | { 45 | this.UpdateAuditableEntities(editorUserId); 46 | this.UpdateTrackableEntities(); 47 | this.UpdateConcurrentEntities(); 48 | 49 | return this.SaveChangesWithTransactionLog(base.SaveChanges); 50 | } 51 | } 52 | 53 | public override Task SaveChangesAsync(CancellationToken cancellationToken) 54 | { 55 | using (this.WithChangeTrackingOnce()) 56 | { 57 | this.UpdateTrackableEntities(); 58 | this.UpdateConcurrentEntities(); 59 | 60 | return this.SaveChangesWithTransactionLogAsync(base.SaveChangesAsync, cancellationToken); 61 | } 62 | } 63 | 64 | public Task SaveChangesAsync(string editorUserId) 65 | { 66 | using (this.WithChangeTrackingOnce()) 67 | { 68 | this.UpdateAuditableEntities(editorUserId); 69 | this.UpdateTrackableEntities(); 70 | this.UpdateConcurrentEntities(); 71 | 72 | return this.SaveChangesWithTransactionLogAsync(base.SaveChangesAsync); 73 | } 74 | } 75 | 76 | public void OriginalSaveChanges() 77 | { 78 | base.SaveChanges(); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Tests/TestEntities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | using System.Runtime.Serialization; 6 | 7 | namespace EntityFramework.CommonTools.Tests 8 | { 9 | public abstract class Entity 10 | { 11 | public int Id { get; set; } 12 | } 13 | 14 | public class Role : Entity, IConcurrencyCheckable, ITransactionLoggable 15 | { 16 | public string Name { get; set; } 17 | 18 | [ConcurrencyCheck] 19 | public Guid RowVersion { get; set; } 20 | } 21 | 22 | public class User : Entity, IFullTrackable, ITransactionLoggable 23 | { 24 | public string Login { get; set; } 25 | 26 | [Column("UserContacts")] 27 | public string Contacts { get; set; } 28 | 29 | public bool IsDeleted { get; set; } 30 | public DateTime CreatedUtc { get; set; } 31 | public DateTime? UpdatedUtc { get; set; } 32 | public DateTime? DeletedUtc { get; set; } 33 | 34 | [InverseProperty(nameof(Post.Author))] 35 | public virtual ICollection Posts { get; set; } = new HashSet(); 36 | } 37 | 38 | public class Post : Entity, IFullAuditable, IConcurrencyCheckable, ITransactionLoggable 39 | { 40 | public string Title { get; set; } 41 | public string Content { get; set; } 42 | 43 | JsonField> _tags = new HashSet(); 44 | 45 | public bool ShouldSerializeTagsJson() => false; 46 | 47 | public string TagsJson 48 | { 49 | get { return _tags.Json; } 50 | set { _tags.Json = value; } 51 | } 52 | 53 | public ICollection Tags 54 | { 55 | get { return _tags.Object; } 56 | set { _tags.Object = value; } 57 | } 58 | 59 | public bool IsDeleted { get; set; } 60 | public int CreatorUserId { get; set; } 61 | public DateTime CreatedUtc { get; set; } 62 | public int? UpdaterUserId { get; set; } 63 | public DateTime? UpdatedUtc { get; set; } 64 | public int? DeleterUserId { get; set; } 65 | public DateTime? DeletedUtc { get; set; } 66 | 67 | [ConcurrencyCheck] 68 | public Guid RowVersion { get; set; } 69 | 70 | [ForeignKey(nameof(CreatorUserId))] 71 | public virtual User Author { get; set; } 72 | } 73 | 74 | [Table("Settings")] 75 | public class Settings : IFullAuditable, IConcurrencyCheckable 76 | { 77 | [Key] 78 | public string Key { get; set; } 79 | 80 | JsonField _value; 81 | 82 | [Column("Value"), IgnoreDataMember] 83 | public string ValueJson 84 | { 85 | get { return _value.Json; } 86 | set { _value.Json = value; } 87 | } 88 | 89 | public dynamic Value 90 | { 91 | get { return _value.Object; } 92 | set { _value.Object = value; } 93 | } 94 | 95 | public bool IsDeleted { get; set; } 96 | public string CreatorUserId { get; set; } 97 | public DateTime CreatedUtc { get; set; } 98 | public string UpdaterUserId { get; set; } 99 | public DateTime? UpdatedUtc { get; set; } 100 | public string DeleterUserId { get; set; } 101 | public DateTime? DeletedUtc { get; set; } 102 | 103 | [ConcurrencyCheck] 104 | [DatabaseGenerated(DatabaseGeneratedOption.Computed)] 105 | public long RowVersion { get; set; } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Tests/TestInitializer.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Common; 2 | using System.Data.SQLite; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | namespace EntityFramework.CommonTools.Tests 6 | { 7 | [TestClass] 8 | public abstract class TestInitializer 9 | { 10 | private DbConnection _connection; 11 | 12 | [TestInitialize] 13 | public void TestInitialize() 14 | { 15 | _connection = new SQLiteConnection("Data Source=:memory:;Version=3;New=True;"); 16 | 17 | _connection.Open(); 18 | 19 | using (var context = CreateSqliteDbContext()) 20 | { 21 | context.Database.ExecuteSqlCommand(@" 22 | CREATE TABLE _TransactionLog ( 23 | Id INTEGER PRIMARY KEY AUTOINCREMENT, 24 | TransactionId BLOB, 25 | CreatedUtc DATETIME, 26 | Operation TEXT, 27 | Schema TEXT, 28 | TableName TEXT, 29 | EntityType TEXT, 30 | EntityJson TEXT 31 | ); 32 | 33 | CREATE TABLE Roles ( 34 | Id INTEGER PRIMARY KEY AUTOINCREMENT, 35 | Name TEXT, 36 | RowVersion TEXT 37 | ); 38 | 39 | CREATE TABLE Users ( 40 | Id INTEGER PRIMARY KEY AUTOINCREMENT, 41 | Login TEXT, 42 | UserContacts TEXT, 43 | 44 | IsDeleted BOOLEAN, 45 | CreatedUtc DATETIME, 46 | UpdatedUtc DATETIME, 47 | DeletedUtc DATETIME 48 | ); 49 | 50 | CREATE TABLE Posts ( 51 | Id INTEGER PRIMARY KEY AUTOINCREMENT, 52 | Title TEXT, 53 | Content TEXT, 54 | TagsJson TEXT, 55 | 56 | IsDeleted BOOLEAN, 57 | CreatedUtc DATETIME, 58 | CreatorUserId INTEGER, 59 | UpdatedUtc DATETIME, 60 | UpdaterUserId INTEGER, 61 | DeletedUtc DATETIME, 62 | DeleterUserId INTEGER, 63 | 64 | RowVersion TEXT 65 | ); 66 | 67 | CREATE TABLE Settings ( 68 | Key TEXT PRIMARY KEY, 69 | Value TEXT, 70 | 71 | IsDeleted BOOLEAN, 72 | CreatedUtc DATETIME, 73 | CreatorUserId TEXT, 74 | UpdatedUtc DATETIME, 75 | UpdaterUserId TEXT, 76 | DeletedUtc DATETIME, 77 | DeleterUserId TEXT, 78 | 79 | RowVersion INTEGER DEFAULT 0 80 | ); 81 | 82 | CREATE TRIGGER TRG_Settings_UPD 83 | AFTER UPDATE ON Settings 84 | WHEN old.RowVersion = new.RowVersion 85 | BEGIN 86 | UPDATE Settings 87 | SET RowVersion = RowVersion + 1; 88 | END;"); 89 | } 90 | } 91 | 92 | protected TestDbContext CreateInMemoryDbContext() 93 | { 94 | return CreateSqliteDbContext(); 95 | } 96 | 97 | protected TestDbContext CreateSqliteDbContext() 98 | { 99 | return new TestDbContext(_connection); 100 | } 101 | 102 | [TestCleanup] 103 | public void TestCleanup() 104 | { 105 | _connection.Close(); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Tests/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 |
5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.Tests/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26430.15 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EntityFramework.CommonTools", "EntityFramework.CommonTools\EntityFramework.CommonTools.csproj", "{1760A172-08A0-4232-B507-55E08971E87D}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.CommonTools", "EFCore.CommonTools\EntityFrameworkCore.CommonTools.csproj", "{4962545A-A94C-41A9-8C04-B9432F9A9058}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EntityFramework.CommonTools.Tests", "EntityFramework.CommonTools.Tests\EntityFramework.CommonTools.Tests.csproj", "{B0EB94E6-C524-472F-B276-C8B992BB5092}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.CommonTools.Tests", "EFCore.CommonTools.Tests\EntityFrameworkCore.CommonTools.Tests.csproj", "{3496C87F-E595-44F3-AB3C-E678A38DA950}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EntityFramework.CommonTools.Benchmarks", "EntityFramework.CommonTools.Benchmarks\EntityFramework.CommonTools.Benchmarks.csproj", "{01646964-497E-43A0-897C-267A3D04F429}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EntityFrameworkCore.CommonTools.Benchmarks", "EFCore.CommonTools.Benchmarks\EntityFrameworkCore.CommonTools.Benchmarks.csproj", "{F2C1ED95-5CB7-4125-B244-3E1AE983B96E}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Release|Any CPU = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {1760A172-08A0-4232-B507-55E08971E87D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {1760A172-08A0-4232-B507-55E08971E87D}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {1760A172-08A0-4232-B507-55E08971E87D}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {1760A172-08A0-4232-B507-55E08971E87D}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {4962545A-A94C-41A9-8C04-B9432F9A9058}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {4962545A-A94C-41A9-8C04-B9432F9A9058}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {4962545A-A94C-41A9-8C04-B9432F9A9058}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {4962545A-A94C-41A9-8C04-B9432F9A9058}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {B0EB94E6-C524-472F-B276-C8B992BB5092}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {B0EB94E6-C524-472F-B276-C8B992BB5092}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {B0EB94E6-C524-472F-B276-C8B992BB5092}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {B0EB94E6-C524-472F-B276-C8B992BB5092}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {3496C87F-E595-44F3-AB3C-E678A38DA950}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {3496C87F-E595-44F3-AB3C-E678A38DA950}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {3496C87F-E595-44F3-AB3C-E678A38DA950}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {3496C87F-E595-44F3-AB3C-E678A38DA950}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {01646964-497E-43A0-897C-267A3D04F429}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {01646964-497E-43A0-897C-267A3D04F429}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {01646964-497E-43A0-897C-267A3D04F429}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {01646964-497E-43A0-897C-267A3D04F429}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {F2C1ED95-5CB7-4125-B244-3E1AE983B96E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {F2C1ED95-5CB7-4125-B244-3E1AE983B96E}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {F2C1ED95-5CB7-4125-B244-3E1AE983B96E}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {F2C1ED95-5CB7-4125-B244-3E1AE983B96E}.Release|Any CPU.Build.0 = Release|Any CPU 48 | EndGlobalSection 49 | GlobalSection(SolutionProperties) = preSolution 50 | HideSolutionNode = FALSE 51 | EndGlobalSection 52 | EndGlobal 53 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools/EntityFramework.CommonTools.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Release 6 | AnyCPU 7 | {1760A172-08A0-4232-B507-55E08971E87D} 8 | Library 9 | Properties 10 | EntityFramework.CommonTools 11 | EntityFramework.CommonTools 12 | v4.5 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | TRACE;DEBUG;EF_6 22 | prompt 23 | 4 24 | 1591 25 | bin\Debug\EntityFramework.CommonTools.xml 26 | 27 | 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE;EF_6 32 | prompt 33 | 4 34 | bin\Release\EntityFramework.CommonTools.xml 35 | 1591 36 | 37 | 38 | 39 | ..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll 40 | 41 | 42 | ..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll 43 | 44 | 45 | ..\packages\Jil.2.15.4\lib\net45\Jil.dll 46 | 47 | 48 | ..\packages\Sigil.4.7.0\lib\net45\Sigil.dll 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | Auditing\%(RecursiveDir)%(Filename)%(Extension) 58 | 59 | 60 | Concurrency\%(RecursiveDir)%(Filename)%(Extension) 61 | 62 | 63 | Expression\%(RecursiveDir)%(Filename)%(Extension) 64 | 65 | 66 | Json\%(RecursiveDir)%(Filename)%(Extension) 67 | 68 | 69 | Querying\%(RecursiveDir)%(Filename)%(Extension) 70 | 71 | 72 | Specification\%(RecursiveDir)%(Filename)%(Extension) 73 | 74 | 75 | TransactionLog\%(RecursiveDir)%(Filename)%(Extension) 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools/EntityFramework.CommonTools.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EntityFramework.CommonTools 5 | 2.0.2 6 | Auditing, Concurrency Checks, JSON properties and Transaction Logs for EntityFramework 7 | An extension for EntityFramework that provides Auditing, Concurrency Checks, storing complex types as JSON and storing history of all changes from DbContext to Transaction Log. 8 | Dmitry Panyushkin 9 | gnaeus 10 | https://github.com/gnaeus/EntityFramework.CommonTools 11 | https://github.com/gnaeus/EntityFramework.CommonTools/blob/master/LICENSE 12 | https://raw.githubusercontent.com/gnaeus/EntityFramework.CommonTools/master/icon.png 13 | false 14 | context.Entry(entity).State = EntityState.Modified does not reset CreatedUtc and CreatorUserId 15 | Copyright © Dmitry Panyushkin 2017 16 | EF EntityFramework Entity Framework ChangeTracking Change Tracking Auditing Audit TransactionLog Transaction Log ComplexType Complex Type JSON 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools/Extensions/ChangeTrackingExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Entity; 3 | using System.Data.Entity.Infrastructure; 4 | 5 | namespace EntityFramework.CommonTools 6 | { 7 | public static partial class DbContextExtensions 8 | { 9 | /// 10 | /// Disposable region where AutoDetectChanges is disabled. 11 | /// 12 | public static IDisposable WithoutChangeTracking(this DbContext dbContext) 13 | { 14 | return new AutoDetectChangesContext(dbContext.Configuration); 15 | } 16 | 17 | /// 18 | /// Run once and return 19 | /// disposable region where AutoDetectChanges is disabled. 20 | /// 21 | public static IDisposable WithChangeTrackingOnce(this DbContext dbContext) 22 | { 23 | IDisposable result = dbContext.WithoutChangeTracking(); 24 | 25 | dbContext.ChangeTracker.DetectChanges(); 26 | 27 | return result; 28 | } 29 | 30 | private struct AutoDetectChangesContext : IDisposable 31 | { 32 | private readonly DbContextConfiguration _configuration; 33 | private readonly bool _autoDetectChangesEnabled; 34 | 35 | public AutoDetectChangesContext(DbContextConfiguration configuration) 36 | { 37 | _configuration = configuration; 38 | _autoDetectChangesEnabled = _configuration.AutoDetectChangesEnabled; 39 | _configuration.AutoDetectChangesEnabled = false; 40 | } 41 | 42 | public void Dispose() 43 | { 44 | _configuration.AutoDetectChangesEnabled = _autoDetectChangesEnabled; 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools/Extensions/README.md: -------------------------------------------------------------------------------- 1 | ## DbContext Extensions (EF 6 only) 2 | 3 | __`static IDisposable WithoutChangeTracking(this DbContext dbContext)`__ 4 | Disposable token for `using(...)` statement where `DbContext.Configuration.AutoDetectChanges` is disabled. 5 | 6 | ```cs 7 | // here AutoDetectChanges is enabled 8 | using (dbContext.WithoutChangeTracking()) 9 | { 10 | // inside this block AutoDetectChanges is disabled 11 | } 12 | // here AutoDetectChanges is enabled again 13 | ``` 14 | 15 |
16 | 17 | __`static IDisposable WithChangeTrackingOnce(this DbContext dbContext)`__ 18 | Run `DbChangeTracker.DetectChanges()` once and return disposable token for `using(...)` statement 19 | where `DbContext.Configuration.AutoDetectChanges` is disabled. 20 | 21 | ```cs 22 | // here AutoDetectChanges is enabled 23 | using (dbContext.WithChangeTrackingOnce()) 24 | { 25 | // inside this block AutoDetectChanges is disabled 26 | } 27 | // here AutoDetectChanges is enabled again 28 | ``` 29 | 30 |
31 | 32 | __`static TableAndSchema GetTableAndSchemaName(this DbContext context, Type entityType)`__ 33 | Get corresponding table name and schema by `entityType`. 34 | 35 | __`static TableAndSchema[] GetTableAndSchemaNames(this DbContext context, Type entityType)`__ 36 | Get corresponding table name and schema by `entityType`. 37 | Use it if entity is splitted between multiple tables. 38 | 39 | ```cs 40 | struct TableAndSchema 41 | { 42 | public string TableName; 43 | public string Schema; 44 | } 45 | ``` 46 | 47 |
48 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools/Extensions/TableNameExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Data; 5 | using System.Data.Entity; 6 | using System.Data.Entity.Core.Metadata.Edm; 7 | using System.Data.Entity.Core.Mapping; 8 | using System.Data.Entity.Infrastructure; 9 | using System.Linq; 10 | 11 | namespace EntityFramework.CommonTools 12 | { 13 | public struct TableAndSchema 14 | { 15 | public string TableName; 16 | public string Schema; 17 | 18 | public TableAndSchema(string table, string schema) 19 | { 20 | TableName = table; 21 | Schema = schema; 22 | } 23 | 24 | public void Deconstruct(out string table, out string schema) 25 | { 26 | table = TableName; 27 | schema = Schema; 28 | } 29 | } 30 | 31 | public static partial class DbContextExtensions 32 | { 33 | /// 34 | /// Get corresponding table name and schema by 35 | /// 36 | public static TableAndSchema GetTableAndSchemaName(this DbContext context, Type entityType) 37 | { 38 | return context.GetTableAndSchemaNames(entityType).Single(); 39 | } 40 | 41 | /// 42 | /// Get corresponding table name and schema by . 43 | /// Use it if entity is splitted between multiple tables. 44 | /// 45 | public static TableAndSchema[] GetTableAndSchemaNames(this DbContext context, Type entityType) 46 | { 47 | return _tableNames.GetOrAdd(new ContextEntityType(context.GetType(), entityType), _ => 48 | { 49 | return GetTableAndSchemaNames(entityType, context).ToArray(); 50 | }); 51 | } 52 | 53 | private struct ContextEntityType 54 | { 55 | public Type ContextType; 56 | public Type EntityType; 57 | 58 | public ContextEntityType(Type contextType, Type entityType) 59 | { 60 | ContextType = contextType; 61 | EntityType = entityType; 62 | } 63 | 64 | public override int GetHashCode() 65 | { 66 | return ContextType.GetHashCode() ^ EntityType.GetHashCode(); 67 | } 68 | } 69 | 70 | private static readonly ConcurrentDictionary _tableNames 71 | = new ConcurrentDictionary(); 72 | 73 | /// 74 | /// https://romiller.com/2014/04/08/ef6-1-mapping-between-types-tables/ 75 | /// 76 | private static IEnumerable GetTableAndSchemaNames(Type type, DbContext context) 77 | { 78 | var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace; 79 | 80 | // Get the part of the model that contains info about the actual CLR types 81 | var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace)); 82 | 83 | // Get the entity type from the model that maps to the CLR type 84 | var entityType = metadata 85 | .GetItems(DataSpace.OSpace) 86 | .Single(e => objectItemCollection.GetClrType(e) == type); 87 | 88 | // Get the entity set that uses this entity type 89 | var entitySet = metadata 90 | .GetItems(DataSpace.CSpace) 91 | .Single() 92 | .EntitySets 93 | .Single(s => s.ElementType.Name == entityType.Name); 94 | 95 | // Find the mapping between conceptual and storage model for this entity set 96 | var mapping = metadata.GetItems(DataSpace.CSSpace) 97 | .Single() 98 | .EntitySetMappings 99 | .Single(s => s.EntitySet == entitySet); 100 | 101 | // Find the storage entity sets (tables) that the entity is mapped 102 | var tables = mapping 103 | .EntityTypeMappings.Single() 104 | .Fragments; 105 | 106 | // Return the table name from the storage entity set 107 | return tables.Select(f => new TableAndSchema( 108 | (string)f.StoreEntitySet.MetadataProperties["Table"].Value ?? f.StoreEntitySet.Name, 109 | (string)f.StoreEntitySet.MetadataProperties["Schema"].Value ?? f.StoreEntitySet.Schema)); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("EntityFramework.CommonTools")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("EntityFramework.CommonTools")] 13 | [assembly: AssemblyCopyright("Copyright © Dmitry Panyushkin 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("1760a172-08a0-4232-b507-55e08971e87d")] 24 | 25 | [assembly: InternalsVisibleTo("EntityFramework.CommonTools.Tests")] 26 | 27 | // Version information for an assembly consists of the following four values: 28 | // 29 | // Major Version 30 | // Minor Version 31 | // Build Number 32 | // Revision 33 | // 34 | // You can specify all the values or you can default the Build and Revision Numbers 35 | // by using the '*' as shown below: 36 | // [assembly: AssemblyVersion("1.0.*")] 37 | [assembly: AssemblyVersion("1.0.0.0")] 38 | [assembly: AssemblyFileVersion("1.0.0.0")] 39 | -------------------------------------------------------------------------------- /EntityFramework.CommonTools/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Dmitry Panyushkin 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 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 2.0.2.{build} 2 | 3 | image: Visual Studio 2017 4 | 5 | before_build: 6 | - nuget restore 7 | 8 | test_script: 9 | - dotnet test --no-build .\EFCore.CommonTools.Tests\EntityFrameworkCore.CommonTools.Tests.csproj /p:CollectCoverage=true /p:CoverletOutputFormat=opencover 10 | - dotnet test --no-build .\EntityFramework.CommonTools.Tests\EntityFramework.CommonTools.Tests.csproj 11 | 12 | after_test: 13 | - ps: | 14 | $env:PATH = 'C:\msys64\usr\bin;' + $env:PATH 15 | Invoke-WebRequest -Uri 'https://codecov.io/bash' -OutFile codecov.sh 16 | bash codecov.sh -f "EFCore.CommonTools.Tests/coverage.xml" -t 5a158edf-3f15-40d8-92d7-3b3dc67d079b 17 | 18 | cache: 19 | - '%USERPROFILE%\.nuget\packages' 20 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gnaeus/EntityFramework.CommonTools/3ea1bc66255a493631fd73da6fd7617c029d1bdf/icon.png --------------------------------------------------------------------------------