From c019483cb9629b3231518c71b18709af457966a0 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sat, 2 Apr 2022 21:12:55 +0300 Subject: [PATCH] Some using declarations --- samples/core/DbContextPooling/Program.cs | 16 +-- samples/core/GetStarted/Program.cs | 51 ++++--- .../ConnectionResiliency/Program.cs | 136 +++++++++--------- .../NewInEFCore6/SqliteSamples.cs | 26 ++-- .../AuditingInterceptor.cs | 73 +++++----- samples/core/Modeling/EntityTypes/Program.cs | 24 ++-- .../Modeling/KeylessEntityTypes/Program.cs | 108 +++++++------- 7 files changed, 206 insertions(+), 228 deletions(-) diff --git a/samples/core/DbContextPooling/Program.cs b/samples/core/DbContextPooling/Program.cs index f62f222134..78f14a0002 100644 --- a/samples/core/DbContextPooling/Program.cs +++ b/samples/core/DbContextPooling/Program.cs @@ -77,16 +77,14 @@ await Task.WhenAll( private static void SetupDatabase(IServiceProvider serviceProvider) { - using (var serviceScope = serviceProvider.CreateScope()) - { - var context = serviceScope.ServiceProvider.GetService(); + using var serviceScope = serviceProvider.CreateScope(); + var context = serviceScope.ServiceProvider.GetService(); - if (context.Database.EnsureCreated()) - { - context.Blogs.Add(new Blog { Name = "The Dog Blog", Url = "http://sample.com/dogs" }); - context.Blogs.Add(new Blog { Name = "The Cat Blog", Url = "http://sample.com/cats" }); - context.SaveChanges(); - } + if (context.Database.EnsureCreated()) + { + context.Blogs.Add(new Blog { Name = "The Dog Blog", Url = "http://sample.com/dogs" }); + context.Blogs.Add(new Blog { Name = "The Cat Blog", Url = "http://sample.com/cats" }); + context.SaveChanges(); } } diff --git a/samples/core/GetStarted/Program.cs b/samples/core/GetStarted/Program.cs index 1882bcf775..597209a248 100644 --- a/samples/core/GetStarted/Program.cs +++ b/samples/core/GetStarted/Program.cs @@ -7,33 +7,32 @@ internal class Program { private static void Main() { - using (var db = new BloggingContext()) - { - // Note: This sample requires the database to be created before running. - Console.WriteLine($"Database path: {db.DbPath}."); - - // Create - Console.WriteLine("Inserting a new blog"); - db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" }); - db.SaveChanges(); + using var db = new BloggingContext(); - // Read - Console.WriteLine("Querying for a blog"); - var blog = db.Blogs - .OrderBy(b => b.BlogId) - .First(); + // Note: This sample requires the database to be created before running. + Console.WriteLine($"Database path: {db.DbPath}."); - // Update - Console.WriteLine("Updating the blog and adding a post"); - blog.Url = "https://devblogs.microsoft.com/dotnet"; - blog.Posts.Add( - new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" }); - db.SaveChanges(); + // Create + Console.WriteLine("Inserting a new blog"); + db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" }); + db.SaveChanges(); - // Delete - Console.WriteLine("Delete the blog"); - db.Remove(blog); - db.SaveChanges(); - } + // Read + Console.WriteLine("Querying for a blog"); + var blog = db.Blogs + .OrderBy(b => b.BlogId) + .First(); + + // Update + Console.WriteLine("Updating the blog and adding a post"); + blog.Url = "https://devblogs.microsoft.com/dotnet"; + blog.Posts.Add( + new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" }); + db.SaveChanges(); + + // Delete + Console.WriteLine("Delete the blog"); + db.Remove(blog); + db.SaveChanges(); } -} \ No newline at end of file +} diff --git a/samples/core/Miscellaneous/ConnectionResiliency/Program.cs b/samples/core/Miscellaneous/ConnectionResiliency/Program.cs index 0e7eb69e66..de75f7fc6b 100644 --- a/samples/core/Miscellaneous/ConnectionResiliency/Program.cs +++ b/samples/core/Miscellaneous/ConnectionResiliency/Program.cs @@ -27,101 +27,95 @@ public static void Main(string[] args) private static void ExecuteWithManualTransaction() { #region ManualTransaction - using (var db = new BloggingContext()) - { - var strategy = db.Database.CreateExecutionStrategy(); - - strategy.Execute( - () => - { - using (var context = new BloggingContext()) - { - using (var transaction = context.Database.BeginTransaction()) - { - context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); - context.SaveChanges(); - - context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" }); - context.SaveChanges(); - - transaction.Commit(); - } - } - }); - } + + using var db = new BloggingContext(); + var strategy = db.Database.CreateExecutionStrategy(); + + strategy.Execute( + () => + { + using var context = new BloggingContext(); + using var transaction = context.Database.BeginTransaction(); + + context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); + context.SaveChanges(); + + context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" }); + context.SaveChanges(); + + transaction.Commit(); + }); + #endregion } private static void ExecuteWithManualAmbientTransaction() { #region AmbientTransaction - using (var context1 = new BloggingContext()) - { - context1.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" }); - - var strategy = context1.Database.CreateExecutionStrategy(); - - strategy.Execute( - () => - { - using (var context2 = new BloggingContext()) - { - using (var transaction = new TransactionScope()) - { - context2.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); - context2.SaveChanges(); - - context1.SaveChanges(); - - transaction.Complete(); - } - } - }); - } + + using var context1 = new BloggingContext(); + context1.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" }); + + var strategy = context1.Database.CreateExecutionStrategy(); + + strategy.Execute( + () => + { + using var context2 = new BloggingContext(); + using var transaction = new TransactionScope(); + + context2.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); + context2.SaveChanges(); + + context1.SaveChanges(); + + transaction.Complete(); + }); + #endregion } private static void ExecuteInTransactionWithVerification() { #region Verification - using (var db = new BloggingContext()) - { - var strategy = db.Database.CreateExecutionStrategy(); - var blogToAdd = new Blog { Url = "http://blogs.msdn.com/dotnet" }; - db.Blogs.Add(blogToAdd); + using var db = new BloggingContext(); + var strategy = db.Database.CreateExecutionStrategy(); - strategy.ExecuteInTransaction( - db, - operation: context => { context.SaveChanges(acceptAllChangesOnSuccess: false); }, - verifySucceeded: context => context.Blogs.AsNoTracking().Any(b => b.BlogId == blogToAdd.BlogId)); + var blogToAdd = new Blog { Url = "http://blogs.msdn.com/dotnet" }; + db.Blogs.Add(blogToAdd); + + strategy.ExecuteInTransaction( + db, + operation: context => { context.SaveChanges(acceptAllChangesOnSuccess: false); }, + verifySucceeded: context => context.Blogs.AsNoTracking().Any(b => b.BlogId == blogToAdd.BlogId)); + + db.ChangeTracker.AcceptAllChanges(); - db.ChangeTracker.AcceptAllChanges(); - } #endregion } private static void ExecuteInTransactionWithTracking() { #region Tracking - using (var db = new BloggingContext()) - { - var strategy = db.Database.CreateExecutionStrategy(); - db.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); + using var db = new BloggingContext(); + var strategy = db.Database.CreateExecutionStrategy(); - var transaction = new TransactionRow { Id = Guid.NewGuid() }; - db.Transactions.Add(transaction); + db.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); - strategy.ExecuteInTransaction( - db, - operation: context => { context.SaveChanges(acceptAllChangesOnSuccess: false); }, - verifySucceeded: context => context.Transactions.AsNoTracking().Any(t => t.Id == transaction.Id)); + var transaction = new TransactionRow { Id = Guid.NewGuid() }; + db.Transactions.Add(transaction); + + strategy.ExecuteInTransaction( + db, + operation: context => { context.SaveChanges(acceptAllChangesOnSuccess: false); }, + verifySucceeded: context => context.Transactions.AsNoTracking().Any(t => t.Id == transaction.Id)); + + db.ChangeTracker.AcceptAllChanges(); + db.Transactions.Remove(transaction); + db.SaveChanges(); - db.ChangeTracker.AcceptAllChanges(); - db.Transactions.Remove(transaction); - db.SaveChanges(); - } #endregion } } @@ -156,4 +150,4 @@ public class Blog public class TransactionRow { public Guid Id { get; set; } -} \ No newline at end of file +} diff --git a/samples/core/Miscellaneous/NewInEFCore6/SqliteSamples.cs b/samples/core/Miscellaneous/NewInEFCore6/SqliteSamples.cs index a59146d109..228062f305 100644 --- a/samples/core/Miscellaneous/NewInEFCore6/SqliteSamples.cs +++ b/samples/core/Miscellaneous/NewInEFCore6/SqliteSamples.cs @@ -46,25 +46,23 @@ public static void DateOnly_and_TimeOnly() Helpers.RecreateCleanDatabase(); Helpers.PopulateDatabase(); + using var context = new UsersContext(); - using (var context = new UsersContext()) - { - #region DateOnlyQuery - var users = context.Users.Where(u => u.Birthday < new DateOnly(1900, 1, 1)).ToList(); - #endregion + #region DateOnlyQuery + var users = context.Users.Where(u => u.Birthday < new DateOnly(1900, 1, 1)).ToList(); + #endregion - Console.WriteLine(); + Console.WriteLine(); - foreach (var user in users) - { - Console.WriteLine($" Found '{user.Username}'"); - user.Birthday = new(user.Birthday.Year + 100, user.Birthday.Month, user.Birthday.Day); - } + foreach (var user in users) + { + Console.WriteLine($" Found '{user.Username}'"); + user.Birthday = new(user.Birthday.Year + 100, user.Birthday.Month, user.Birthday.Day); + } - Console.WriteLine(); + Console.WriteLine(); - context.SaveChanges(); - } + context.SaveChanges(); } private static void PerformUpdates() diff --git a/samples/core/Miscellaneous/SaveChangesInterception/AuditingInterceptor.cs b/samples/core/Miscellaneous/SaveChangesInterception/AuditingInterceptor.cs index c5f20bb174..f7c7c81267 100644 --- a/samples/core/Miscellaneous/SaveChangesInterception/AuditingInterceptor.cs +++ b/samples/core/Miscellaneous/SaveChangesInterception/AuditingInterceptor.cs @@ -24,11 +24,10 @@ public async ValueTask> SavingChangesAsync( { _audit = CreateAudit(eventData.Context); - using (var auditContext = new AuditContext(_connectionString)) - { - auditContext.Add(_audit); - await auditContext.SaveChangesAsync(); - } + using var auditContext = new AuditContext(_connectionString); + + auditContext.Add(_audit); + await auditContext.SaveChangesAsync(); return result; } @@ -39,11 +38,9 @@ public InterceptionResult SavingChanges( { _audit = CreateAudit(eventData.Context); - using (var auditContext = new AuditContext(_connectionString)) - { - auditContext.Add(_audit); - auditContext.SaveChanges(); - } + using var auditContext = new AuditContext(_connectionString); + auditContext.Add(_audit); + auditContext.SaveChanges(); return result; } @@ -52,14 +49,13 @@ public InterceptionResult SavingChanges( #region SavedChanges public int SavedChanges(SaveChangesCompletedEventData eventData, int result) { - using (var auditContext = new AuditContext(_connectionString)) - { - auditContext.Attach(_audit); - _audit.Succeeded = true; - _audit.EndTime = DateTime.UtcNow; + using var auditContext = new AuditContext(_connectionString); - auditContext.SaveChanges(); - } + auditContext.Attach(_audit); + _audit.Succeeded = true; + _audit.EndTime = DateTime.UtcNow; + + auditContext.SaveChanges(); return result; } @@ -69,14 +65,13 @@ public async ValueTask SavedChangesAsync( int result, CancellationToken cancellationToken = default) { - using (var auditContext = new AuditContext(_connectionString)) - { - auditContext.Attach(_audit); - _audit.Succeeded = true; - _audit.EndTime = DateTime.UtcNow; + using var auditContext = new AuditContext(_connectionString); - await auditContext.SaveChangesAsync(cancellationToken); - } + auditContext.Attach(_audit); + _audit.Succeeded = true; + _audit.EndTime = DateTime.UtcNow; + + await auditContext.SaveChangesAsync(cancellationToken); return result; } @@ -85,30 +80,28 @@ public async ValueTask SavedChangesAsync( #region SaveChangesFailed public void SaveChangesFailed(DbContextErrorEventData eventData) { - using (var auditContext = new AuditContext(_connectionString)) - { - auditContext.Attach(_audit); - _audit.Succeeded = false; - _audit.EndTime = DateTime.UtcNow; - _audit.ErrorMessage = eventData.Exception.Message; + using var auditContext = new AuditContext(_connectionString); - auditContext.SaveChanges(); - } + auditContext.Attach(_audit); + _audit.Succeeded = false; + _audit.EndTime = DateTime.UtcNow; + _audit.ErrorMessage = eventData.Exception.Message; + + auditContext.SaveChanges(); } public async Task SaveChangesFailedAsync( DbContextErrorEventData eventData, CancellationToken cancellationToken = default) { - using (var auditContext = new AuditContext(_connectionString)) - { - auditContext.Attach(_audit); - _audit.Succeeded = false; - _audit.EndTime = DateTime.UtcNow; - _audit.ErrorMessage = eventData.Exception.InnerException?.Message; + using var auditContext = new AuditContext(_connectionString); - await auditContext.SaveChangesAsync(cancellationToken); - } + auditContext.Attach(_audit); + _audit.Succeeded = false; + _audit.EndTime = DateTime.UtcNow; + _audit.ErrorMessage = eventData.Exception.InnerException?.Message; + + await auditContext.SaveChangesAsync(cancellationToken); } #endregion diff --git a/samples/core/Modeling/EntityTypes/Program.cs b/samples/core/Modeling/EntityTypes/Program.cs index 54144ad4f2..5981aa1def 100644 --- a/samples/core/Modeling/EntityTypes/Program.cs +++ b/samples/core/Modeling/EntityTypes/Program.cs @@ -7,13 +7,12 @@ internal class Program { private static void Main(string[] args) { - using (var context = new MyContextWithFunctionMapping()) - { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); + using var context = new MyContextWithFunctionMapping(); + context.Database.EnsureDeleted(); + context.Database.EnsureCreated(); - context.Database.ExecuteSqlRaw( - @"CREATE FUNCTION dbo.BlogsWithMultiplePosts() + context.Database.ExecuteSqlRaw( + @"CREATE FUNCTION dbo.BlogsWithMultiplePosts() RETURNS TABLE AS RETURN @@ -25,12 +24,11 @@ FROM Blogs AS b HAVING COUNT(p.BlogId) > 1 )"); - #region ToFunctionQuery - var query = from b in context.Set() - where b.PostCount > 3 - select new { b.Url, b.PostCount }; - #endregion - var result = query.ToList(); - } + #region ToFunctionQuery + var query = from b in context.Set() + where b.PostCount > 3 + select new { b.Url, b.PostCount }; + #endregion + var result = query.ToList(); } } \ No newline at end of file diff --git a/samples/core/Modeling/KeylessEntityTypes/Program.cs b/samples/core/Modeling/KeylessEntityTypes/Program.cs index 61c9a7a538..8563d0eea2 100644 --- a/samples/core/Modeling/KeylessEntityTypes/Program.cs +++ b/samples/core/Modeling/KeylessEntityTypes/Program.cs @@ -14,74 +14,72 @@ private static void Main() { SetupDatabase(); - using (var db = new BloggingContext()) + using var db = new BloggingContext(); + + #region Query + var postCounts = db.BlogPostCounts.ToList(); + + foreach (var postCount in postCounts) { - #region Query - var postCounts = db.BlogPostCounts.ToList(); - - foreach (var postCount in postCounts) - { - Console.WriteLine($"{postCount.BlogName} has {postCount.PostCount} posts."); - Console.WriteLine(); - } - #endregion + Console.WriteLine($"{postCount.BlogName} has {postCount.PostCount} posts."); + Console.WriteLine(); } + #endregion } private static void SetupDatabase() { - using (var db = new BloggingContext()) + using var db = new BloggingContext(); + + if (db.Database.EnsureCreated()) { - if (db.Database.EnsureCreated()) - { - db.Blogs.Add( - new Blog + db.Blogs.Add( + new Blog + { + Name = "Fish Blog", + Url = "http://sample.com/blogs/fish", + Posts = new List { - Name = "Fish Blog", - Url = "http://sample.com/blogs/fish", - Posts = new List - { - new Post { Title = "Fish care 101" }, - new Post { Title = "Caring for tropical fish" }, - new Post { Title = "Types of ornamental fish" } - } - }); - - db.Blogs.Add( - new Blog + new Post { Title = "Fish care 101" }, + new Post { Title = "Caring for tropical fish" }, + new Post { Title = "Types of ornamental fish" } + } + }); + + db.Blogs.Add( + new Blog + { + Name = "Cats Blog", + Url = "http://sample.com/blogs/cats", + Posts = new List { - Name = "Cats Blog", - Url = "http://sample.com/blogs/cats", - Posts = new List - { - new Post { Title = "Cat care 101" }, - new Post { Title = "Caring for tropical cats" }, - new Post { Title = "Types of ornamental cats" } - } - }); - - db.Blogs.Add( - new Blog + new Post { Title = "Cat care 101" }, + new Post { Title = "Caring for tropical cats" }, + new Post { Title = "Types of ornamental cats" } + } + }); + + db.Blogs.Add( + new Blog + { + Name = "Catfish Blog", + Url = "http://sample.com/blogs/catfish", + Posts = new List { - Name = "Catfish Blog", - Url = "http://sample.com/blogs/catfish", - Posts = new List - { - new Post { Title = "Catfish care 101" }, new Post { Title = "History of the catfish name" } - } - }); - - db.SaveChanges(); - - #region View - db.Database.ExecuteSqlRaw( - @"CREATE VIEW View_BlogPostCounts AS + new Post { Title = "Catfish care 101" }, new Post { Title = "History of the catfish name" } + } + }); + + db.SaveChanges(); + + #region View + db.Database.ExecuteSqlRaw( + @"CREATE VIEW View_BlogPostCounts AS SELECT b.Name, Count(p.PostId) as PostCount FROM Blogs b JOIN Posts p on p.BlogId = b.BlogId GROUP BY b.Name"); - #endregion - } + #endregion } } } @@ -146,4 +144,4 @@ public class BlogPostsCount public string BlogName { get; set; } public int PostCount { get; set; } } -#endregion \ No newline at end of file +#endregion