private static Task EfCoreFivePointZeroDemo_SimpleLoggingAsync(ITestDbContext dbContext) { ConsoleLoggingHelper.WriteTestSeparator(nameof(EfCoreFivePointZeroDemo_SimpleLoggingAsync)); var generatedSql = dbContext.Documents .Where(d => !d.IsDeleted) .ToQueryString(); Console.WriteLine(generatedSql); return(Task.CompletedTask); }
public static async Task FirstOrNotFoundAsync_EntityDoesNotExist_ThrowNotFoundException(TestDbContext dbContext) { try { var order = await dbContext.SettlementOrders .Include(o => o.IndividualConsumers) .Include(o => o.OrganisationalConsumers) .FirstOrNotFoundAsync(o => o.Id == 999999, nameof(SettlementOrder), 999999, CancellationToken.None); } catch (NotFoundException) { ConsoleLoggingHelper.WriteTestResult(nameof(FirstOrNotFoundAsync_EntityDoesNotExist_ThrowNotFoundException), true); } catch (Exception) { ConsoleLoggingHelper.WriteTestResult(nameof(FirstOrNotFoundAsync_EntityDoesNotExist_ThrowNotFoundException), false); } }
public static async Task FirstOrDefaultAsync_EntityDoesNotExist_ReturnDefault(TestDbContext dbContext) { try { var order = await dbContext.SettlementOrders .Include(o => o.IndividualConsumers) .Include(o => o.OrganisationalConsumers) .FirstOrDefaultAsync(o => o.Id == 999999); if (order == default) { ConsoleLoggingHelper.WriteTestResult(nameof(FirstOrDefaultAsync_EntityDoesNotExist_ReturnDefault), true); } } catch (Exception) { ConsoleLoggingHelper.WriteTestResult(nameof(FirstOrNotFoundAsync_EntityDoesNotExist_ThrowNotFoundException), false); } }
public static async Task NavigationProperty_EntityNotIncluded_ThrowException(TestDbContext dbContext) { try { var order = await dbContext.SettlementOrders .FirstOrNotFoundAsync(o => o.Id == 1, nameof(SettlementOrder), 1, CancellationToken.None); var consumersCount = order.IndividualConsumers.Count; if (consumersCount >= 0) { ConsoleLoggingHelper.WriteTestResult(nameof(NavigationProperty_EntityNotIncluded_ThrowException), false); } } catch (Exception) { ConsoleLoggingHelper.WriteTestResult(nameof(NavigationProperty_EntityNotIncluded_ThrowException), true); } }
private static void RecordTypesDemo() { ConsoleLoggingHelper.WriteTestSeparator(nameof(RecordTypesDemo)); var personClassA = new PersonClass { Name = "Bob" }; var personClassB = new PersonClass { Name = "Bob" }; Console.WriteLine(personClassA == personClassB ? "PersonClassA is equal to PersonClassB" : "PersonClassA is NOT equal to PersonClassB"); var personRecordA = new PersonRecord { Name = "Bob" }; //newRecord.MyProperty = 47; var personRecordB = new PersonRecord { Name = "Bob" }; Console.WriteLine(personRecordA == personRecordB ? "PersonRecordA is equal to PersonRecordB" : "PersonRecordA is NOT equal to PersonRecordB"); }
public static async Task FirstOrNotFoundAsync_EntityExists_ReturnEntity(TestDbContext dbContext) { try { var order = await dbContext.SettlementOrders .Include(o => o.IndividualConsumers) .Include(o => o.OrganisationalConsumers) .FirstOrNotFoundAsync(o => o.Id == 1, nameof(SettlementOrder), 1, CancellationToken.None); if (order != null) { ConsoleLoggingHelper.WriteTestResult(nameof(FirstOrNotFoundAsync_EntityExists_ReturnEntity), true); } else { ConsoleLoggingHelper.WriteTestResult(nameof(FirstOrNotFoundAsync_EntityExists_ReturnEntity), false); } } catch (Exception) { ConsoleLoggingHelper.WriteTestResult(nameof(FirstOrNotFoundAsync_EntityExists_ReturnEntity), false); } }
public static async Task OwnedEntity_OwningEntityExists_NoExceptionThrown(TestDbContext dbContext) { try { var order = await dbContext.SettlementOrders .FirstOrNotFoundAsync(o => o.Id == 1, nameof(SettlementOrder), 1, CancellationToken.None); var address = order.ForwardingAddress; if (address.State == null) { ConsoleLoggingHelper.WriteTestResult(nameof(OwnedEntity_OwningEntityExists_NoExceptionThrown), false); } else { ConsoleLoggingHelper.WriteTestResult(nameof(OwnedEntity_OwningEntityExists_NoExceptionThrown), true); } } catch (Exception) { ConsoleLoggingHelper.WriteTestResult(nameof(OwnedEntity_OwningEntityExists_NoExceptionThrown), false); } }
private static async Task EfCoreDemo_RestrictedClientEvaluation(ITestDbContext dbContext) { var expectedExceptionThrown = false; var unexpectedExceptionThrown = false; try { // This will fail because EF can't translate 'HasCorrectIdentifierForDemo(o.Identifier)' into SQL. var result = await dbContext.SettlementOrders.AsNoTracking() .Where(o => o.Identifier.Contains("EF") && HasCorrectIdentifierForDemo(o.Identifier)) .Select(o => o.Id) .ToListAsync(); } catch (InvalidOperationException translationFailedException) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine("----------------------------------------"); Console.WriteLine("-- EfCoreDemo_RestrictedClientEvaluation"); Console.WriteLine(); Console.WriteLine(translationFailedException.Message); Console.WriteLine(); expectedExceptionThrown = true; } // If we really need to get this to evaluate on the Client side, then we need to instruct EF to bring // the records into memory for further processing, like so: // ---------------------------------------- // -- Synchronously try { var results = dbContext.SettlementOrders.AsNoTracking() .Where(o => o.Identifier.Contains("Ef")) // <-- Processed on the Server (SQL) - i.e. Translates to SQL .AsEnumerable() // <-- This will force the records to load into memory after the SQL component is finished. .Where(o => HasCorrectIdentifierForDemo(o.Identifier)) // <-- Processed Client Side (C#) .Select(o => o.Id) .ToList(); // Yes, this is NOT Async. And that's by design. if (results.Count != 1) { throw new Exception("Invalid Data - EfCoreDemo_RestrictedClientEvaluation"); } } catch (Exception) { unexpectedExceptionThrown = true; } // ---------------------------------------- // -- Asynchronously try { var results = new List <int>(); var ordersQuery = dbContext.SettlementOrders.AsNoTracking() .Where(o => o.Identifier.Contains("Ef")); // <-- Processed on the Server (SQL) - i.e. Translates to SQL await foreach (var order in ordersQuery.AsAsyncEnumerable()) { if (HasCorrectIdentifierForDemo(order.Identifier)) { results.Add(order.Id); } } if (results.Count != 1) { throw new Exception("Invalid Data - EfCoreDemo_RestrictedClientEvaluation"); } } catch (Exception) { unexpectedExceptionThrown = true; } if (unexpectedExceptionThrown || !expectedExceptionThrown) { ConsoleLoggingHelper.WriteTestResult(nameof(EfCoreDemo_RestrictedClientEvaluation), passed: false); } else { ConsoleLoggingHelper.WriteTestResult(nameof(EfCoreDemo_RestrictedClientEvaluation), passed: true); } }
private static async Task EfCoreDemo_ReferenceStitchingChanges(IServiceProvider serviceProvider) { var expectedExceptionThrown = false; var unexpectedExceptionThrown = false; // ---------------------------------------- // -- Incorrect Method try { using var scope = serviceProvider.CreateScope(); using var dbContext = scope.ServiceProvider.GetRequiredService <ITestDbContext>(); var order = new SettlementOrder(); var document = new Document { OrderId = order.Id, FilePath = "EfCoreDemo_ReferenceStitchingChanges_Incorrect" }; dbContext.Documents.Add(document); dbContext.SettlementOrders.Add(order); await dbContext.SaveChangesAsync(CancellationToken.None); } catch (Exception) { expectedExceptionThrown = true; } // ---------------------------------------- // -- Correct Method try { using var scope = serviceProvider.CreateScope(); using var dbContext = scope.ServiceProvider.GetRequiredService <ITestDbContext>(); var order = new SettlementOrder(); var document = new Document { Order = order, FilePath = "EfCoreDemo_ReferenceStitchingChanges_Success" }; dbContext.Documents.Add(document); dbContext.SettlementOrders.Add(order); await dbContext.SaveChangesAsync(CancellationToken.None); } catch (Exception) { unexpectedExceptionThrown = true; } if (unexpectedExceptionThrown || !expectedExceptionThrown) { ConsoleLoggingHelper.WriteTestResult(nameof(EfCoreDemo_ReferenceStitchingChanges), passed: false); } else { ConsoleLoggingHelper.WriteTestResult(nameof(EfCoreDemo_ReferenceStitchingChanges), passed: true); } }
private static async Task EfCoreFivePointZeroDemo_FilteredIncludeAsync(ITestDbContext dbContext) { ConsoleLoggingHelper.WriteTestSeparator(nameof(EfCoreFivePointZeroDemo_FilteredIncludeAsync)); /* * INSERT INTO [dbo].[Orders] ([OrderType], [Identifier]) * VALUES (0, 'EfCore5Demo') * ; * DECLARE @OrderId INT = SCOPE_IDENTITY(); * * INSERT INTO [dbo].[Consumers] ([OrderId], [IsOrganisation], [Street], [Suburb], [State], [OrganisationName], [IndividualName], [CompanyType]) * VALUES * (@OrderId, 0, 'street1', 'suburb1', 'state1', NULL, 'First Individual', NULL) * ,(@OrderId, 0, 'street2', 'suburb2', 'state2', NULL, 'Second Individual', NULL) * ,(@OrderId, 1, 'street3', 'suburb3', 'state3', 'First Organisation', NULL, 'Company ') * ,(@OrderId, 1, 'street4', 'suburb3', 'state4', 'Second Organisation', NULL, 'SoleTrader') * ,(@OrderId, 1, 'street5', 'suburb5', 'state5', 'Third Organisation', NULL, 'Company ') * ; * * INSERT INTO [dbo].[Documents] ([OrderId], [FilePath], [IsDeleted]) * VALUES * (@OrderId, 'FilePath_1_NotDeleted', 0) * ,(@OrderId, 'FilePath_2_Deleted', 1) * ,(@OrderId, 'FilePath_3_NotDeleted', 0) * ; */ // ---------------------------------------- // -- Previous Method var previousGetOrderQuery = dbContext.SettlementOrders.AsNoTracking() .Include(o => o.Documents) .Include(o => o.IndividualConsumers) .Include(o => o.OrganisationalConsumers) .Where(o => o.Identifier == EfCoreFivePointZeroOrderIdentifier); var previousGetOrderQueryString = previousGetOrderQuery.ToQueryString(); Console.WriteLine("Previous Method SQL:"); Console.WriteLine(previousGetOrderQueryString); var orderFromPreviousQuery = await previousGetOrderQuery.FirstAsync(); // ---------------------------------------- // -- Filtered Includes Method var newGetOrderQuery = dbContext.SettlementOrders.AsNoTracking() .Include(o => o.Documents.Where(d => !d.IsDeleted)) .Include(o => o.IndividualConsumers.Where(ic => ic.IndividualName == "Second Individual")) .Include(o => o.OrganisationalConsumers.Where(oc => oc.CompanyType == CompanyType.Company)) .Where(o => o.Identifier == EfCoreFivePointZeroOrderIdentifier); var newGetOrderQueryString = newGetOrderQuery.ToQueryString(); Console.WriteLine(); Console.WriteLine("Filtered Includes SQL:"); Console.WriteLine(newGetOrderQueryString); var orderFromNewQuery = await newGetOrderQuery.FirstAsync(); //var jsonSerializerOptions = new JsonSerializerOptions //{ // ReferenceHandler = ReferenceHandler.Preserve //}; //Console.WriteLine(JsonSerializer.Serialize(orderFromPreviousQuery, jsonSerializerOptions)); //Console.WriteLine(JsonSerializer.Serialize(newGetOrderQuery, jsonSerializerOptions)); }