diff --git a/All.sln.DotSettings b/All.sln.DotSettings index d794c295092..880a655eacd 100644 --- a/All.sln.DotSettings +++ b/All.sln.DotSettings @@ -80,12 +80,14 @@ True False True - False + True True True CHOP_IF_LONG + True True True + CHOP_IF_LONG 140 True CHOP_ALWAYS @@ -167,10 +169,15 @@ Licensed under the Apache License, Version 2.0. See License.txt in the project r <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> - True - ..\EFCore.sln.DotSettings - True - 1 + + + True + C:\repos\EntityFrameworkCore\All.sln.DotSettings + + + + True + 2 DO_NOTHING True True @@ -187,13 +194,20 @@ Licensed under the Apache License, Version 2.0. See License.txt in the project r True True True + False + True True True True True + True True True True + False + True + False + True True True True diff --git a/EFCore.sln.DotSettings b/EFCore.sln.DotSettings deleted file mode 100644 index e7d45a2a845..00000000000 --- a/EFCore.sln.DotSettings +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/benchmark/EF.Benchmarks.Shared/Initialization/ColdStartSandbox.cs b/benchmark/EF.Benchmarks.Shared/Initialization/ColdStartSandbox.cs index 2a4b580e2a8..5b98d8004e7 100644 --- a/benchmark/EF.Benchmarks.Shared/Initialization/ColdStartSandbox.cs +++ b/benchmark/EF.Benchmarks.Shared/Initialization/ColdStartSandbox.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #if NET461 - using System; namespace Microsoft.EntityFrameworkCore.Benchmarks.Initialization diff --git a/benchmark/EF6.SqlServer.Benchmarks/Support/Program.cs b/benchmark/EF6.SqlServer.Benchmarks/Support/Program.cs index dfbc9c83601..e57a97c3a64 100644 --- a/benchmark/EF6.SqlServer.Benchmarks/Support/Program.cs +++ b/benchmark/EF6.SqlServer.Benchmarks/Support/Program.cs @@ -1,8 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - - // ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore.Benchmarks { diff --git a/benchmark/EFCore.SqlServer.Benchmarks/Support/Program.cs b/benchmark/EFCore.SqlServer.Benchmarks/Support/Program.cs index dfbc9c83601..e57a97c3a64 100644 --- a/benchmark/EFCore.SqlServer.Benchmarks/Support/Program.cs +++ b/benchmark/EFCore.SqlServer.Benchmarks/Support/Program.cs @@ -1,8 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - - // ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore.Benchmarks { diff --git a/benchmark/EFCore.Sqlite.Benchmarks/Support/Program.cs b/benchmark/EFCore.Sqlite.Benchmarks/Support/Program.cs index dfbc9c83601..e57a97c3a64 100644 --- a/benchmark/EFCore.Sqlite.Benchmarks/Support/Program.cs +++ b/benchmark/EFCore.Sqlite.Benchmarks/Support/Program.cs @@ -1,8 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - - // ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore.Benchmarks { diff --git a/src/EFCore.Cosmos/Extensions/CosmosEntityTypeExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosEntityTypeExtensions.cs index bde438fdea6..c3c16d3cb48 100644 --- a/src/EFCore.Cosmos/Extensions/CosmosEntityTypeExtensions.cs +++ b/src/EFCore.Cosmos/Extensions/CosmosEntityTypeExtensions.cs @@ -27,8 +27,8 @@ public static string GetContainer([NotNull] this IEntityType entityType) => private static string GetDefaultContainer(IEntityType entityType) => entityType.IsOwned() - ? null - : entityType.Model.GetDefaultContainer() + ? null + : entityType.Model.GetDefaultContainer() ?? entityType.ShortName(); /// diff --git a/src/EFCore.Cosmos/Extensions/CosmosModelExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosModelExtensions.cs index 9a0d0c716c5..dbea08211b4 100644 --- a/src/EFCore.Cosmos/Extensions/CosmosModelExtensions.cs +++ b/src/EFCore.Cosmos/Extensions/CosmosModelExtensions.cs @@ -38,7 +38,8 @@ public static void SetDefaultContainer([NotNull] this IMutableModel model, [CanB /// The model. /// The name to set. /// Indicates whether the configuration was specified using a data annotation. - public static void SetDefaultContainer([NotNull] this IConventionModel model, [CanBeNull] string name, bool fromDataAnnotation = false) + public static void SetDefaultContainer( + [NotNull] this IConventionModel model, [CanBeNull] string name, bool fromDataAnnotation = false) => model.SetOrRemoveAnnotation( CosmosAnnotationNames.ContainerName, Check.NullButNotEmpty(name, nameof(name)), diff --git a/src/EFCore.Cosmos/Extensions/CosmosPropertyExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosPropertyExtensions.cs index e3452eea563..4fa98985825 100644 --- a/src/EFCore.Cosmos/Extensions/CosmosPropertyExtensions.cs +++ b/src/EFCore.Cosmos/Extensions/CosmosPropertyExtensions.cs @@ -60,7 +60,8 @@ public static void SetPropertyName([NotNull] this IMutableProperty property, [Ca /// The property. /// The name to set. /// Indicates whether the configuration was specified using a data annotation. - public static void SetPropertyName([NotNull] this IConventionProperty property, [CanBeNull] string name, bool fromDataAnnotation = false) + public static void SetPropertyName( + [NotNull] this IConventionProperty property, [CanBeNull] string name, bool fromDataAnnotation = false) => property.SetOrRemoveAnnotation( CosmosAnnotationNames.PropertyName, name, diff --git a/src/EFCore.Cosmos/Query/Internal/ContainsTranslator.cs b/src/EFCore.Cosmos/Query/Internal/ContainsTranslator.cs index c6555eb1104..8c09046acce 100644 --- a/src/EFCore.Cosmos/Query/Internal/ContainsTranslator.cs +++ b/src/EFCore.Cosmos/Query/Internal/ContainsTranslator.cs @@ -44,8 +44,8 @@ public virtual SqlExpression Translate(SqlExpression instance, MethodInfo method } if ((method.DeclaringType.GetInterfaces().Contains(typeof(IList)) - || method.DeclaringType.IsGenericType - && method.DeclaringType.GetGenericTypeDefinition() == typeof(ICollection<>)) + || method.DeclaringType.IsGenericType + && method.DeclaringType.GetGenericTypeDefinition() == typeof(ICollection<>)) && string.Equals(method.Name, nameof(IList.Contains))) { return _sqlExpressionFactory.In(arguments[0], instance, false); diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs index 4f37e8dcfcd..2cf539c6b80 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs @@ -310,7 +310,6 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp throw new InvalidOperationException(CoreStrings.QueryFailed(methodCallExpression.Print(), GetType().Name)); } - Expression navigationProjection; var navigation = _includedNavigations.FirstOrDefault(n => n.Name == memberName); if (navigation == null) @@ -367,16 +366,16 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp { var genericMethod = method.IsGenericMethod ? method.GetGenericMethodDefinition() : null; var visitedSource = Visit(methodCallExpression.Arguments[0]); - + switch (method.Name) { case nameof(Queryable.AsQueryable) - when genericMethod == QueryableMethods.AsQueryable: + when genericMethod == QueryableMethods.AsQueryable: // Unwrap AsQueryable return visitedSource; case nameof(Queryable.Select) - when genericMethod == QueryableMethods.Select: + when genericMethod == QueryableMethods.Select: if (!(visitedSource is CollectionShaperExpression shaper)) { return null; diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitor.cs index 8fa8e9037ee..59258262658 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitor.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitor.cs @@ -11,7 +11,6 @@ using Microsoft.EntityFrameworkCore.Cosmos.Metadata.Internal; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Query; diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.QueryingEnumerable.cs b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.QueryingEnumerable.cs index 166504aebc4..5b6743565d3 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.QueryingEnumerable.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.QueryingEnumerable.cs @@ -41,8 +41,10 @@ public QueryingEnumerable( _contextType = contextType; _logger = logger; } + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) => new AsyncEnumerator(this, cancellationToken); + public IEnumerator GetEnumerator() => new Enumerator(this); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs index a8f4d7f4a69..6940add6b62 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs @@ -187,11 +187,9 @@ public virtual async Task DeleteDatabaseOnceAsync( { return false; } - else - { - response.EnsureSuccessStatusCode(); - return response.StatusCode == HttpStatusCode.NoContent; - } + + response.EnsureSuccessStatusCode(); + return response.StatusCode == HttpStatusCode.NoContent; } } @@ -242,11 +240,9 @@ private async Task CreateContainerIfNotExistsOnceAsync( { return false; } - else - { - response.EnsureSuccessStatusCode(); - return response.StatusCode == HttpStatusCode.Created; - } + + response.EnsureSuccessStatusCode(); + return response.StatusCode == HttpStatusCode.Created; } } diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosExecutionStrategy.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosExecutionStrategy.cs index f7551495ebd..059b1dff050 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosExecutionStrategy.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosExecutionStrategy.cs @@ -118,7 +118,7 @@ protected override bool ShouldRetryOn(Exception exception) static bool IsTransient(HttpStatusCode statusCode) => statusCode == HttpStatusCode.ServiceUnavailable - || statusCode == (HttpStatusCode)429; // TooManyRequests + || statusCode == (HttpStatusCode)429; // TooManyRequests } /// diff --git a/src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs b/src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs index 13a1f49dbe4..517a91f46ec 100644 --- a/src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs +++ b/src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs @@ -81,7 +81,7 @@ public virtual string WriteCode( if (finalContextNamespace != modelNamespace) { - _sb.AppendLine(String.Concat("using ", modelNamespace, ";")); + _sb.AppendLine(string.Concat("using ", modelNamespace, ";")); } _sb.AppendLine(); diff --git a/src/EFCore.InMemory/Query/Internal/EntityProjectionExpression.cs b/src/EFCore.InMemory/Query/Internal/EntityProjectionExpression.cs index ab4769e0420..52ae43f02bd 100644 --- a/src/EFCore.InMemory/Query/Internal/EntityProjectionExpression.cs +++ b/src/EFCore.InMemory/Query/Internal/EntityProjectionExpression.cs @@ -12,6 +12,7 @@ namespace Microsoft.EntityFrameworkCore.InMemory.Query.Internal public class EntityProjectionExpression : Expression, IPrintableExpression { private readonly IDictionary _readExpressionMap; + private readonly IDictionary _navigationExpressionsCache = new Dictionary(); @@ -60,7 +61,7 @@ public virtual void AddNavigationBinding(INavigation navigation, EntityShaperExp && !navigation.DeclaringEntityType.IsAssignableFrom(EntityType)) { throw new InvalidOperationException( - $"Called EntityProjectionExpression.AddNavigationBinding() with incorrect INavigation. " + + "Called EntityProjectionExpression.AddNavigationBinding() with incorrect INavigation. " + $"EntityType:{EntityType.DisplayName()}, Property:{navigation.Name}"); } @@ -73,7 +74,7 @@ public virtual EntityShaperExpression BindNavigation(INavigation navigation) && !navigation.DeclaringEntityType.IsAssignableFrom(EntityType)) { throw new InvalidOperationException( - $"Called EntityProjectionExpression.BindNavigation() with incorrect INavigation. " + + "Called EntityProjectionExpression.BindNavigation() with incorrect INavigation. " + $"EntityType:{EntityType.DisplayName()}, Property:{navigation.Name}"); } diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs index c53ae429091..da002da20f8 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs @@ -74,7 +74,8 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) var newLeft = Visit(binaryExpression.Left); var newRight = Visit(binaryExpression.Right); - if (newLeft == null || newRight == null) + if (newLeft == null + || newRight == null) { return null; } @@ -101,7 +102,9 @@ protected override Expression VisitConditional(ConditionalExpression conditional var ifTrue = Visit(conditionalExpression.IfTrue); var ifFalse = Visit(conditionalExpression.IfFalse); - if (test == null || ifTrue == null || ifFalse == null) + if (test == null + || ifTrue == null + || ifFalse == null) { return null; } @@ -124,15 +127,16 @@ protected override Expression VisitConditional(ConditionalExpression conditional protected override Expression VisitMember(MemberExpression memberExpression) { var innerExpression = Visit(memberExpression.Expression); - if (memberExpression.Expression != null && innerExpression == null) + if (memberExpression.Expression != null + && innerExpression == null) { return null; } if ((innerExpression is EntityProjectionExpression - || (innerExpression is UnaryExpression innerUnaryExpression - && innerUnaryExpression.NodeType == ExpressionType.Convert - && innerUnaryExpression.Operand is EntityProjectionExpression)) + || (innerExpression is UnaryExpression innerUnaryExpression + && innerUnaryExpression.NodeType == ExpressionType.Convert + && innerUnaryExpression.Operand is EntityProjectionExpression)) && TryBindMember(innerExpression, MemberIdentity.Create(memberExpression.Member), memberExpression.Type, out var result)) { return result; @@ -140,8 +144,8 @@ protected override Expression VisitMember(MemberExpression memberExpression) static bool shouldApplyNullProtectionForMemberAccess(Type callerType, string memberName) => !(callerType.IsGenericType - && callerType.GetGenericTypeDefinition() == typeof(Nullable<>) - && (memberName == nameof(Nullable.Value) || memberName == nameof(Nullable.HasValue))); + && callerType.GetGenericTypeDefinition() == typeof(Nullable<>) + && (memberName == nameof(Nullable.Value) || memberName == nameof(Nullable.HasValue))); var updatedMemberExpression = (Expression)memberExpression.Update(innerExpression); if (innerExpression != null @@ -202,8 +206,8 @@ private bool TryBindMember(Expression source, MemberIdentity memberIdentity, Typ // if the result type change was just nullability change e.g from int to int? we want to preserve the new type for null propagation if (result.Type != type && !(result.Type.IsNullableType() - && !type.IsNullableType() - && result.Type.UnwrapNullableType() == type)) + && !type.IsNullableType() + && result.Type.UnwrapNullableType() == type)) { result = Expression.Convert(result, type); } @@ -216,18 +220,18 @@ private bool TryBindMember(Expression source, MemberIdentity memberIdentity, Typ private static bool IsConvertedToNullable(Expression result, Expression original) => result.Type.IsNullableType() - && !original.Type.IsNullableType() - && result.Type.UnwrapNullableType() == original.Type; + && !original.Type.IsNullableType() + && result.Type.UnwrapNullableType() == original.Type; private static Expression ConvertToNullable(Expression expression) => !expression.Type.IsNullableType() - ? Expression.Convert(expression, expression.Type.MakeNullable()) - : expression; + ? Expression.Convert(expression, expression.Type.MakeNullable()) + : expression; private static Expression ConvertToNonNullable(Expression expression) => expression.Type.IsNullableType() - ? Expression.Convert(expression, expression.Type.UnwrapNullableType()) - : expression; + ? Expression.Convert(expression, expression.Type.UnwrapNullableType()) + : expression; private static Expression BindProperty(EntityProjectionExpression entityProjectionExpression, IProperty property) => entityProjectionExpression.BindProperty(property); @@ -315,7 +319,8 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp ? method.MakeGenericMethod(typeof(ValueBuffer), selector.ReturnType) : method.MakeGenericMethod(typeof(ValueBuffer)); - return Expression.Call(method, + return Expression.Call( + method, groupByShaperExpression.GroupingParameter, selector); @@ -339,8 +344,8 @@ MethodInfo GetMethod() { return Expression.Call( (countMethod - ? InMemoryLinqOperatorProvider.CountWithoutPredicate - : InMemoryLinqOperatorProvider.LongCountWithoutPredicate) + ? InMemoryLinqOperatorProvider.CountWithoutPredicate + : InMemoryLinqOperatorProvider.LongCountWithoutPredicate) .MakeGenericMethod(typeof(ValueBuffer)), groupByShaperExpression.GroupingParameter); } @@ -355,8 +360,8 @@ MethodInfo GetMethod() return Expression.Call( (countMethod - ? InMemoryLinqOperatorProvider.CountWithPredicate - : InMemoryLinqOperatorProvider.LongCountWithPredicate) + ? InMemoryLinqOperatorProvider.CountWithPredicate + : InMemoryLinqOperatorProvider.LongCountWithPredicate) .MakeGenericMethod(typeof(ValueBuffer)), groupByShaperExpression.GroupingParameter, predicate); @@ -383,8 +388,6 @@ MethodInfo GetMethod() return null; } - Expression result; - // Unwrap ResultEnumerable var selectMethod = (MethodCallExpression)subquery.ServerQueryExpression; var resultEnumerable = (NewExpression)selectMethod.Arguments[0]; @@ -392,6 +395,7 @@ MethodInfo GetMethod() // New ValueBuffer construct if (resultFunc is NewExpression newValueBufferExpression) { + Expression result; var innerExpression = ((NewArrayExpression)newValueBufferExpression.Arguments[0]).Expressions[0]; if (innerExpression is UnaryExpression unaryExpression && innerExpression.NodeType == ExpressionType.Convert @@ -565,6 +569,7 @@ protected override Expression VisitNewArray(NewArrayExpression newArrayExpressio { return null; } + if (IsConvertedToNullable(newExpression, expression)) { newExpression = ConvertToNonNullable(newExpression); @@ -583,6 +588,7 @@ protected override MemberAssignment VisitMemberAssignment(MemberAssignment membe { return null; } + if (IsConvertedToNullable(expression, memberAssignment.Expression)) { expression = ConvertToNonNullable(expression); diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryLinqOperatorProvider.cs b/src/EFCore.InMemory/Query/Internal/InMemoryLinqOperatorProvider.cs index cf0c734b2ba..451ef7a2f4c 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryLinqOperatorProvider.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryLinqOperatorProvider.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.InMemory.Query.Internal { @@ -76,6 +75,7 @@ public static class InMemoryLinqOperatorProvider public static MethodInfo GetAverageWithoutSelector(Type type) => AverageWithoutSelectorMethods[type]; public static MethodInfo GetAverageWithSelector(Type type) => AverageWithSelectorMethods[type]; + public static MethodInfo GetMaxWithoutSelector(Type type) => MaxWithoutSelectorMethods.TryGetValue(type, out var method) ? method @@ -119,9 +119,10 @@ private static Type GetFuncType(int funcGenericArguments) _ => throw new InvalidOperationException("Invalid number of arguments for Func"), }; } + private static bool IsFunc(Type type, int funcGenericArguments = 2) => type.IsGenericType - && type.GetGenericTypeDefinition() == GetFuncType(funcGenericArguments); + && type.GetGenericTypeDefinition() == GetFuncType(funcGenericArguments); static InMemoryLinqOperatorProvider() { @@ -160,15 +161,20 @@ static InMemoryLinqOperatorProvider() LongCountWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.LongCount) && mi.GetParameters().Length == 1); LongCountWithPredicate = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.LongCount) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.LongCount) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); MinWithSelector = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.Min) && mi.IsGenericMethod && mi.GetGenericArguments().Length == 2 && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.Min) && mi.IsGenericMethod && mi.GetGenericArguments().Length == 2 + && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); MinWithoutSelector = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.Min) && mi.IsGenericMethod && mi.GetGenericArguments().Length == 1 && mi.GetParameters().Length == 1); + mi => mi.Name == nameof(Enumerable.Min) && mi.IsGenericMethod && mi.GetGenericArguments().Length == 1 + && mi.GetParameters().Length == 1); MaxWithSelector = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.Max) && mi.IsGenericMethod && mi.GetGenericArguments().Length == 2 && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.Max) && mi.IsGenericMethod && mi.GetGenericArguments().Length == 2 + && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); MaxWithoutSelector = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.Max) && mi.IsGenericMethod && mi.GetGenericArguments().Length == 1 && mi.GetParameters().Length == 1); + mi => mi.Name == nameof(Enumerable.Max) && mi.IsGenericMethod && mi.GetGenericArguments().Length == 1 + && mi.GetParameters().Length == 1); ElementAt = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.ElementAt) && mi.GetParameters().Length == 2); @@ -181,15 +187,18 @@ static InMemoryLinqOperatorProvider() FirstOrDefaultWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.FirstOrDefault) && mi.GetParameters().Length == 1); FirstOrDefaultWithPredicate = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.FirstOrDefault) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.FirstOrDefault) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); SingleWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Single) && mi.GetParameters().Length == 1); SingleWithPredicate = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.Single) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.Single) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); SingleOrDefaultWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.SingleOrDefault) && mi.GetParameters().Length == 1); SingleOrDefaultWithPredicate = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.SingleOrDefault) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.SingleOrDefault) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); LastWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Last) && mi.GetParameters().Length == 1); LastWithPredicate = enumerableMethods.Single( @@ -197,7 +206,8 @@ static InMemoryLinqOperatorProvider() LastOrDefaultWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.LastOrDefault) && mi.GetParameters().Length == 1); LastOrDefaultWithPredicate = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.LastOrDefault) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.LastOrDefault) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); Distinct = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Distinct) && mi.GetParameters().Length == 1); @@ -206,23 +216,30 @@ static InMemoryLinqOperatorProvider() Where = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Where) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); Select = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.Select) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.Select) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); Skip = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Skip) && mi.GetParameters().Length == 2); Take = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Take) && mi.GetParameters().Length == 2); SkipWhile = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.SkipWhile) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.SkipWhile) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); TakeWhile = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.TakeWhile) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.TakeWhile) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); OrderBy = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.OrderBy) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.OrderBy) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); OrderByDescending = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.OrderByDescending) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.OrderByDescending) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); ThenBy = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.ThenBy) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.ThenBy) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); ThenByDescending = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.ThenByDescending) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.ThenByDescending) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); DefaultIfEmptyWithoutArgument = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.DefaultIfEmpty) && mi.GetParameters().Length == 1); DefaultIfEmptyWithArgument = enumerableMethods.Single( @@ -233,18 +250,24 @@ static InMemoryLinqOperatorProvider() GroupJoin = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.GroupJoin) && mi.GetParameters().Length == 5); SelectManyWithCollectionSelector = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.SelectMany) && mi.GetParameters().Length == 3 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.SelectMany) && mi.GetParameters().Length == 3 + && IsFunc(mi.GetParameters()[1].ParameterType)); SelectManyWithoutCollectionSelector = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.SelectMany) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.SelectMany) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); GroupByWithKeySelector = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 2 && IsFunc(mi.GetParameters()[1].ParameterType)); + mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 2 + && IsFunc(mi.GetParameters()[1].ParameterType)); GroupByWithKeyElementSelector = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 3 && IsFunc(mi.GetParameters()[1].ParameterType) && IsFunc(mi.GetParameters()[2].ParameterType)); + mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 3 && IsFunc(mi.GetParameters()[1].ParameterType) + && IsFunc(mi.GetParameters()[2].ParameterType)); GroupByWithKeyElementResultSelector = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 4 && IsFunc(mi.GetParameters()[1].ParameterType) && IsFunc(mi.GetParameters()[2].ParameterType) && IsFunc(mi.GetParameters()[3].ParameterType, 3)); + mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 4 && IsFunc(mi.GetParameters()[1].ParameterType) + && IsFunc(mi.GetParameters()[2].ParameterType) && IsFunc(mi.GetParameters()[3].ParameterType, 3)); GroupByWithKeyResultSelector = enumerableMethods.Single( - mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 3 && IsFunc(mi.GetParameters()[1].ParameterType) && IsFunc(mi.GetParameters()[2].ParameterType, 3)); + mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 3 && IsFunc(mi.GetParameters()[1].ParameterType) + && IsFunc(mi.GetParameters()[2].ParameterType, 3)); MethodInfo getSumOrAverageWithoutSelector(string methodName) => enumerableMethods.Single( diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs index 7e86283543f..aa400820078 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs @@ -141,7 +141,8 @@ public override Expression Visit(Expression expression) translation = NullSafeConvert(translation, expression.Type); } - return new ProjectionBindingExpression(_queryExpression, _queryExpression.AddToProjection(translation), expression.Type); + return new ProjectionBindingExpression( + _queryExpression, _queryExpression.AddToProjection(translation), expression.Type); } else { @@ -204,13 +205,11 @@ protected override Expression VisitExtension(Expression extensionExpression) return entityShaperExpression.Update( new ProjectionBindingExpression(_queryExpression, _queryExpression.AddToProjection(entityProjectionExpression))); } - else - { - _projectionMapping[_projectionMembers.Peek()] = entityProjectionExpression; - return entityShaperExpression.Update( - new ProjectionBindingExpression(_queryExpression, _projectionMembers.Peek(), typeof(ValueBuffer))); - } + _projectionMapping[_projectionMembers.Peek()] = entityProjectionExpression; + + return entityShaperExpression.Update( + new ProjectionBindingExpression(_queryExpression, _projectionMembers.Peek(), typeof(ValueBuffer))); } if (extensionExpression is IncludeExpression includeExpression) diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs b/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs index 504c13d1e01..b7c043877e7 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs @@ -17,12 +17,15 @@ public partial class InMemoryQueryExpression : Expression, IPrintableExpression { private static readonly ConstructorInfo _valueBufferConstructor = typeof(ValueBuffer).GetConstructors().Single(ci => ci.GetParameters().Length == 1); + private static readonly PropertyInfo _valueBufferCountMemberInfo = typeof(ValueBuffer).GetTypeInfo().GetProperty(nameof(ValueBuffer.Count)); private readonly List _valueBufferSlots = new List(); + private readonly IDictionary> _entityProjectionCache = new Dictionary>(); + private readonly ParameterExpression _valueBufferParameter; private IDictionary _projectionMapping = new Dictionary(); @@ -49,7 +52,8 @@ public InMemoryQueryExpression(IEntityType entityType) readExpressionMap[property] = Condition( LessThan( Constant(property.GetIndex()), - MakeMemberAccess(_valueBufferParameter, + MakeMemberAccess( + _valueBufferParameter, _valueBufferCountMemberInfo)), CreateReadValueExpression(property.ClrType, property.GetIndex(), property), Default(property.ClrType)); @@ -138,7 +142,8 @@ public virtual int AddSubqueryProjection(ShapedQueryExpression shapedQueryExpres if (serverQueryExpression is MethodCallExpression selectMethodCall && selectMethodCall.Arguments[0].Type == typeof(ResultEnumerable)) { - var terminatingMethodCall = (MethodCallExpression)((LambdaExpression)((NewExpression)selectMethodCall.Arguments[0]).Arguments[0]).Body; + var terminatingMethodCall = + (MethodCallExpression)((LambdaExpression)((NewExpression)selectMethodCall.Arguments[0]).Arguments[0]).Body; selectMethodCall = selectMethodCall.Update( null, new[] { terminatingMethodCall.Arguments[0], selectMethodCall.Arguments[1] }); serverQueryExpression = terminatingMethodCall.Update(null, new[] { selectMethodCall }); @@ -171,15 +176,14 @@ public override Expression Visit(Expression expression) { return new ProjectionBindingExpression(projectionBindingExpression.QueryExpression, indexMap); } - else if (mappingValue is int index) + + if (mappingValue is int index) { return new ProjectionBindingExpression( projectionBindingExpression.QueryExpression, index, projectionBindingExpression.Type); } - else - { - throw new InvalidOperationException("Invalid ProjectionMapping."); - } + + throw new InvalidOperationException("Invalid ProjectionMapping."); } return base.Visit(expression); @@ -209,6 +213,7 @@ public virtual void PushdownIntoSubquery() var index = AddToProjection(expressionToAdd); map[property] = CreateReadValueExpression(expressionToAdd.Type, index, property); } + result[keyValuePair.Key] = new EntityProjectionExpression(entityProjection.EntityType, map); } else @@ -272,6 +277,7 @@ public virtual void ApplyDefaultIfEmpty() var index = AddToProjection(expressionToAdd); map[property] = CreateReadValueExpression(expressionToAdd.Type.MakeNullable(), index, property); } + result[keyValuePair.Key] = new EntityProjectionExpression(entityProjection.EntityType, map); } else @@ -334,6 +340,7 @@ public virtual void ApplyProjection() { map[property] = AddToProjection(entityProjection.BindProperty(property)); } + result[keyValuePair.Key] = Constant(map); } else @@ -381,11 +388,11 @@ public virtual InMemoryGroupByShaperExpression ApplyGrouping(Expression grouping _valueBufferParameter); ServerQueryExpression = Call( - InMemoryLinqOperatorProvider.GroupByWithKeyElementSelector.MakeGenericMethod( - typeof(ValueBuffer), typeof(ValueBuffer), typeof(ValueBuffer)), - selectMethod.Arguments[0], - keySelector, - selectMethod.Arguments[1]); + InMemoryLinqOperatorProvider.GroupByWithKeyElementSelector.MakeGenericMethod( + typeof(ValueBuffer), typeof(ValueBuffer), typeof(ValueBuffer)), + selectMethod.Arguments[0], + keySelector, + selectMethod.Arguments[1]); return new InMemoryGroupByShaperExpression( groupingKey, @@ -410,6 +417,7 @@ private Expression GetGroupingKey(Expression key, List groupingExpre { arguments[i] = GetGroupingKey(newExpression.Arguments[i], groupingExpressions, groupingKeyAccessExpression); } + return newExpression.Update(arguments); case MemberInitExpression memberInitExpression: @@ -430,6 +438,7 @@ private Expression GetGroupingKey(Expression key, List groupingExpre groupingExpressions, groupingKeyAccessExpression)); } + return memberInitExpression.Update(updatedNewExpression, memberBindings); default: @@ -465,11 +474,10 @@ public virtual void AddInnerJoin( var resultValueBufferExpressions = new List(); var projectionMapping = new Dictionary(); var replacingVisitor = new ReplacingExpressionVisitor( - new Dictionary - { - { CurrentParameter, outerParameter }, - { innerQueryExpression.CurrentParameter, innerParameter } - }); + new Dictionary + { + { CurrentParameter, outerParameter }, { innerQueryExpression.CurrentParameter, innerParameter } + }); var index = 0; var outerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Outer"); @@ -581,11 +589,11 @@ public virtual void AddLeftJoin( var resultValueBufferExpressions = new List(); var projectionMapping = new Dictionary(); var replacingVisitor = new ReplacingExpressionVisitor( - new Dictionary - { - { CurrentParameter, MakeMemberAccess(outerParameter, outerMemberInfo) }, - { innerQueryExpression.CurrentParameter, innerParameter } - }); + new Dictionary + { + { CurrentParameter, MakeMemberAccess(outerParameter, outerMemberInfo) }, + { innerQueryExpression.CurrentParameter, innerParameter } + }); var index = 0; outerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Outer"); @@ -681,11 +689,10 @@ public virtual void AddSelectMany(InMemoryQueryExpression innerQueryExpression, var resultValueBufferExpressions = new List(); var projectionMapping = new Dictionary(); var replacingVisitor = new ReplacingExpressionVisitor( - new Dictionary - { - { CurrentParameter, outerParameter }, - { innerQueryExpression.CurrentParameter, innerParameter } - }); + new Dictionary + { + { CurrentParameter, outerParameter }, { innerQueryExpression.CurrentParameter, innerParameter } + }); var index = 0; var outerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Outer"); @@ -726,6 +733,7 @@ public virtual void AddSelectMany(InMemoryQueryExpression innerQueryExpression, { replacedExpression = nullableReadValueExpressionVisitor.Visit(replacedExpression); } + resultValueBufferExpressions.Add(replacedExpression); readExpressionMap[property] = CreateReadValueExpression(replacedExpression.Type, index++, property); } @@ -740,6 +748,7 @@ public virtual void AddSelectMany(InMemoryQueryExpression innerQueryExpression, { replacedExpression = nullableReadValueExpressionVisitor.Visit(replacedExpression); } + resultValueBufferExpressions.Add(replacedExpression); projectionMapping[projection.Key.Prepend(innerMemberInfo)] = CreateReadValueExpression(replacedExpression.Type, index++, InferPropertyFromInner(projection.Value)); @@ -784,8 +793,7 @@ public virtual EntityShaperExpression AddNavigationToWeakEntityType( var resultSelector = Lambda( New( groupTransparentIdentifierType.GetTypeInfo().DeclaredConstructors.Single(), - new[] { outerParameter, innerParameter }, - new[] { outerMemberInfo, innerMemberInfo }), + new[] { outerParameter, innerParameter }, outerMemberInfo, innerMemberInfo), outerParameter, innerParameter); @@ -832,7 +840,7 @@ EntityProjectionExpression copyEntityProjectionToOuter(EntityProjectionExpressio // Also lift nested entity projections foreach (var navigation in entityProjection.EntityType.GetTypesInHierarchy() - .SelectMany(EntityTypeExtensions.GetDeclaredNavigations)) + .SelectMany(EntityTypeExtensions.GetDeclaredNavigations)) { var boundEntityShaperExpression = entityProjection.BindNavigation(navigation); if (boundEntityShaperExpression != null) @@ -876,6 +884,7 @@ EntityProjectionExpression copyEntityProjectionToOuter(EntityProjectionExpressio resultValueBufferExpressions.Add(replacedExpression); innerReadExpressionMap[property] = CreateReadValueExpression(replacedExpression.Type, index++, property); } + innerEntityProjection = new EntityProjectionExpression(innerEntityProjection.EntityType, innerReadExpressionMap); var collectionSelector = Lambda( diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs index a621712b7af..d05c5b9b19d 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs @@ -233,7 +233,8 @@ protected override ShapedQueryExpression TranslateFirstOrDefault( : InMemoryLinqOperatorProvider.FirstWithoutPredicate); } - protected override ShapedQueryExpression TranslateGroupBy(ShapedQueryExpression source, LambdaExpression keySelector, LambdaExpression elementSelector, LambdaExpression resultSelector) + protected override ShapedQueryExpression TranslateGroupBy( + ShapedQueryExpression source, LambdaExpression keySelector, LambdaExpression elementSelector, LambdaExpression resultSelector) { var remappedKeySelector = RemapLambdaBody(source, keySelector); @@ -257,7 +258,8 @@ protected override ShapedQueryExpression TranslateGroupBy(ShapedQueryExpression var original2 = resultSelector.Parameters[1]; var newResultSelectorBody = new ReplacingExpressionVisitor( - new Dictionary { + new Dictionary + { { original1, ((GroupByShaperExpression)source.ShaperExpression).KeySelector }, { original2, source.ShaperExpression } }).Visit(resultSelector.Body); @@ -332,7 +334,7 @@ private Expression TranslateGroupingKey(Expression expression) } return translation.Type == expression.Type - ? (Expression)translation + ? translation : Expression.Convert(translation, expression.Type); } } @@ -351,7 +353,8 @@ protected override ShapedQueryExpression TranslateJoin( { outerKeySelector = TranslateLambdaExpression(outer, outerKeySelector); innerKeySelector = TranslateLambdaExpression(inner, innerKeySelector); - if (outerKeySelector == null || innerKeySelector == null) + if (outerKeySelector == null + || innerKeySelector == null) { return null; } @@ -380,8 +383,8 @@ private static (LambdaExpression OuterKeySelector, LambdaExpression InnerKeySele { static bool isConvertedToNullable(Expression outer, Expression inner) => outer.Type.IsNullableType() - && !inner.Type.IsNullableType() - && outer.Type.UnwrapNullableType() == inner.Type; + && !inner.Type.IsNullableType() + && outer.Type.UnwrapNullableType() == inner.Type; if (outerKeySelector.Body.Type != innerKeySelector.Body.Type) { @@ -400,7 +403,8 @@ static bool isConvertedToNullable(Expression outer, Expression inner) return (outerKeySelector, innerKeySelector); } - protected override ShapedQueryExpression TranslateLastOrDefault(ShapedQueryExpression source, LambdaExpression predicate, Type returnType, bool returnDefault) + protected override ShapedQueryExpression TranslateLastOrDefault( + ShapedQueryExpression source, LambdaExpression predicate, Type returnType, bool returnDefault) { return TranslateSingleResultOperator( source, @@ -417,7 +421,8 @@ protected override ShapedQueryExpression TranslateLeftJoin( { outerKeySelector = TranslateLambdaExpression(outer, outerKeySelector); innerKeySelector = TranslateLambdaExpression(inner, innerKeySelector); - if (outerKeySelector == null || innerKeySelector == null) + if (outerKeySelector == null + || innerKeySelector == null) { return null; } @@ -449,7 +454,8 @@ protected override ShapedQueryExpression TranslateLongCount(ShapedQueryExpressio { inMemoryQueryExpression.ServerQueryExpression = Expression.Call( - InMemoryLinqOperatorProvider.LongCountWithoutPredicate.MakeGenericMethod(inMemoryQueryExpression.CurrentParameter.Type), + InMemoryLinqOperatorProvider.LongCountWithoutPredicate.MakeGenericMethod( + inMemoryQueryExpression.CurrentParameter.Type), inMemoryQueryExpression.ServerQueryExpression); } else @@ -462,7 +468,8 @@ protected override ShapedQueryExpression TranslateLongCount(ShapedQueryExpressio inMemoryQueryExpression.ServerQueryExpression = Expression.Call( - InMemoryLinqOperatorProvider.LongCountWithPredicate.MakeGenericMethod(inMemoryQueryExpression.CurrentParameter.Type), + InMemoryLinqOperatorProvider.LongCountWithPredicate.MakeGenericMethod( + inMemoryQueryExpression.CurrentParameter.Type), inMemoryQueryExpression.ServerQueryExpression, predicate); } @@ -540,7 +547,7 @@ protected override ShapedQueryExpression TranslateOfType(ShapedQueryExpression s inMemoryQueryExpression.ReplaceProjectionMapping( new Dictionary { - { projectionMember, entityProjection.UpdateEntityType(derivedType)} + { projectionMember, entityProjection.UpdateEntityType(derivedType) } }); source.ShaperExpression = entityShaperExpression.WithEntityType(derivedType); @@ -657,12 +664,7 @@ protected override ShapedQueryExpression TranslateSelectMany(ShapedQueryExpressi { var innerParameter = Expression.Parameter(selector.ReturnType.TryGetSequenceType(), "i"); var resultSelector = Expression.Lambda( - innerParameter, - new[] - { - Expression.Parameter(source.Type.TryGetSequenceType()), - innerParameter - }); + innerParameter, Expression.Parameter(source.Type.TryGetSequenceType()), innerParameter); return TranslateSelectMany(source, selector, resultSelector); } @@ -736,7 +738,7 @@ protected override ShapedQueryExpression TranslateThenBy(ShapedQueryExpression s inMemoryQueryExpression.ServerQueryExpression = Expression.Call( (ascending ? InMemoryLinqOperatorProvider.ThenBy : InMemoryLinqOperatorProvider.ThenByDescending) - .MakeGenericMethod(inMemoryQueryExpression.CurrentParameter.Type, keySelector.ReturnType), + .MakeGenericMethod(inMemoryQueryExpression.CurrentParameter.Type, keySelector.ReturnType), inMemoryQueryExpression.ServerQueryExpression, keySelector); @@ -767,8 +769,10 @@ private Expression TranslateExpression(Expression expression, bool preserveType { var result = _expressionTranslator.Translate(expression); - if (expression != null && result != null - && preserveType && expression.Type != result.Type) + if (expression != null + && result != null + && preserveType + && expression.Type != result.Type) { result = expression.Type == typeof(bool) ? Expression.Equal(result, Expression.Constant(true, result.Type)) @@ -786,7 +790,8 @@ private LambdaExpression TranslateLambdaExpression( var lambdaBody = TranslateExpression(RemapLambdaBody(shapedQueryExpression, lambdaExpression), preserveType); return lambdaBody != null - ? Expression.Lambda(lambdaBody, + ? Expression.Lambda( + lambdaBody, ((InMemoryQueryExpression)shapedQueryExpression.QueryExpression).CurrentParameter) : null; } @@ -845,8 +850,8 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp source = Visit(source); if (source is EntityShaperExpression || (source is UnaryExpression innerUnaryExpression - && innerUnaryExpression.NodeType == ExpressionType.Convert - && innerUnaryExpression.Operand is EntityShaperExpression)) + && innerUnaryExpression.NodeType == ExpressionType.Convert + && innerUnaryExpression.Operand is EntityShaperExpression)) { var collectionNavigation = Expand(source, MemberIdentity.Create(navigationName)); if (collectionNavigation != null) @@ -983,7 +988,8 @@ ProjectionBindingExpression projectionBindingExpression makeNullable); var outerKeySelector = Expression.Lambda(_expressionTranslator.Translate(outerKey), _queryExpression.CurrentParameter); - var innerKeySelector = Expression.Lambda(_expressionTranslator.Translate(innerKey), innerQueryExpression.CurrentParameter); + var innerKeySelector = Expression.Lambda( + _expressionTranslator.Translate(innerKey), innerQueryExpression.CurrentParameter); (outerKeySelector, innerKeySelector) = AlignKeySelectorTypes(outerKeySelector, innerKeySelector); innerShaper = _queryExpression.AddNavigationToWeakEntityType( entityProjectionExpression, navigation, innerQueryExpression, outerKeySelector, innerKeySelector); @@ -1019,13 +1025,15 @@ MethodInfo getMethod() nameof(Enumerable.Sum) => InMemoryLinqOperatorProvider.GetSumWithSelector(selector.ReturnType), _ => throw new InvalidOperationException("Invalid Aggregate Operator encountered."), }; + var method = getMethod(); method = method.GetGenericArguments().Length == 2 ? method.MakeGenericMethod(typeof(ValueBuffer), selector.ReturnType) : method.MakeGenericMethod(typeof(ValueBuffer)); inMemoryQueryExpression.ServerQueryExpression - = Expression.Call(method, + = Expression.Call( + method, inMemoryQueryExpression.ServerQueryExpression, selector); diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.CustomShaperCompilingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.CustomShaperCompilingExpressionVisitor.cs index fa2bcbae860..550daa5c419 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.CustomShaperCompilingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.CustomShaperCompilingExpressionVisitor.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.InMemoryProjectionBindingRemovingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.InMemoryProjectionBindingRemovingExpressionVisitor.cs index 6895b4f6d1a..de205ddcc01 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.InMemoryProjectionBindingRemovingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.InMemoryProjectionBindingRemovingExpressionVisitor.cs @@ -17,7 +17,7 @@ private class InMemoryProjectionBindingRemovingExpressionVisitor : ExpressionVis { private readonly IDictionary IndexMap, ParameterExpression valueBuffer)> _materializationContextBindings - = new Dictionary IndexMap, ParameterExpression valueBuffer)>(); + = new Dictionary IndexMap, ParameterExpression valueBuffer)>(); protected override Expression VisitBinary(BinaryExpression binaryExpression) { @@ -103,7 +103,8 @@ private IPropertyBase InferPropertyFromInner(Expression expression) return null; } - private object GetProjectionIndex(InMemoryQueryExpression queryExpression, ProjectionBindingExpression projectionBindingExpression) + private object GetProjectionIndex( + InMemoryQueryExpression queryExpression, ProjectionBindingExpression projectionBindingExpression) { return projectionBindingExpression.ProjectionMember != null ? ((ConstantExpression)queryExpression.GetMappedProjection(projectionBindingExpression.ProjectionMember)).Value diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.cs index 980062f54fd..3a77fc27b7d 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.cs @@ -50,7 +50,7 @@ protected override Expression VisitShapedQueryExpression(ShapedQueryExpression s var inMemoryQueryExpression = (InMemoryQueryExpression)shapedQueryExpression.QueryExpression; var shaper = new ShaperExpressionProcessingExpressionVisitor( - inMemoryQueryExpression, inMemoryQueryExpression.CurrentParameter) + inMemoryQueryExpression, inMemoryQueryExpression.CurrentParameter) .Inject(shapedQueryExpression.ShaperExpression); shaper = InjectEntityMaterializers(shaper); diff --git a/src/EFCore.InMemory/Query/Internal/ShaperExpressionProcessingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/ShaperExpressionProcessingExpressionVisitor.cs index 688007a71c2..b935738cae7 100644 --- a/src/EFCore.InMemory/Query/Internal/ShaperExpressionProcessingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/ShaperExpressionProcessingExpressionVisitor.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; -using System.Linq; using System.Linq.Expressions; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Query; @@ -147,7 +146,7 @@ protected override Expression VisitExtension(Expression extensionExpression) private Expression GenerateKey(ProjectionBindingExpression projectionBindingExpression) => _queryExpression != null - && projectionBindingExpression.ProjectionMember != null + && projectionBindingExpression.ProjectionMember != null ? _queryExpression.GetMappedProjection(projectionBindingExpression.ProjectionMember) : projectionBindingExpression; } diff --git a/src/EFCore.InMemory/Query/Internal/SingleResultShaperExpression.cs b/src/EFCore.InMemory/Query/Internal/SingleResultShaperExpression.cs index db4e3a291a1..d8c3ce1089e 100644 --- a/src/EFCore.InMemory/Query/Internal/SingleResultShaperExpression.cs +++ b/src/EFCore.InMemory/Query/Internal/SingleResultShaperExpression.cs @@ -47,7 +47,7 @@ public virtual void Print(ExpressionPrinter expressionPrinter) expressionPrinter.Visit(Projection); expressionPrinter.Append(", "); expressionPrinter.Visit(InnerShaper); - expressionPrinter.AppendLine($")"); + expressionPrinter.AppendLine(")"); } } } diff --git a/src/EFCore.Relational/Diagnostics/DbTransactionInterceptor.cs b/src/EFCore.Relational/Diagnostics/DbTransactionInterceptor.cs index f54fb0118fa..e1d51a719f0 100644 --- a/src/EFCore.Relational/Diagnostics/DbTransactionInterceptor.cs +++ b/src/EFCore.Relational/Diagnostics/DbTransactionInterceptor.cs @@ -67,7 +67,8 @@ public virtual DbTransaction TransactionStarted( => result; /// - /// Called just before EF intends to call . + /// Called just before EF intends to call + /// . /// /// The connection. /// Contextual information about connection and transaction. @@ -92,7 +93,8 @@ public virtual Task> TransactionStartingAsync( /// /// - /// Called immediately after EF calls . + /// Called immediately after EF calls + /// . /// /// /// This method is still called if an interceptor suppressed creation in . @@ -102,7 +104,8 @@ public virtual Task> TransactionStartingAsync( /// The connection. /// Contextual information about connection and transaction. /// - /// The result of the call to . + /// The result of the call to + /// . /// This value is typically used as the return value for the implementation of this method. /// /// The cancellation token. @@ -198,7 +201,8 @@ public virtual void TransactionCommitted( } /// - /// Called just before EF intends to call . + /// Called just before EF intends to call + /// . /// /// The transaction. /// Contextual information about connection and transaction. @@ -272,7 +276,8 @@ public virtual void TransactionRolledBack( } /// - /// Called just before EF intends to call . + /// Called just before EF intends to call + /// . /// /// The transaction. /// Contextual information about connection and transaction. diff --git a/src/EFCore.Relational/Diagnostics/IDbTransactionInterceptor.cs b/src/EFCore.Relational/Diagnostics/IDbTransactionInterceptor.cs index 8092a7e437f..a4764a7b90a 100644 --- a/src/EFCore.Relational/Diagnostics/IDbTransactionInterceptor.cs +++ b/src/EFCore.Relational/Diagnostics/IDbTransactionInterceptor.cs @@ -81,7 +81,8 @@ DbTransaction TransactionStarted( [CanBeNull] DbTransaction result); /// - /// Called just before EF intends to call . + /// Called just before EF intends to call + /// . /// /// The connection. /// Contextual information about connection and transaction. @@ -107,7 +108,8 @@ Task> TransactionStartingAsync( /// /// - /// Called immediately after EF calls . + /// Called immediately after EF calls + /// . /// /// /// This method is still called if an interceptor suppressed creation in . @@ -117,7 +119,8 @@ Task> TransactionStartingAsync( /// The connection. /// Contextual information about connection and transaction. /// - /// The result of the call to . + /// The result of the call to + /// . /// This value is typically used as the return value for the implementation of this method. /// /// The cancellation token. @@ -210,7 +213,8 @@ void TransactionCommitted( [NotNull] TransactionEndEventData eventData); /// - /// Called just before EF intends to call . + /// Called just before EF intends to call + /// . /// /// The transaction. /// Contextual information about connection and transaction. @@ -279,7 +283,8 @@ void TransactionRolledBack( [NotNull] TransactionEndEventData eventData); /// - /// Called just before EF intends to call . + /// Called just before EF intends to call + /// . /// /// The transaction. /// Contextual information about connection and transaction. diff --git a/src/EFCore.Relational/Metadata/Builders/DbFunctionParameterBuilder.cs b/src/EFCore.Relational/Metadata/Builders/DbFunctionParameterBuilder.cs index f17c429d226..3e3f2c16e33 100644 --- a/src/EFCore.Relational/Metadata/Builders/DbFunctionParameterBuilder.cs +++ b/src/EFCore.Relational/Metadata/Builders/DbFunctionParameterBuilder.cs @@ -71,8 +71,8 @@ IConventionDbFunctionParameterBuilder IConventionDbFunctionParameterBuilder.HasS /// bool IConventionDbFunctionParameterBuilder.CanSetStoreType(string storeType, bool fromDataAnnotation) - => Overrides(fromDataAnnotation, _parameter.GetStoreTypeConfigurationSource()) - || _parameter.StoreType == storeType; + => Overrides(fromDataAnnotation, _parameter.GetStoreTypeConfigurationSource()) + || _parameter.StoreType == storeType; /// IConventionDbFunctionParameterBuilder IConventionDbFunctionParameterBuilder.HasTypeMapping( @@ -89,8 +89,8 @@ IConventionDbFunctionParameterBuilder IConventionDbFunctionParameterBuilder.HasT /// bool IConventionDbFunctionParameterBuilder.CanSetTypeMapping(RelationalTypeMapping typeMapping, bool fromDataAnnotation) - => Overrides(fromDataAnnotation, _parameter.GetTypeMappingConfigurationSource()) - || _parameter.TypeMapping == typeMapping; + => Overrides(fromDataAnnotation, _parameter.GetTypeMappingConfigurationSource()) + || _parameter.TypeMapping == typeMapping; private bool Overrides(bool fromDataAnnotation, ConfigurationSource? configurationSource) => (fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention) diff --git a/src/EFCore.Relational/Metadata/Conventions/RelationalValueGenerationConvention.cs b/src/EFCore.Relational/Metadata/Conventions/RelationalValueGenerationConvention.cs index 7cb7d1586c4..338356ca05b 100644 --- a/src/EFCore.Relational/Metadata/Conventions/RelationalValueGenerationConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/RelationalValueGenerationConvention.cs @@ -76,7 +76,8 @@ public virtual void ProcessEntityTypeAnnotationChanged( entityTypeBuilder, (string)oldAnnotation?.Value ?? entityTypeBuilder.Metadata.GetDefaultTableName(), entityTypeBuilder.Metadata.GetSchema()); - } else if (name == RelationalAnnotationNames.Schema) + } + else if (name == RelationalAnnotationNames.Schema) { ProcessTableChanged( entityTypeBuilder, diff --git a/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs b/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs index c30bd156efd..4e8f10aaa36 100644 --- a/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs +++ b/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs @@ -32,19 +32,32 @@ namespace Microsoft.EntityFrameworkCore.Migrations.Internal /// doing so can result in application failures when updating to a new Entity Framework Core release. /// /// - /// The service lifetime is . This means that each - /// instance will use its own instance of this service. + /// The service lifetime is . This means that each + /// instance will use its own instance of this service. /// The implementation may depend on other services registered with any lifetime. /// The implementation does not need to be thread-safe. /// /// public class MigrationsModelDiffer : IMigrationsModelDiffer { - private static readonly Type[] _dropOperationTypes = { typeof(DropIndexOperation), typeof(DropPrimaryKeyOperation), typeof(DropSequenceOperation), typeof(DropUniqueConstraintOperation), typeof(DropCheckConstraintOperation) }; - - private static readonly Type[] _alterOperationTypes = { typeof(AddPrimaryKeyOperation), typeof(AddUniqueConstraintOperation), typeof(AlterSequenceOperation) }; + private static readonly Type[] _dropOperationTypes = + { + typeof(DropIndexOperation), + typeof(DropPrimaryKeyOperation), + typeof(DropSequenceOperation), + typeof(DropUniqueConstraintOperation), + typeof(DropCheckConstraintOperation) + }; + + private static readonly Type[] _alterOperationTypes = + { + typeof(AddPrimaryKeyOperation), typeof(AddUniqueConstraintOperation), typeof(AlterSequenceOperation) + }; - private static readonly Type[] _renameOperationTypes = { typeof(RenameColumnOperation), typeof(RenameIndexOperation), typeof(RenameSequenceOperation) }; + private static readonly Type[] _renameOperationTypes = + { + typeof(RenameColumnOperation), typeof(RenameIndexOperation), typeof(RenameSequenceOperation) + }; private static readonly Type[] _columnOperationTypes = { typeof(AddColumnOperation), typeof(AlterColumnOperation) }; @@ -455,7 +468,8 @@ protected virtual IEnumerable Remove([NotNull] IModel source /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - protected virtual IEnumerable Diff([NotNull] IEnumerable source, [NotNull] IEnumerable target, [NotNull] DiffContext diffContext) + protected virtual IEnumerable Diff( + [NotNull] IEnumerable source, [NotNull] IEnumerable target, [NotNull] DiffContext diffContext) => DiffCollection( source, target, @@ -471,7 +485,8 @@ protected virtual IEnumerable Diff([NotNull] IEnumerable - protected virtual IEnumerable Diff([NotNull] string source, [NotNull] string target, [NotNull] DiffContext diffContext) + protected virtual IEnumerable Diff( + [NotNull] string source, [NotNull] string target, [NotNull] DiffContext diffContext) => Enumerable.Empty(); /// @@ -482,10 +497,7 @@ protected virtual IEnumerable Diff([NotNull] string source, /// protected virtual IEnumerable Add([NotNull] string target, [NotNull] DiffContext diffContext) { - yield return new EnsureSchemaOperation - { - Name = target - }; + yield return new EnsureSchemaOperation { Name = target }; } /// @@ -552,10 +564,7 @@ protected virtual IEnumerable Diff( { yield return new RenameTableOperation { - Schema = source.Schema, - Name = source.Name, - NewSchema = target.Schema, - NewName = target.Name + Schema = source.Schema, Name = source.Name, NewSchema = target.Schema, NewName = target.Name }; } @@ -571,10 +580,7 @@ protected virtual IEnumerable Diff( Name = target.Name, Schema = target.Schema, Comment = target.GetComment(), - OldTable = - { - Comment = source.GetComment() - } + OldTable = { Comment = source.GetComment() } }; alterTableOperation.AddAnnotations(targetMigrationsAnnotations); @@ -608,9 +614,7 @@ protected virtual IEnumerable Add( var entityType = target.EntityTypes[0]; var createTableOperation = new CreateTableOperation { - Schema = target.Schema, - Name = target.Name, - Comment = target.GetComment() + Schema = target.Schema, Name = target.Name, Comment = target.GetComment() }; createTableOperation.AddAnnotations(MigrationsAnnotations.For(entityType)); @@ -621,6 +625,7 @@ protected virtual IEnumerable Add( { createTableOperation.PrimaryKey = Add(primaryKey, diffContext).Cast().Single(); } + createTableOperation.UniqueConstraints.AddRange( target.GetKeys().Where(k => !k.IsPrimaryKey()).SelectMany(k => Add(k, diffContext)) .Cast()); @@ -650,11 +655,7 @@ protected virtual IEnumerable Add( protected virtual IEnumerable Remove( [NotNull] TableMapping source, [NotNull] DiffContext diffContext) { - var operation = new DropTableOperation - { - Schema = source.Schema, - Name = source.Name - }; + var operation = new DropTableOperation { Schema = source.Schema, Name = source.Name }; operation.AddAnnotations(MigrationsAnnotations.ForRemove(source.EntityTypes[0])); diffContext.AddDrop(source, operation); @@ -709,10 +710,7 @@ private static IEnumerable GetSortedProperties(IEntityType entityType } groups.Add( - clrProperty, new List - { - property - }); + clrProperty, new List { property }); } var clrType = clrProperty.DeclaringType; @@ -912,7 +910,8 @@ private static string GetDefiningNavigationName(IEntityType entityType) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - protected virtual IEnumerable Diff([NotNull] IProperty source, [NotNull] IProperty target, [NotNull] DiffContext diffContext) + protected virtual IEnumerable Diff( + [NotNull] IProperty source, [NotNull] IProperty target, [NotNull] DiffContext diffContext) { var targetEntityType = target.DeclaringEntityType.GetRootType(); @@ -990,9 +989,7 @@ protected virtual IEnumerable Add( var operation = new AddColumnOperation { - Schema = targetEntityType.GetSchema(), - Table = targetEntityType.GetTableName(), - Name = target.GetColumnName() + Schema = targetEntityType.GetSchema(), Table = targetEntityType.GetTableName(), Name = target.GetColumnName() }; Initialize( @@ -1014,9 +1011,7 @@ protected virtual IEnumerable Remove([NotNull] IProperty sou var operation = new DropColumnOperation { - Schema = sourceEntityType.GetSchema(), - Table = sourceEntityType.GetTableName(), - Name = source.GetColumnName() + Schema = sourceEntityType.GetSchema(), Table = sourceEntityType.GetTableName(), Name = source.GetColumnName() }; operation.AddAnnotations(MigrationsAnnotations.ForRemove(source)); @@ -1150,18 +1145,14 @@ protected virtual IEnumerable Remove( { operation = new DropPrimaryKeyOperation { - Schema = sourceEntityType.GetSchema(), - Table = sourceEntityType.GetTableName(), - Name = source.GetName() + Schema = sourceEntityType.GetSchema(), Table = sourceEntityType.GetTableName(), Name = source.GetName() }; } else { operation = new DropUniqueConstraintOperation { - Schema = sourceEntityType.GetSchema(), - Table = sourceEntityType.GetTableName(), - Name = source.GetName() + Schema = sourceEntityType.GetSchema(), Table = sourceEntityType.GetTableName(), Name = source.GetName() }; } @@ -1371,9 +1362,7 @@ protected virtual IEnumerable Remove([NotNull] IIndex source var operation = new DropIndexOperation { - Name = source.GetName(), - Schema = sourceEntityType.GetSchema(), - Table = sourceEntityType.GetTableName() + Name = source.GetName(), Schema = sourceEntityType.GetSchema(), Table = sourceEntityType.GetTableName() }; operation.AddAnnotations(MigrationsAnnotations.ForRemove(source)); @@ -1427,10 +1416,7 @@ protected virtual IEnumerable Add([NotNull] ICheckConstraint var operation = new CreateCheckConstraintOperation { - Name = target.Name, - Sql = target.Sql, - Schema = targetEntityType.GetSchema(), - Table = targetEntityType.GetTableName() + Name = target.Name, Sql = target.Sql, Schema = targetEntityType.GetSchema(), Table = targetEntityType.GetTableName() }; operation.Sql = target.Sql; @@ -1451,9 +1437,7 @@ protected virtual IEnumerable Remove([NotNull] ICheckConstra var operation = new DropCheckConstraintOperation { - Name = source.Name, - Schema = sourceEntityType.GetSchema(), - Table = sourceEntityType.GetTableName() + Name = source.Name, Schema = sourceEntityType.GetSchema(), Table = sourceEntityType.GetTableName() }; operation.AddAnnotations(MigrationsAnnotations.ForRemove(source)); @@ -1493,28 +1477,21 @@ protected virtual IEnumerable Diff( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - protected virtual IEnumerable Diff([NotNull] ISequence source, [NotNull] ISequence target, [NotNull] DiffContext diffContext) + protected virtual IEnumerable Diff( + [NotNull] ISequence source, [NotNull] ISequence target, [NotNull] DiffContext diffContext) { if (source.Schema != target.Schema || source.Name != target.Name) { yield return new RenameSequenceOperation { - Schema = source.Schema, - Name = source.Name, - NewSchema = target.Schema, - NewName = target.Name + Schema = source.Schema, Name = source.Name, NewSchema = target.Schema, NewName = target.Name }; } if (source.StartValue != target.StartValue) { - yield return new RestartSequenceOperation - { - Schema = target.Schema, - Name = target.Name, - StartValue = target.StartValue - }; + yield return new RestartSequenceOperation { Schema = target.Schema, Name = target.Name, StartValue = target.StartValue }; } var sourceMigrationsAnnotations = MigrationsAnnotations.For(source).ToList(); @@ -1526,11 +1503,7 @@ protected virtual IEnumerable Diff([NotNull] ISequence sourc || source.IsCyclic != target.IsCyclic || HasDifferences(sourceMigrationsAnnotations, targetMigrationsAnnotations)) { - var alterSequenceOperation = new AlterSequenceOperation - { - Schema = target.Schema, - Name = target.Name - }; + var alterSequenceOperation = new AlterSequenceOperation { Schema = target.Schema, Name = target.Name }; Initialize(alterSequenceOperation, target, targetMigrationsAnnotations); Initialize(alterSequenceOperation.OldSequence, source, sourceMigrationsAnnotations); @@ -1549,10 +1522,7 @@ protected virtual IEnumerable Add([NotNull] ISequence target { var operation = new CreateSequenceOperation { - Schema = target.Schema, - Name = target.Name, - ClrType = target.ClrType, - StartValue = target.StartValue + Schema = target.Schema, Name = target.Name, ClrType = target.ClrType, StartValue = target.StartValue }; yield return Initialize(operation, target, MigrationsAnnotations.For(target)); @@ -1566,11 +1536,7 @@ protected virtual IEnumerable Add([NotNull] ISequence target /// protected virtual IEnumerable Remove([NotNull] ISequence source, [NotNull] DiffContext diffContext) { - var operation = new DropSequenceOperation - { - Schema = source.Schema, - Name = source.Name - }; + var operation = new DropSequenceOperation { Schema = source.Schema, Name = source.Name }; operation.AddAnnotations(MigrationsAnnotations.ForRemove(source)); yield return operation; @@ -1830,7 +1796,8 @@ var modelValuesChanged var convertedType = sourceConverter?.ProviderClrType ?? targetConverter?.ProviderClrType; - var storeValuesChanged = convertedSourceValue?.GetType().UnwrapNullableType() != convertedTargetValue?.GetType().UnwrapNullableType(); + var storeValuesChanged = convertedSourceValue?.GetType().UnwrapNullableType() + != convertedTargetValue?.GetType().UnwrapNullableType(); if (!storeValuesChanged && convertedType != null) @@ -1962,7 +1929,8 @@ protected virtual IEnumerable GetDataOperations([NotNull] Di { batchInsertOperation.Values = AddToMultidimensionalArray( - c.ColumnModifications.Where(col => col.IsKey || col.IsWrite).Select(GetValue).ToList(), batchInsertOperation.Values); + c.ColumnModifications.Where(col => col.IsKey || col.IsWrite).Select(GetValue).ToList(), + batchInsertOperation.Values); continue; } @@ -1973,7 +1941,8 @@ protected virtual IEnumerable GetDataOperations([NotNull] Di { Schema = c.Schema, Table = c.TableName, - Columns = c.ColumnModifications.Where(col => col.IsKey || col.IsWrite).Select(col => col.ColumnName).ToArray(), + Columns = c.ColumnModifications.Where(col => col.IsKey || col.IsWrite).Select(col => col.ColumnName) + .ToArray(), Values = ToMultidimensionalArray( c.ColumnModifications.Where(col => col.IsKey || col.IsWrite).Select(GetValue).ToList()) }; @@ -2129,7 +2098,8 @@ protected virtual bool HasDifferences([NotNull] IEnumerable source, foreach (var annotation in source) { - var index = unmatched.FindIndex(a => a.Name == annotation.Name && StructuralComparisons.StructuralEqualityComparer.Equals(a.Value, annotation.Value)); + var index = unmatched.FindIndex( + a => a.Name == annotation.Name && StructuralComparisons.StructuralEqualityComparer.Equals(a.Value, annotation.Value)); if (index == -1) { return true; diff --git a/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs b/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs index e3f0a0c7fac..3a5c86a6825 100644 --- a/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs +++ b/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs @@ -27,8 +27,8 @@ public virtual SqlExpression Translate(SqlExpression instance, MethodInfo method } if ((method.DeclaringType.GetInterfaces().Contains(typeof(IList)) - || method.DeclaringType.IsGenericType - && method.DeclaringType.GetGenericTypeDefinition() == typeof(ICollection<>)) + || method.DeclaringType.IsGenericType + && method.DeclaringType.GetGenericTypeDefinition() == typeof(ICollection<>)) && string.Equals(method.Name, nameof(IList.Contains))) { return _sqlExpressionFactory.In(arguments[0], instance, false); diff --git a/src/EFCore.Relational/Query/Internal/SqlExpressionOptimizingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/SqlExpressionOptimizingExpressionVisitor.cs index 163e5f472f5..7a2969d0b03 100644 --- a/src/EFCore.Relational/Query/Internal/SqlExpressionOptimizingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/SqlExpressionOptimizingExpressionVisitor.cs @@ -13,15 +13,16 @@ public class SqlExpressionOptimizingExpressionVisitor : ExpressionVisitor private static bool TryNegate(ExpressionType expressionType, out ExpressionType result) { - var negated = expressionType switch { - ExpressionType.AndAlso => ExpressionType.OrElse, - ExpressionType.OrElse => ExpressionType.AndAlso, - ExpressionType.Equal => ExpressionType.NotEqual, - ExpressionType.NotEqual => ExpressionType.Equal, - ExpressionType.GreaterThan => ExpressionType.LessThanOrEqual, + var negated = expressionType switch + { + ExpressionType.AndAlso => ExpressionType.OrElse, + ExpressionType.OrElse => ExpressionType.AndAlso, + ExpressionType.Equal => ExpressionType.NotEqual, + ExpressionType.NotEqual => ExpressionType.Equal, + ExpressionType.GreaterThan => ExpressionType.LessThanOrEqual, ExpressionType.GreaterThanOrEqual => ExpressionType.LessThan, - ExpressionType.LessThan => ExpressionType.GreaterThanOrEqual, - ExpressionType.LessThanOrEqual => ExpressionType.GreaterThan, + ExpressionType.LessThan => ExpressionType.GreaterThanOrEqual, + ExpressionType.LessThanOrEqual => ExpressionType.GreaterThan, _ => (ExpressionType?)null }; @@ -40,11 +41,11 @@ public SqlExpressionOptimizingExpressionVisitor(ISqlExpressionFactory sqlExpress protected override Expression VisitExtension(Expression extensionExpression) => extensionExpression switch - { - SqlUnaryExpression sqlUnaryExpression => VisitSqlUnaryExpression(sqlUnaryExpression), - SqlBinaryExpression sqlBinaryExpression => VisitSqlBinaryExpression(sqlBinaryExpression), - _ => base.VisitExtension(extensionExpression), - }; + { + SqlUnaryExpression sqlUnaryExpression => VisitSqlUnaryExpression(sqlUnaryExpression), + SqlBinaryExpression sqlBinaryExpression => VisitSqlBinaryExpression(sqlBinaryExpression), + _ => base.VisitExtension(extensionExpression), + }; protected virtual Expression VisitSqlUnaryExpression(SqlUnaryExpression sqlUnaryExpression) { @@ -60,13 +61,13 @@ protected virtual Expression VisitSqlUnaryExpression(SqlUnaryExpression sqlUnary return SqlExpressionFactory.Constant(constantOperand.Value == null, sqlUnaryExpression.TypeMapping); case ColumnExpression columnOperand - when !columnOperand.IsNullable: + when !columnOperand.IsNullable: return SqlExpressionFactory.Constant(false, sqlUnaryExpression.TypeMapping); case SqlUnaryExpression sqlUnaryOperand - when sqlUnaryOperand.OperatorType == ExpressionType.Convert - || sqlUnaryOperand.OperatorType == ExpressionType.Not - || sqlUnaryOperand.OperatorType == ExpressionType.Negate: + when sqlUnaryOperand.OperatorType == ExpressionType.Convert + || sqlUnaryOperand.OperatorType == ExpressionType.Not + || sqlUnaryOperand.OperatorType == ExpressionType.Negate: return (SqlExpression)Visit(SqlExpressionFactory.IsNull(sqlUnaryOperand.Operand)); case SqlBinaryExpression sqlBinaryOperand: @@ -74,9 +75,12 @@ protected virtual Expression VisitSqlUnaryExpression(SqlUnaryExpression sqlUnary var newRight = (SqlExpression)Visit(SqlExpressionFactory.IsNull(sqlBinaryOperand.Right)); return sqlBinaryOperand.OperatorType == ExpressionType.Coalesce - ? SimplifyLogicalSqlBinaryExpression(ExpressionType.AndAlso, newLeft, newRight, sqlBinaryOperand.TypeMapping) - : SimplifyLogicalSqlBinaryExpression(ExpressionType.OrElse, newLeft, newRight, sqlBinaryOperand.TypeMapping); + ? SimplifyLogicalSqlBinaryExpression( + ExpressionType.AndAlso, newLeft, newRight, sqlBinaryOperand.TypeMapping) + : SimplifyLogicalSqlBinaryExpression( + ExpressionType.OrElse, newLeft, newRight, sqlBinaryOperand.TypeMapping); } + break; case ExpressionType.NotEqual: @@ -86,13 +90,13 @@ protected virtual Expression VisitSqlUnaryExpression(SqlUnaryExpression sqlUnary return SqlExpressionFactory.Constant(constantOperand.Value != null, sqlUnaryExpression.TypeMapping); case ColumnExpression columnOperand - when !columnOperand.IsNullable: + when !columnOperand.IsNullable: return SqlExpressionFactory.Constant(true, sqlUnaryExpression.TypeMapping); case SqlUnaryExpression sqlUnaryOperand - when sqlUnaryOperand.OperatorType == ExpressionType.Convert - || sqlUnaryOperand.OperatorType == ExpressionType.Not - || sqlUnaryOperand.OperatorType == ExpressionType.Negate: + when sqlUnaryOperand.OperatorType == ExpressionType.Convert + || sqlUnaryOperand.OperatorType == ExpressionType.Not + || sqlUnaryOperand.OperatorType == ExpressionType.Negate: return (SqlExpression)Visit(SqlExpressionFactory.IsNotNull(sqlUnaryOperand.Operand)); case SqlBinaryExpression sqlBinaryOperand: @@ -101,8 +105,10 @@ protected virtual Expression VisitSqlUnaryExpression(SqlUnaryExpression sqlUnary return sqlBinaryOperand.OperatorType == ExpressionType.Coalesce ? SimplifyLogicalSqlBinaryExpression(ExpressionType.OrElse, newLeft, newRight, sqlBinaryOperand.TypeMapping) - : SimplifyLogicalSqlBinaryExpression(ExpressionType.AndAlso, newLeft, newRight, sqlBinaryOperand.TypeMapping); + : SimplifyLogicalSqlBinaryExpression( + ExpressionType.AndAlso, newLeft, newRight, sqlBinaryOperand.TypeMapping); } + break; } @@ -169,7 +175,8 @@ private Expression VisitNot(SqlUnaryExpression sqlUnaryExpression) // they are safe to do here because null semantics removes possibility of nulls in the tree // however if we decide to do "partial" null semantics (that doesn't distinguish between NULL and FALSE, e.g. for predicates) // we need to be extra careful here - if (!_useRelationalNulls && TryNegate(innerBinary.OperatorType, out var negated)) + if (!_useRelationalNulls + && TryNegate(innerBinary.OperatorType, out var negated)) { return Visit( SqlExpressionFactory.MakeBinary( @@ -205,7 +212,8 @@ private Expression VisitSqlBinaryExpression(SqlBinaryExpression sqlBinaryExpress // however if we decide to do "partial" null semantics (that doesn't distinguish between NULL and FALSE, e.g. for predicates) // we need to be extra careful here if (!_useRelationalNulls - && (sqlBinaryExpression.OperatorType == ExpressionType.Equal || sqlBinaryExpression.OperatorType == ExpressionType.NotEqual)) + && (sqlBinaryExpression.OperatorType == ExpressionType.Equal + || sqlBinaryExpression.OperatorType == ExpressionType.NotEqual)) { // op(a, b) == true -> op(a, b) // op(a, b) != false -> op(a, b) @@ -213,7 +221,9 @@ private Expression VisitSqlBinaryExpression(SqlBinaryExpression sqlBinaryExpress // op(a, b) != true -> !op(a, b) var constant = sqlBinaryExpression.Left as SqlConstantExpression ?? sqlBinaryExpression.Right as SqlConstantExpression; var binary = sqlBinaryExpression.Left as SqlBinaryExpression ?? sqlBinaryExpression.Right as SqlBinaryExpression; - if (constant != null && binary != null && TryNegate(binary.OperatorType, out var negated)) + if (constant != null + && binary != null + && TryNegate(binary.OperatorType, out var negated)) { return (bool)constant.Value == (sqlBinaryExpression.OperatorType == ExpressionType.Equal) ? binary @@ -248,7 +258,8 @@ private SqlExpression SimplifyLogicalSqlBinaryExpression( ? newLeftConstant : newRight; } - else if (newRight is SqlConstantExpression newRightConstant) + + if (newRight is SqlConstantExpression newRightConstant) { // a && true -> a // a || true -> true diff --git a/src/EFCore.Relational/Query/QuerySqlGenerator.cs b/src/EFCore.Relational/Query/QuerySqlGenerator.cs index 6c11f6228b5..afacb5b3cc6 100644 --- a/src/EFCore.Relational/Query/QuerySqlGenerator.cs +++ b/src/EFCore.Relational/Query/QuerySqlGenerator.cs @@ -17,6 +17,7 @@ public class QuerySqlGenerator : SqlExpressionVisitor { private static readonly Regex _composibleSql = new Regex(@"^\s*?SELECT\b", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(value: 1000.0)); + private readonly IRelationalCommandBuilderFactory _relationalCommandBuilderFactory; private readonly ISqlGenerationHelper _sqlGenerationHelper; private IRelationalCommandBuilder _relationalCommandBuilder; @@ -97,19 +98,21 @@ protected override Expression VisitSqlFragment(SqlFragmentExpression sqlFragment private bool IsNonComposedSetOperation(SelectExpression selectExpression) => selectExpression.Offset == null - && selectExpression.Limit == null - && !selectExpression.IsDistinct - && selectExpression.Predicate == null - && selectExpression.Having == null - && selectExpression.Orderings.Count == 0 - && selectExpression.GroupBy.Count == 0 - && selectExpression.Tables.Count == 1 - && selectExpression.Tables[0] is SetOperationBase setOperation - && selectExpression.Projection.Count == setOperation.Source1.Projection.Count - && selectExpression.Projection.Select((pe, index) => pe.Expression is ColumnExpression column - && string.Equals(column.Table.Alias, setOperation.Alias, StringComparison.OrdinalIgnoreCase) - && string.Equals(column.Name, setOperation.Source1.Projection[index].Alias, StringComparison.OrdinalIgnoreCase)) - .All(e => e); + && selectExpression.Limit == null + && !selectExpression.IsDistinct + && selectExpression.Predicate == null + && selectExpression.Having == null + && selectExpression.Orderings.Count == 0 + && selectExpression.GroupBy.Count == 0 + && selectExpression.Tables.Count == 1 + && selectExpression.Tables[0] is SetOperationBase setOperation + && selectExpression.Projection.Count == setOperation.Source1.Projection.Count + && selectExpression.Projection.Select( + (pe, index) => pe.Expression is ColumnExpression column + && string.Equals(column.Table.Alias, setOperation.Alias, StringComparison.OrdinalIgnoreCase) + && string.Equals( + column.Name, setOperation.Source1.Projection[index].Alias, StringComparison.OrdinalIgnoreCase)) + .All(e => e); protected override Expression VisitSelect(SelectExpression selectExpression) { diff --git a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs index c959ad0fb0b..4808b9218c4 100644 --- a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs @@ -6,7 +6,6 @@ using System.Diagnostics; using System.Linq; using System.Linq.Expressions; -using System.Reflection; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; @@ -257,7 +256,8 @@ protected override ShapedQueryExpression TranslateDistinct(ShapedQueryExpression return source; } - protected override ShapedQueryExpression TranslateElementAtOrDefault(ShapedQueryExpression source, Expression index, bool returnDefault) + protected override ShapedQueryExpression TranslateElementAtOrDefault( + ShapedQueryExpression source, Expression index, bool returnDefault) => null; protected override ShapedQueryExpression TranslateExcept(ShapedQueryExpression source1, ShapedQueryExpression source2) @@ -320,10 +320,7 @@ protected override ShapedQueryExpression TranslateGroupBy( var original2 = resultSelector.Parameters[1]; var newResultSelectorBody = new ReplacingExpressionVisitor( - new Dictionary - { - { original1, translatedKey }, { original2, source.ShaperExpression } - }) + new Dictionary { { original1, translatedKey }, { original2, source.ShaperExpression } }) .Visit(resultSelector.Body); newResultSelectorBody = ExpandWeakEntities(selectExpression, newResultSelectorBody); @@ -587,10 +584,7 @@ protected override ShapedQueryExpression TranslateLongCount(ShapedQueryExpressio return null; } - var projectionMapping = new Dictionary - { - { new ProjectionMember(), translation } - }; + var projectionMapping = new Dictionary { { new ProjectionMember(), translation } }; selectExpression.ClearOrdering(); selectExpression.ReplaceProjectionMapping(projectionMapping); diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.InExpressionValuesExpandingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.InExpressionValuesExpandingExpressionVisitor.cs index 094c44a62e4..2f4690b1d3d 100644 --- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.InExpressionValuesExpandingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.InExpressionValuesExpandingExpressionVisitor.cs @@ -48,7 +48,7 @@ public override Expression Visit(Expression expression) inValues.Add(value); } - + break; } @@ -66,7 +66,7 @@ public override Expression Visit(Expression expression) inValues.Add(value); } - + break; } } diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ParameterNullabilityOptimizingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ParameterNullabilityOptimizingExpressionVisitor.cs index 993dbe30b46..82a1cc5c26d 100644 --- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ParameterNullabilityOptimizingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ParameterNullabilityOptimizingExpressionVisitor.cs @@ -32,7 +32,7 @@ protected override Expression VisitExtension(Expression extensionExpression) // if predicate is optimized to true, we can simply remove it var newPredicate = newSelectExpression.Predicate is SqlConstantExpression newSelectPredicateConstant - && !(selectExpression.Predicate is SqlConstantExpression) + && !(selectExpression.Predicate is SqlConstantExpression) ? (bool)newSelectPredicateConstant.Value ? null : SqlExpressionFactory.Equal( @@ -41,7 +41,7 @@ protected override Expression VisitExtension(Expression extensionExpression) : newSelectExpression.Predicate; var newHaving = newSelectExpression.Having is SqlConstantExpression newSelectHavingConstant - && !(selectExpression.Having is SqlConstantExpression) + && !(selectExpression.Having is SqlConstantExpression) ? (bool)newSelectHavingConstant.Value ? null : SqlExpressionFactory.Equal( @@ -50,7 +50,7 @@ protected override Expression VisitExtension(Expression extensionExpression) : newSelectExpression.Having; return newPredicate != newSelectExpression.Predicate - || newHaving != newSelectExpression.Having + || newHaving != newSelectExpression.Having ? newSelectExpression.Update( newSelectExpression.Projection.ToList(), newSelectExpression.Tables.ToList(), diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ParameterValueBasedSelectExpressionOptimizer.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ParameterValueBasedSelectExpressionOptimizer.cs index f853136a736..918c5e7386f 100644 --- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ParameterValueBasedSelectExpressionOptimizer.cs +++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ParameterValueBasedSelectExpressionOptimizer.cs @@ -25,7 +25,8 @@ public ParameterValueBasedSelectExpressionOptimizer( _useRelationalNulls = useRelationalNulls; } - public (SelectExpression selectExpression, bool canCache) Optimize(SelectExpression selectExpression, IReadOnlyDictionary parametersValues) + public (SelectExpression selectExpression, bool canCache) Optimize( + SelectExpression selectExpression, IReadOnlyDictionary parametersValues) { var canCache = true; diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.QueryingEnumerable.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.QueryingEnumerable.cs index 1fa982a1c91..d24f08c9656 100644 --- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.QueryingEnumerable.cs +++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.QueryingEnumerable.cs @@ -39,8 +39,10 @@ public QueryingEnumerable( _contextType = contextType; _logger = logger; } + public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) => new AsyncEnumerator(this, cancellationToken); + public IEnumerator GetEnumerator() => new Enumerator(this); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.RelationalCommandCache.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.RelationalCommandCache.cs index a4f4d8a3108..0143e957099 100644 --- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.RelationalCommandCache.cs +++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.RelationalCommandCache.cs @@ -16,6 +16,7 @@ private class RelationalCommandCache { private static readonly ConcurrentDictionary _syncObjects = new ConcurrentDictionary(); + private readonly IMemoryCache _memoryCache; private readonly ISqlExpressionFactory _sqlExpressionFactory; @@ -59,8 +60,8 @@ public virtual IRelationalCommand GetRelationalCommand(IReadOnlyDictionary ApplyTypeMappingOnCase(e, typeMapping), - LikeExpression e => ApplyTypeMappingOnLike(e), - SqlBinaryExpression e => ApplyTypeMappingOnSqlBinary(e, typeMapping), - SqlUnaryExpression e => ApplyTypeMappingOnSqlUnary(e, typeMapping), - SqlConstantExpression e => e.ApplyTypeMapping(typeMapping), - SqlFragmentExpression e => e, - SqlFunctionExpression e => e.ApplyTypeMapping(typeMapping), + CaseExpression e => ApplyTypeMappingOnCase(e, typeMapping), + LikeExpression e => ApplyTypeMappingOnLike(e), + SqlBinaryExpression e => ApplyTypeMappingOnSqlBinary(e, typeMapping), + SqlUnaryExpression e => ApplyTypeMappingOnSqlUnary(e, typeMapping), + SqlConstantExpression e => e.ApplyTypeMapping(typeMapping), + SqlFragmentExpression e => e, + SqlFunctionExpression e => e.ApplyTypeMapping(typeMapping), SqlParameterExpression e => e.ApplyTypeMapping(typeMapping), - _ => sqlExpression + _ => sqlExpression }; } private SqlExpression ApplyTypeMappingOnLike(LikeExpression likeExpression) { var inferredTypeMapping = (likeExpression.EscapeChar == null - ? ExpressionExtensions.InferTypeMapping( - likeExpression.Match, likeExpression.Pattern) - : ExpressionExtensions.InferTypeMapping( - likeExpression.Match, likeExpression.Pattern, likeExpression.EscapeChar)) - ?? _typeMappingSource.FindMapping(likeExpression.Match.Type); + ? ExpressionExtensions.InferTypeMapping( + likeExpression.Match, likeExpression.Pattern) + : ExpressionExtensions.InferTypeMapping( + likeExpression.Match, likeExpression.Pattern, likeExpression.EscapeChar)) + ?? _typeMappingSource.FindMapping(likeExpression.Match.Type); return new LikeExpression( ApplyTypeMapping(likeExpression.Match, inferredTypeMapping), diff --git a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs index a7582ef1eaa..bebe7c791cd 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs @@ -93,16 +93,17 @@ private SelectExpression(IEntityType entityType, TableExpressionBase tableExpres public bool IsNonComposedFromSql() => Limit == null - && Offset == null - && !IsDistinct - && Predicate == null - && GroupBy.Count == 0 - && Having == null - && Orderings.Count == 0 - && Tables.Count == 1 - && Tables[0] is FromSqlExpression fromSql - && Projection.All(pe => pe.Expression is ColumnExpression column - && string.Equals(fromSql.Alias, column.Table.Alias, StringComparison.OrdinalIgnoreCase)); + && Offset == null + && !IsDistinct + && Predicate == null + && GroupBy.Count == 0 + && Having == null + && Orderings.Count == 0 + && Tables.Count == 1 + && Tables[0] is FromSqlExpression fromSql + && Projection.All( + pe => pe.Expression is ColumnExpression column + && string.Equals(fromSql.Alias, column.Table.Alias, StringComparison.OrdinalIgnoreCase)); public void ApplyProjection() { @@ -492,13 +493,13 @@ private void ApplySetOperation(SetOperationType setOperationType, SelectExpressi select2.ClearOrdering(); } - var setExpression = (SetOperationBase)(setOperationType switch + var setExpression = setOperationType switch { - SetOperationType.Except => new ExceptExpression("t", select1, select2, distinct), + SetOperationType.Except => (SetOperationBase)new ExceptExpression("t", select1, select2, distinct), SetOperationType.Intersect => new IntersectExpression("t", select1, select2, distinct), SetOperationType.Union => new UnionExpression("t", select1, select2, distinct), _ => throw new InvalidOperationException($"Invalid {nameof(setOperationType)}: {setOperationType}") - }); + }; if (_projection.Any() || select2._projection.Any()) @@ -997,7 +998,10 @@ private SqlExpression TryExtractJoinKey(SelectExpression selectExpression) } private SqlExpression TryExtractJoinKey( - SelectExpression selectExpression, SqlExpression predicate, List columnExpressions, out SqlExpression updatedPredicate) + SelectExpression selectExpression, + SqlExpression predicate, + List columnExpressions, + out SqlExpression updatedPredicate) { if (predicate is SqlBinaryExpression sqlBinaryExpression) { @@ -1011,8 +1015,10 @@ private SqlExpression TryExtractJoinKey( if (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso) { - var leftJoinKey = TryExtractJoinKey(selectExpression, sqlBinaryExpression.Left, columnExpressions, out var leftPredicate); - var rightJoinKey = TryExtractJoinKey(selectExpression, sqlBinaryExpression.Right, columnExpressions, out var rightPredicate); + var leftJoinKey = TryExtractJoinKey( + selectExpression, sqlBinaryExpression.Left, columnExpressions, out var leftPredicate); + var rightJoinKey = TryExtractJoinKey( + selectExpression, sqlBinaryExpression.Right, columnExpressions, out var rightPredicate); updatedPredicate = CombineNonNullExpressions(leftPredicate, rightPredicate); @@ -1026,13 +1032,14 @@ private SqlExpression TryExtractJoinKey( } private static SqlExpression CombineNonNullExpressions(SqlExpression left, SqlExpression right) - => left != null - ? right != null - ? new SqlBinaryExpression(ExpressionType.AndAlso, left, right, left.Type, left.TypeMapping) - : left - : right; - - private SqlBinaryExpression ValidateKeyComparison(SelectExpression inner, SqlBinaryExpression sqlBinaryExpression, List columnExpressions) + => left != null + ? right != null + ? new SqlBinaryExpression(ExpressionType.AndAlso, left, right, left.Type, left.TypeMapping) + : left + : right; + + private SqlBinaryExpression ValidateKeyComparison( + SelectExpression inner, SqlBinaryExpression sqlBinaryExpression, List columnExpressions) { if (sqlBinaryExpression.OperatorType == ExpressionType.Equal) { @@ -1266,15 +1273,15 @@ private void AddJoin( } var innerTable = innerSelectExpression.Tables.Single(); - var joinTable = (TableExpressionBase)(joinType switch + var joinTable = joinType switch { JoinType.InnerJoin => new InnerJoinExpression(innerTable, joinPredicate), JoinType.LeftJoin => new LeftJoinExpression(innerTable, joinPredicate), JoinType.CrossJoin => new CrossJoinExpression(innerTable), JoinType.CrossApply => new CrossApplyExpression(innerTable), - JoinType.OuterApply => new OuterApplyExpression(innerTable), + JoinType.OuterApply => (TableExpressionBase)new OuterApplyExpression(innerTable), _ => throw new InvalidOperationException($"Invalid {nameof(joinType)}: {joinType}") - }); + }; _tables.Add(joinTable); @@ -1408,159 +1415,161 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) return this; } - else - { - var changed = false; - var newProjections = _projection; - var newProjectionMapping = _projectionMapping; - if (_projection.Any()) + var changed = false; + + var newProjections = _projection; + var newProjectionMapping = _projectionMapping; + if (_projection.Any()) + { + for (var i = 0; i < _projection.Count; i++) { - for (var i = 0; i < _projection.Count; i++) + var item = _projection[i]; + var projection = (ProjectionExpression)visitor.Visit(item); + if (projection != item + && newProjections == _projection) { - var item = _projection[i]; - var projection = (ProjectionExpression)visitor.Visit(item); - if (projection != item - && newProjections == _projection) + newProjections = new List(_projection.Count); + for (var j = 0; j < i; j++) { - newProjections = new List(_projection.Count); - for (var j = 0; j < i; j++) - { - newProjections.Add(_projection[j]); - } - changed = true; + newProjections.Add(_projection[j]); } - if (newProjections != _projection) - { - newProjections.Add(projection); - } + changed = true; } - } - else - { - foreach (var mapping in _projectionMapping) - { - var newProjection = visitor.Visit(mapping.Value); - if (newProjection != mapping.Value - && newProjectionMapping == _projectionMapping) - { - newProjectionMapping = new Dictionary(_projectionMapping); - changed = true; - } - if (newProjectionMapping != _projectionMapping) - { - newProjectionMapping[mapping.Key] = newProjection; - } + if (newProjections != _projection) + { + newProjections.Add(projection); } } - - var newTables = _tables; - for (var i = 0; i < _tables.Count; i++) + } + else + { + foreach (var mapping in _projectionMapping) { - var table = _tables[i]; - var newTable = (TableExpressionBase)visitor.Visit(table); - if (newTable != table - && newTables == _tables) + var newProjection = visitor.Visit(mapping.Value); + if (newProjection != mapping.Value + && newProjectionMapping == _projectionMapping) { - newTables = new List(_tables.Count); - for (var j = 0; j < i; j++) - { - newTables.Add(_tables[j]); - } + newProjectionMapping = new Dictionary(_projectionMapping); changed = true; } - if (newTables != _tables) + if (newProjectionMapping != _projectionMapping) { - newTables.Add(newTable); + newProjectionMapping[mapping.Key] = newProjection; } } + } - var predicate = (SqlExpression)visitor.Visit(Predicate); - changed |= predicate != Predicate; - - var newGroupBy = _groupBy; - for (var i = 0; i < _groupBy.Count; i++) + var newTables = _tables; + for (var i = 0; i < _tables.Count; i++) + { + var table = _tables[i]; + var newTable = (TableExpressionBase)visitor.Visit(table); + if (newTable != table + && newTables == _tables) { - var groupingKey = _groupBy[i]; - var newGroupingKey = (SqlExpression)visitor.Visit(groupingKey); - if (newGroupingKey != groupingKey - || newGroupingKey is SqlConstantExpression - || newGroupingKey is SqlParameterExpression) + newTables = new List(_tables.Count); + for (var j = 0; j < i; j++) { - if (newGroupBy == _groupBy) - { - newGroupBy = new List(_groupBy.Count); - for (var j = 0; j < i; j++) - { - newGroupBy.Add(_groupBy[j]); - } - } - changed = true; + newTables.Add(_tables[j]); } - if (newGroupBy != _groupBy && - !(newGroupingKey is SqlConstantExpression - || newGroupingKey is SqlParameterExpression)) - { - newGroupBy.Add(newGroupingKey); - } + changed = true; } - var havingExpression = (SqlExpression)visitor.Visit(Having); - changed |= havingExpression != Having; + if (newTables != _tables) + { + newTables.Add(newTable); + } + } - var newOrderings = _orderings; - for (var i = 0; i < _orderings.Count; i++) + var predicate = (SqlExpression)visitor.Visit(Predicate); + changed |= predicate != Predicate; + + var newGroupBy = _groupBy; + for (var i = 0; i < _groupBy.Count; i++) + { + var groupingKey = _groupBy[i]; + var newGroupingKey = (SqlExpression)visitor.Visit(groupingKey); + if (newGroupingKey != groupingKey + || newGroupingKey is SqlConstantExpression + || newGroupingKey is SqlParameterExpression) { - var ordering = _orderings[i]; - var newOrdering = (OrderingExpression)visitor.Visit(ordering); - if (newOrdering != ordering - && newOrderings == _orderings) + if (newGroupBy == _groupBy) { - newOrderings = new List(_orderings.Count); + newGroupBy = new List(_groupBy.Count); for (var j = 0; j < i; j++) { - newOrderings.Add(_orderings[j]); + newGroupBy.Add(_groupBy[j]); } - changed = true; } - if (newOrderings != _orderings) - { - newOrderings.Add(newOrdering); - } + changed = true; } - var offset = (SqlExpression)visitor.Visit(Offset); - changed |= offset != Offset; + if (newGroupBy != _groupBy + && !(newGroupingKey is SqlConstantExpression + || newGroupingKey is SqlParameterExpression)) + { + newGroupBy.Add(newGroupingKey); + } + } - var limit = (SqlExpression)visitor.Visit(Limit); - changed |= limit != Limit; + var havingExpression = (SqlExpression)visitor.Visit(Having); + changed |= havingExpression != Having; - if (changed) + var newOrderings = _orderings; + for (var i = 0; i < _orderings.Count; i++) + { + var ordering = _orderings[i]; + var newOrdering = (OrderingExpression)visitor.Visit(ordering); + if (newOrdering != ordering + && newOrderings == _orderings) { - var newSelectExpression = new SelectExpression(Alias, newProjections, newTables, newGroupBy, newOrderings) + newOrderings = new List(_orderings.Count); + for (var j = 0; j < i; j++) { - _projectionMapping = newProjectionMapping, - Predicate = predicate, - Having = havingExpression, - Offset = offset, - Limit = limit, - IsDistinct = IsDistinct, - Tags = Tags - }; - - newSelectExpression._identifier.AddRange(_identifier); - newSelectExpression._identifier.AddRange(_childIdentifiers); - - return newSelectExpression; + newOrderings.Add(_orderings[j]); + } + + changed = true; } - return this; + if (newOrderings != _orderings) + { + newOrderings.Add(newOrdering); + } + } + + var offset = (SqlExpression)visitor.Visit(Offset); + changed |= offset != Offset; + + var limit = (SqlExpression)visitor.Visit(Limit); + changed |= limit != Limit; + + if (changed) + { + var newSelectExpression = new SelectExpression(Alias, newProjections, newTables, newGroupBy, newOrderings) + { + _projectionMapping = newProjectionMapping, + Predicate = predicate, + Having = havingExpression, + Offset = offset, + Limit = limit, + IsDistinct = IsDistinct, + Tags = Tags + }; + + newSelectExpression._identifier.AddRange(_identifier); + newSelectExpression._identifier.AddRange(_childIdentifiers); + + return newSelectExpression; } + + return this; } public override bool Equals(object obj) diff --git a/src/EFCore.Relational/Storage/Internal/DbParameterCollectionExtensions.cs b/src/EFCore.Relational/Storage/Internal/DbParameterCollectionExtensions.cs index ad33a32a6d0..9475ec06abb 100644 --- a/src/EFCore.Relational/Storage/Internal/DbParameterCollectionExtensions.cs +++ b/src/EFCore.Relational/Storage/Internal/DbParameterCollectionExtensions.cs @@ -134,7 +134,8 @@ public static string FormatParameter( private static void FormatParameterValue(StringBuilder builder, object parameterValue) { - if (parameterValue == null || parameterValue == DBNull.Value) + if (parameterValue == null + || parameterValue == DBNull.Value) { builder.Append("NULL"); } diff --git a/src/EFCore.Relational/Update/ColumnModification.cs b/src/EFCore.Relational/Update/ColumnModification.cs index 6f61b93c0a2..73dd9ea5b1f 100644 --- a/src/EFCore.Relational/Update/ColumnModification.cs +++ b/src/EFCore.Relational/Update/ColumnModification.cs @@ -189,7 +189,9 @@ public virtual object Value { get => Entry == null ? _value - : Entry.EntityState == EntityState.Deleted ? null : Entry.GetCurrentValue(Property); + : Entry.EntityState == EntityState.Deleted + ? null + : Entry.GetCurrentValue(Property); [param: CanBeNull] set { diff --git a/src/EFCore.Relational/Update/ModificationCommand.cs b/src/EFCore.Relational/Update/ModificationCommand.cs index 32ea0f66590..3bbe563e44c 100644 --- a/src/EFCore.Relational/Update/ModificationCommand.cs +++ b/src/EFCore.Relational/Update/ModificationCommand.cs @@ -192,16 +192,16 @@ public virtual void AddEntry([NotNull] IUpdateEntry entry, bool mainEntry) private void ValidateState(IUpdateEntry mainEntry, IUpdateEntry entry) { var mainEntryState = mainEntry.SharedIdentityEntry == null - ? mainEntry.EntityState - : EntityState.Modified; + ? mainEntry.EntityState + : EntityState.Modified; if (mainEntryState == EntityState.Modified) { return; } var entryState = entry.SharedIdentityEntry == null - ? entry.EntityState - : EntityState.Modified; + ? entry.EntityState + : EntityState.Modified; if (mainEntryState != entryState) { if (_sensitiveLoggingEnabled) @@ -257,8 +257,8 @@ private IReadOnlyList GenerateColumnModifications() foreach (var entry in _entries) { var nonMainEntry = updating - && (entry.EntityState == EntityState.Deleted - || entry.EntityState == EntityState.Added); + && (entry.EntityState == EntityState.Deleted + || entry.EntityState == EntityState.Added); foreach (var property in entry.EntityType.GetProperties()) { @@ -277,7 +277,7 @@ private IReadOnlyList GenerateColumnModifications() writeValue = property.GetBeforeSaveBehavior() == PropertySaveBehavior.Save; } else if ((updating && property.GetAfterSaveBehavior() == PropertySaveBehavior.Save) - || (!isKey && nonMainEntry)) + || (!isKey && nonMainEntry)) { writeValue = columnPropagator?.TryPropagate(property, (InternalEntityEntry)entry) ?? entry.IsModified(property); @@ -404,6 +404,7 @@ public void RecordValue(IProperty property, IUpdateEntry entry) _write = true; _currentValue = null; } + break; } } diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerStringMethodTranslator.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerStringMethodTranslator.cs index 75bed70c12d..d20aa0b6f30 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerStringMethodTranslator.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerStringMethodTranslator.cs @@ -287,12 +287,12 @@ private SqlExpression TranslateStartsEndsWith(SqlExpression instance, SqlExpress if (startsWith) { return _sqlExpressionFactory.Equal( - _sqlExpressionFactory.Function( - "LEFT", - new[] { instance, _sqlExpressionFactory.Function("LEN", new[] { pattern }, typeof(int)) }, - typeof(string), - stringTypeMapping), - pattern); + _sqlExpressionFactory.Function( + "LEFT", + new[] { instance, _sqlExpressionFactory.Function("LEN", new[] { pattern }, typeof(int)) }, + typeof(string), + stringTypeMapping), + pattern); } return _sqlExpressionFactory.Equal( diff --git a/src/EFCore.Sqlite.Core/Infrastructure/SpatialiteLoader.cs b/src/EFCore.Sqlite.Core/Infrastructure/SpatialiteLoader.cs index 0e8d4626768..f19372e81aa 100644 --- a/src/EFCore.Sqlite.Core/Infrastructure/SpatialiteLoader.cs +++ b/src/EFCore.Sqlite.Core/Infrastructure/SpatialiteLoader.cs @@ -134,8 +134,8 @@ private static void FindExtension() var candidateAssets = new Dictionary(); var rid = RuntimeEnvironment.GetRuntimeIdentifier(); var rids = DependencyContext.Default.RuntimeGraph.FirstOrDefault(g => g.Runtime == rid)?.Fallbacks - .ToList() - ?? new List(); + .ToList() + ?? new List(); rids.Insert(0, rid); foreach (var library in DependencyContext.Default.RuntimeLibraries) diff --git a/src/EFCore/Extensions/Internal/ExpressionExtensions.cs b/src/EFCore/Extensions/Internal/ExpressionExtensions.cs index 44a333bc16a..6317e820338 100644 --- a/src/EFCore/Extensions/Internal/ExpressionExtensions.cs +++ b/src/EFCore/Extensions/Internal/ExpressionExtensions.cs @@ -8,7 +8,6 @@ using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; -using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.EntityFrameworkCore.Utilities; diff --git a/src/EFCore/Query/ReplacingExpressionVisitor.cs b/src/EFCore/Query/ReplacingExpressionVisitor.cs index 7ea4cb60b5b..ae8033b8b5a 100644 --- a/src/EFCore/Query/ReplacingExpressionVisitor.cs +++ b/src/EFCore/Query/ReplacingExpressionVisitor.cs @@ -6,7 +6,6 @@ using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; -using Microsoft.EntityFrameworkCore.Metadata; namespace Microsoft.EntityFrameworkCore.Query { diff --git a/src/Shared/EnumerableMethods.cs b/src/Shared/EnumerableMethods.cs index 9dac113a72d..6ae8e727e61 100644 --- a/src/Shared/EnumerableMethods.cs +++ b/src/Shared/EnumerableMethods.cs @@ -112,12 +112,12 @@ static EnumerableMethods() All = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.All) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); AnyWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Any) && mi.GetParameters().Length == 1); AnyWithPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Any) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); Contains = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Contains) && mi.GetParameters().Length == 2); @@ -137,12 +137,12 @@ static EnumerableMethods() mi => mi.Name == nameof(Enumerable.Count) && mi.GetParameters().Length == 1); CountWithPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Count) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); LongCountWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.LongCount) && mi.GetParameters().Length == 1); LongCountWithPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.LongCount) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); MinWithSelector = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Min) && mi.GetParameters().Length == 2 && mi.GetGenericArguments().Length == 2 @@ -166,32 +166,32 @@ static EnumerableMethods() mi => mi.Name == nameof(Enumerable.First) && mi.GetParameters().Length == 1); FirstWithPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.First) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); FirstOrDefaultWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.FirstOrDefault) && mi.GetParameters().Length == 1); FirstOrDefaultWithPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.FirstOrDefault) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); SingleWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Single) && mi.GetParameters().Length == 1); SingleWithPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Single) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); SingleOrDefaultWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.SingleOrDefault) && mi.GetParameters().Length == 1); SingleOrDefaultWithPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.SingleOrDefault) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); LastWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Last) && mi.GetParameters().Length == 1); LastWithPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Last) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); LastOrDefaultWithoutPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.LastOrDefault) && mi.GetParameters().Length == 1); LastOrDefaultWithPredicate = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.LastOrDefault) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); Distinct = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Distinct) && mi.GetParameters().Length == 1); @@ -199,35 +199,35 @@ static EnumerableMethods() mi => mi.Name == nameof(Enumerable.Reverse) && mi.GetParameters().Length == 1); Where = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Where) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); Select = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Select) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); SelectWithOrdinal = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Select) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType, funcGenericArgs: 3)); + && IsFunc(mi.GetParameters()[1].ParameterType, funcGenericArgs: 3)); Skip = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Skip) && mi.GetParameters().Length == 2); Take = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.Take) && mi.GetParameters().Length == 2); SkipWhile = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.SkipWhile) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); TakeWhile = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.TakeWhile) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); OrderBy = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.OrderBy) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); OrderByDescending = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.OrderByDescending) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); ThenBy = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.ThenBy) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); ThenByDescending = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.ThenByDescending) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); DefaultIfEmptyWithoutArgument = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.DefaultIfEmpty) && mi.GetParameters().Length == 1); DefaultIfEmptyWithArgument = enumerableMethods.Single( @@ -239,27 +239,27 @@ static EnumerableMethods() mi => mi.Name == nameof(Enumerable.GroupJoin) && mi.GetParameters().Length == 5); SelectManyWithCollectionSelector = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.SelectMany) && mi.GetParameters().Length == 3 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); SelectManyWithoutCollectionSelector = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.SelectMany) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); GroupByWithKeySelector = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 2 - && IsFunc(mi.GetParameters()[1].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType)); GroupByWithKeyElementSelector = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 3 - && IsFunc(mi.GetParameters()[1].ParameterType) - && IsFunc(mi.GetParameters()[2].ParameterType)); + && IsFunc(mi.GetParameters()[1].ParameterType) + && IsFunc(mi.GetParameters()[2].ParameterType)); GroupByWithKeyElementResultSelector = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 4 - && IsFunc(mi.GetParameters()[1].ParameterType) - && IsFunc(mi.GetParameters()[2].ParameterType) && IsFunc( - mi.GetParameters()[3].ParameterType, 3)); + && IsFunc(mi.GetParameters()[1].ParameterType) + && IsFunc(mi.GetParameters()[2].ParameterType) && IsFunc( + mi.GetParameters()[3].ParameterType, 3)); GroupByWithKeyResultSelector = enumerableMethods.Single( mi => mi.Name == nameof(Enumerable.GroupBy) && mi.GetParameters().Length == 3 - && IsFunc(mi.GetParameters()[1].ParameterType) && IsFunc( - mi.GetParameters()[2].ParameterType, 3)); + && IsFunc(mi.GetParameters()[1].ParameterType) && IsFunc( + mi.GetParameters()[2].ParameterType, 3)); SumWithoutSelectorMethods = new Dictionary { @@ -332,8 +332,8 @@ static MethodInfo GetSumOrAverageWithSelector(List enumerableMeth static bool IsFunc(Type type, int funcGenericArgs = 2) => type.IsGenericType && (funcGenericArgs == 1 && type.GetGenericTypeDefinition() == typeof(Func<>) - || funcGenericArgs == 2 && type.GetGenericTypeDefinition() == typeof(Func<,>) - || funcGenericArgs == 3 && type.GetGenericTypeDefinition() == typeof(Func<,,>)); + || funcGenericArgs == 2 && type.GetGenericTypeDefinition() == typeof(Func<,>) + || funcGenericArgs == 3 && type.GetGenericTypeDefinition() == typeof(Func<,,>)); static bool IsSelector(Type type) => type.IsGenericType diff --git a/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs b/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs index 19f74ec9406..2269090cbfe 100644 --- a/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/EmbeddedDocumentsTest.cs @@ -163,8 +163,7 @@ public virtual async Task Can_add_collection_dependent_to_owner() using (var context = new EmbeddedTransportationContext(options)) { - var peopleBase = await context.Set().OrderBy(o => o.Id).ToListAsync(); - var people = peopleBase.Cast().ToList(); + var people = await context.Set().OrderBy(o => o.Id).ToListAsync(); var addresses = people[0].Addresses.ToList(); Assert.Equal(addedAddress1.Street, addresses.Single().Street); Assert.Equal(addedAddress1.City, addresses.Single().City); @@ -300,7 +299,7 @@ public virtual async Task Can_query_just_embedded_collection() Id = 3, Addresses = new[] { - new Address { Street = "First", City = "City" }, new Address { Street = "Second", City = "City" } + new Address { Street = "First", City = "City" }, new Address { Street = "Second", City = "City" } } }); @@ -413,13 +412,14 @@ public DbContextOptions CreateOptions( OnModelCreatingAction = onModelCreating; AdditionalModelCacheKey = additionalModelCacheKey; var options = CreateOptions(TestStore); - TestStore.Initialize(ServiceProvider, () => new EmbeddedTransportationContext(options), c => - { - if (seed) + TestStore.Initialize( + ServiceProvider, () => new EmbeddedTransportationContext(options), c => { - ((TransportationContext)c).Seed(); - } - }); + if (seed) + { + ((TransportationContext)c).Seed(); + } + }); ListLoggerFactory.Clear(); return options; diff --git a/test/EFCore.Cosmos.FunctionalTests/EndToEndCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/EndToEndCosmosTest.cs index f65f307ff59..59b78d21fab 100644 --- a/test/EFCore.Cosmos.FunctionalTests/EndToEndCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/EndToEndCosmosTest.cs @@ -237,7 +237,8 @@ public async Task Can_add_update_delete_end_to_end_with_partition_key() var customerFromStore = await context.Set().OrderBy(c => c.PartitionKey).FirstAsync(); customerFromStore.PartitionKey = 2; - Assert.Equal(CoreStrings.KeyReadOnly(nameof(Customer.PartitionKey), nameof(Customer)), + Assert.Equal( + CoreStrings.KeyReadOnly(nameof(Customer.PartitionKey), nameof(Customer)), Assert.Throws(() => context.SaveChanges()).Message); } @@ -271,12 +272,13 @@ public PartitionKeyContext(DbContextOptions dbContextOptions) protected override void OnModelCreating(ModelBuilder modelBuilder) { - modelBuilder.Entity(cb => - { - cb.HasPartitionKey(c => c.PartitionKey); - cb.Property(c => c.PartitionKey).HasConversion(); - cb.HasKey(c => new { c.Id, c.PartitionKey }); - }); + modelBuilder.Entity( + cb => + { + cb.HasPartitionKey(c => c.PartitionKey); + cb.Property(c => c.PartitionKey).HasConversion(); + cb.HasKey(c => new { c.Id, c.PartitionKey }); + }); } } @@ -449,7 +451,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) [ConditionalFact] public async Task Add_update_delete_query_throws_if_no_container() { - await using var testDatabase = CosmosTestStore.CreateInitialized(DatabaseName+"Empty"); + await using var testDatabase = CosmosTestStore.CreateInitialized(DatabaseName + "Empty"); var options = Fixture.CreateOptions(testDatabase); var customer = new Customer { Id = 42, Name = "Theon" }; @@ -457,7 +459,8 @@ public async Task Add_update_delete_query_throws_if_no_container() { context.Add(customer); - Assert.StartsWith("Response status code does not indicate success: 404 Substatus: 0", + Assert.StartsWith( + "Response status code does not indicate success: 404 Substatus: 0", (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); } @@ -465,7 +468,8 @@ public async Task Add_update_delete_query_throws_if_no_container() { context.Add(customer).State = EntityState.Modified; - Assert.StartsWith("Response status code does not indicate success: 404 Substatus: 0", + Assert.StartsWith( + "Response status code does not indicate success: 404 Substatus: 0", (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); } @@ -473,13 +477,15 @@ public async Task Add_update_delete_query_throws_if_no_container() { context.Add(customer).State = EntityState.Deleted; - Assert.StartsWith("Response status code does not indicate success: 404 Substatus: 0", + Assert.StartsWith( + "Response status code does not indicate success: 404 Substatus: 0", (await Assert.ThrowsAsync(() => context.SaveChangesAsync())).Message); } using (var context = new CustomerContext(options)) { - Assert.StartsWith("Response status code does not indicate success: 404 Substatus: 0", + Assert.StartsWith( + "Response status code does not indicate success: 404 Substatus: 0", (await Assert.ThrowsAsync(() => context.Set().SingleAsync())).Message); } } diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs index 364b6a76171..e22305597cc 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/OwnedQueryCosmosTest.cs @@ -169,9 +169,11 @@ public override Task Navigation_rewrite_on_owned_reference_followed_by_regular_e } [ConditionalTheory(Skip = "LeftJoin #12086")] - public override Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(bool isAsync) + public override Task + Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(bool isAsync) { - return base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(isAsync); + return base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection( + isAsync); } [ConditionalTheory(Skip = "LeftJoin #12086")] diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/SimpleQueryCosmosTest.Where.cs b/test/EFCore.Cosmos.FunctionalTests/Query/SimpleQueryCosmosTest.Where.cs index e5effc18e73..66f313de3c1 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/SimpleQueryCosmosTest.Where.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/SimpleQueryCosmosTest.Where.cs @@ -1788,7 +1788,7 @@ await AssertQuery( isAsync, ss => ss.Set().Where(od => od.OrderID < 10250).Where( od => ss.Set().OrderBy(p => p.ProductID).Take(1).Select(p => p.ProductID).Contains(od.ProductID) - || ss.Set().OrderBy(o => o.OrderID).Take(1).Select(o => o.OrderID).Contains(od.OrderID)), + || ss.Set().OrderBy(o => o.OrderID).Take(1).Select(o => o.OrderID).Contains(od.OrderID)), entryCount: 3); AssertSql( @@ -1804,7 +1804,7 @@ await AssertQuery( isAsync, ss => ss.Set().Where(od => od.OrderID < 10260).Where( od => ss.Set().OrderBy(p => p.ProductID).Take(20).Select(p => p.ProductID).Contains(od.ProductID) - && ss.Set().OrderBy(o => o.OrderID).Take(10).Select(o => o.OrderID).Contains(od.OrderID)), + && ss.Set().OrderBy(o => o.OrderID).Take(10).Select(o => o.OrderID).Contains(od.OrderID)), entryCount: 5); AssertSql( @@ -1819,8 +1819,9 @@ public override async Task Where_contains_on_navigation(bool isAsync) await AssertQuery( isAsync, ss => ss.Set().Where(o => o.OrderID > 10354 && o.OrderID < 10360) - .Where(o => ss.Set().Where(c => c.City == "London") - .Any(c => c.Orders.Contains(o))), + .Where( + o => ss.Set().Where(c => c.City == "London") + .Any(c => c.Orders.Contains(o))), entryCount: 2); AssertSql( @@ -1834,7 +1835,8 @@ public override async Task Where_subquery_FirstOrDefault_is_null(bool isAsync) { await AssertQuery( isAsync, - ss => ss.Set().Where(c => c.CustomerID == "PARIS").Where(c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault() == null), + ss => ss.Set().Where(c => c.CustomerID == "PARIS") + .Where(c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault() == null), entryCount: 1); AssertSql( diff --git a/test/EFCore.Cosmos.FunctionalTests/Query/SimpleQueryCosmosTest.cs b/test/EFCore.Cosmos.FunctionalTests/Query/SimpleQueryCosmosTest.cs index 0eba1ebfd2c..25ab05637d8 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Query/SimpleQueryCosmosTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Query/SimpleQueryCosmosTest.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.TestModels.Northwind; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; @@ -1025,9 +1024,13 @@ public override async Task All_top_level_subquery(bool isAsync) await AssertSingleResult( isAsync, syncQuery: ss => ss.Set() - .All(c1 => c1.CustomerID == "ALFKI" && ss.Set().Any(c2 => ss.Set().Any(c3 => c1.CustomerID == c3.CustomerID))), + .All( + c1 => c1.CustomerID == "ALFKI" + && ss.Set().Any(c2 => ss.Set().Any(c3 => c1.CustomerID == c3.CustomerID))), asyncQuery: ss => ss.Set() - .AllAsync(c1 => c1.CustomerID == "ALFKI" && ss.Set().Any(c2 => ss.Set().Any(c3 => c1.CustomerID == c3.CustomerID)))); + .AllAsync( + c1 => c1.CustomerID == "ALFKI" + && ss.Set().Any(c2 => ss.Set().Any(c3 => c1.CustomerID == c3.CustomerID)))); AssertSql( @"SELECT c @@ -1041,13 +1044,17 @@ public override async Task All_top_level_subquery_ef_property(bool isAsync) await AssertSingleResult( isAsync, syncQuery: ss => ss.Set() - .All(c1 => c1.CustomerID == "ALFKI" && ss.Set() - .Any(c2 => ss.Set() - .Any(c3 => EF.Property(c1, "CustomerID") == c3.CustomerID))), + .All( + c1 => c1.CustomerID == "ALFKI" && ss.Set() + .Any( + c2 => ss.Set() + .Any(c3 => EF.Property(c1, "CustomerID") == c3.CustomerID))), asyncQuery: ss => ss.Set() - .AllAsync(c1 => c1.CustomerID == "ALFKI" && ss.Set() - .Any(c2 => ss.Set() - .Any(c3 => EF.Property(c1, "CustomerID") == c3.CustomerID)))); + .AllAsync( + c1 => c1.CustomerID == "ALFKI" && ss.Set() + .Any( + c2 => ss.Set() + .Any(c3 => EF.Property(c1, "CustomerID") == c3.CustomerID)))); AssertSql( @"SELECT c @@ -1436,7 +1443,7 @@ await AssertQuery( from c in ss.Set().Where(cst => cst.CustomerID == "ALFKI") from o in ss.Set().Where(o => o.CustomerID == c.CustomerID).DefaultIfEmpty() select new { c.ContactName, o }, - e => (e.ContactName, + e.o?.OrderID), + e => (e.ContactName, +e.o?.OrderID), entryCount: 6); AssertSql( @@ -1517,8 +1524,8 @@ await AssertSingle( from o in ss.Set().Where(or => or.OrderID < 10300) orderby c.CustomerID, o.OrderID select new { c, o }) - .Take(1) - .Cast(), + .Take(1) + .Cast(), entryCount: 2); AssertSql( @@ -1852,7 +1859,8 @@ await AssertQuery( { var firstOrder = ss.Set().OrderBy(o => o.OrderID).First(); Expression> expr = x => x.OrderID == firstOrder.OrderID; - return ss.Set().Where(o => o.OrderID < 10250).Where(x => ss.Set().Where(expr).Where(o => o.CustomerID == x.CustomerID).Any()); + return ss.Set().Where(o => o.OrderID < 10250) + .Where(x => ss.Set().Where(expr).Where(o => o.CustomerID == x.CustomerID).Any()); }, entryCount: 1); @@ -1975,9 +1983,10 @@ public override async Task Where_subquery_on_collection(bool isAsync) await AssertQuery( isAsync, ss => ss.Set().Where(p => p.ProductID == 72) - .Where(p => ss.Set() - .Where(o => o.ProductID == p.ProductID) - .Select(odd => odd.Quantity).Contains(5)), + .Where( + p => ss.Set() + .Where(o => o.ProductID == p.ProductID) + .Select(odd => odd.Quantity).Contains(5)), entryCount: 1); AssertSql( @@ -2792,9 +2801,9 @@ await AssertQuery( isAsync, ss => ss.Set().Where( o => o.OrderID > 11002 && o.OrderID < 11004 && ss.Set() - .Where(od => od.Product.ProductName == "Chai") - .Select(od => od.OrderID) - .Contains(o.OrderID)), + .Where(od => od.Product.ProductName == "Chai") + .Select(od => od.OrderID) + .Contains(o.OrderID)), entryCount: 1); AssertSql( @@ -3546,10 +3555,7 @@ await AssertQuery( isAsync, ss => ss.Set().Where(c => c.CustomerID == "ALFKI") .Select( - c => new - { - c.CustomerID, OuterOrders = c.Orders.Where(o => o.OrderID < 10250).Count(o => c.Orders.Count() > 0) - })); + c => new { c.CustomerID, OuterOrders = c.Orders.Where(o => o.OrderID < 10250).Count(o => c.Orders.Count() > 0) })); AssertSql( @"SELECT c @@ -3725,8 +3731,10 @@ public override async Task Collection_navigation_equal_to_null_for_subquery(bool { await AssertQuery( isAsync, - ss => ss.Set().Where(c => c.Orders.Where(o => o.OrderID < 10250).OrderBy(o => o.OrderID).FirstOrDefault().OrderDetails == null), - ss => ss.Set().Where(c => c.Orders.Where(o => o.OrderID < 10250).OrderBy(o => o.OrderID).FirstOrDefault() == null), + ss => ss.Set().Where( + c => c.Orders.Where(o => o.OrderID < 10250).OrderBy(o => o.OrderID).FirstOrDefault().OrderDetails == null), + ss => ss.Set().Where( + c => c.Orders.Where(o => o.OrderID < 10250).OrderBy(o => o.OrderID).FirstOrDefault() == null), entryCount: 89); AssertSql( @@ -3739,7 +3747,8 @@ public override async Task Dependent_to_principal_navigation_equal_to_null_for_s { await AssertQuery( isAsync, - ss => ss.Set().Where(c => c.Orders.Where(o => o.OrderID < 10250).OrderBy(o => o.OrderID).FirstOrDefault().Customer == null), + ss => ss.Set().Where( + c => c.Orders.Where(o => o.OrderID < 10250).OrderBy(o => o.OrderID).FirstOrDefault().Customer == null), ss => ss.Set().Where( c => c.Orders.Where(o => o.OrderID < 10250).OrderBy(o => o.OrderID).Select(o => o.CustomerID).FirstOrDefault() == null), entryCount: 89); diff --git a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosDbConfiguredConditionAttribute.cs b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosDbConfiguredConditionAttribute.cs index 22a4e3e549c..4d505dea0a9 100644 --- a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosDbConfiguredConditionAttribute.cs +++ b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosDbConfiguredConditionAttribute.cs @@ -15,7 +15,8 @@ public class CosmosDbConfiguredConditionAttribute : Attribute, ITestCondition { private static bool? _connectionAvailable; - public string SkipReason => "Unable to connect to Cosmos DB. Please install/start the emulator service or configure a valid endpoint."; + public string SkipReason + => "Unable to connect to Cosmos DB. Please install/start the emulator service or configure a valid endpoint."; public async ValueTask IsMetAsync() { @@ -68,8 +69,8 @@ private static bool IsNotConfigured(Exception exception) { HttpRequestException re => re.InnerException is SocketException, _ => exception.Message.Contains( - "The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used.", - StringComparison.Ordinal), + "The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used.", + StringComparison.Ordinal), }; } } diff --git a/test/EFCore.Cosmos.Tests/Metadata/CosmosMetadataExtensionsTest.cs b/test/EFCore.Cosmos.Tests/Metadata/CosmosMetadataExtensionsTest.cs index 7fb9f2d8210..90cd89a2a45 100644 --- a/test/EFCore.Cosmos.Tests/Metadata/CosmosMetadataExtensionsTest.cs +++ b/test/EFCore.Cosmos.Tests/Metadata/CosmosMetadataExtensionsTest.cs @@ -48,11 +48,13 @@ public void Can_get_and_set_partition_key_name() ((IConventionEntityType)entityType).SetPartitionKeyPropertyName("pk"); Assert.Equal("pk", entityType.GetPartitionKeyPropertyName()); - Assert.Equal(ConfigurationSource.Convention, ((IConventionEntityType)entityType).GetPartitionKeyPropertyNameConfigurationSource()); + Assert.Equal( + ConfigurationSource.Convention, ((IConventionEntityType)entityType).GetPartitionKeyPropertyNameConfigurationSource()); entityType.SetPartitionKeyPropertyName("pk"); Assert.Equal("pk", entityType.GetPartitionKeyPropertyName()); - Assert.Equal(ConfigurationSource.Explicit, ((IConventionEntityType)entityType).GetPartitionKeyPropertyNameConfigurationSource()); + Assert.Equal( + ConfigurationSource.Explicit, ((IConventionEntityType)entityType).GetPartitionKeyPropertyNameConfigurationSource()); entityType.SetPartitionKeyPropertyName(null); Assert.Null(entityType.GetPartitionKeyPropertyName()); diff --git a/test/EFCore.CrossStore.FunctionalTests/TestModels/CrossStoreContext.cs b/test/EFCore.CrossStore.FunctionalTests/TestModels/CrossStoreContext.cs index 2ccd0631023..5ff05f9aa54 100644 --- a/test/EFCore.CrossStore.FunctionalTests/TestModels/CrossStoreContext.cs +++ b/test/EFCore.CrossStore.FunctionalTests/TestModels/CrossStoreContext.cs @@ -6,7 +6,6 @@ namespace Microsoft.EntityFrameworkCore.TestModels public class CrossStoreContext : DbContext { public CrossStoreContext() - : base() { } diff --git a/test/EFCore.Design.Tests/Migrations/ModelSnapshotSqlServerTest.cs b/test/EFCore.Design.Tests/Migrations/ModelSnapshotSqlServerTest.cs index d9ec7d00e46..2eb3ba3a17b 100644 --- a/test/EFCore.Design.Tests/Migrations/ModelSnapshotSqlServerTest.cs +++ b/test/EFCore.Design.Tests/Migrations/ModelSnapshotSqlServerTest.cs @@ -128,6 +128,7 @@ private class EntityWithTwoProperties { [Key] public int Id { get; set; } + public int AlternateId { get; set; } public EntityWithOneProperty EntityWithOneProperty { get; set; } @@ -2049,20 +2050,22 @@ public virtual void Property_without_column_type() modelBuilder .HasAnnotation(SqlServerAnnotationNames.ValueGenerationStrategy, SqlServerValueGenerationStrategy.IdentityColumn); - modelBuilder.Entity("Building", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasAnnotation(SqlServerAnnotationNames.ValueGenerationStrategy, SqlServerValueGenerationStrategy.IdentityColumn); + modelBuilder.Entity( + "Building", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasAnnotation(SqlServerAnnotationNames.ValueGenerationStrategy, SqlServerValueGenerationStrategy.IdentityColumn); - b.HasKey("Id"); + b.HasKey("Id"); - b.ToTable("Buildings"); - }); + b.ToTable("Buildings"); + }); Test( model.FinalizeModel(), - AddBoilerPlate(@" + AddBoilerPlate( + @" modelBuilder .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs index 31dc3807ef3..a5ca4e07eb7 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs @@ -197,15 +197,15 @@ public void Views_work() [ConditionalFact] public void ModelInDiferentNamespaceDbContext_works() { - var modelGenerationOptions = new ModelCodeGenerationOptions() + var modelGenerationOptions = new ModelCodeGenerationOptions { - ContextNamespace = "TestNamespace", - ModelNamespace = "AnotherNamespaceOfModel" + ContextNamespace = "TestNamespace", ModelNamespace = "AnotherNamespaceOfModel" }; const string entityInAnoterNamespaceTypeName = "EntityInAnotherNamespace"; - Test(modelBuilder => modelBuilder.Entity(entityInAnoterNamespaceTypeName) + Test( + modelBuilder => modelBuilder.Entity(entityInAnoterNamespaceTypeName) , modelGenerationOptions , code => Assert.Contains(string.Concat("using ", modelGenerationOptions.ModelNamespace, ";"), code.ContextFile.Code) , model => Assert.NotNull(model.FindEntityType(string.Concat(modelGenerationOptions.ModelNamespace, ".", entityInAnoterNamespaceTypeName))) @@ -215,14 +215,12 @@ public void ModelInDiferentNamespaceDbContext_works() [ConditionalFact] public void ModelSameNamespaceDbContext_works() { - var modelGenerationOptions = new ModelCodeGenerationOptions() - { - ContextNamespace = "TestNamespace", - }; + var modelGenerationOptions = new ModelCodeGenerationOptions { ContextNamespace = "TestNamespace" }; const string entityInAnoterNamespaceTypeName = "EntityInAnotherNamespace"; - Test(modelBuilder => modelBuilder.Entity(entityInAnoterNamespaceTypeName) + Test( + modelBuilder => modelBuilder.Entity(entityInAnoterNamespaceTypeName) , modelGenerationOptions , code => Assert.DoesNotContain(string.Concat("using ", modelGenerationOptions.ModelNamespace, ";"), code.ContextFile.Code) , model => Assert.NotNull(model.FindEntityType(string.Concat(modelGenerationOptions.ModelNamespace, ".", entityInAnoterNamespaceTypeName))) diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/ReverseEngineerScaffolderTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/ReverseEngineerScaffolderTest.cs index 2ed3db2a4b2..e0379577632 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/ReverseEngineerScaffolderTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/ReverseEngineerScaffolderTest.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using System.Data.Common; using System.Globalization; using System.IO; @@ -197,7 +198,7 @@ public DatabaseModel Create(string connectionString, DatabaseModelFactoryOptions } public DatabaseModel Create(DbConnection connection, DatabaseModelFactoryOptions options) - => throw new System.NotImplementedException(); + => throw new NotImplementedException(); } } } diff --git a/test/EFCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryTest.cs index e3094b6d39d..4f3405c8fb0 100644 --- a/test/EFCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryTest.cs @@ -3,7 +3,6 @@ using System; using Microsoft.EntityFrameworkCore.TestUtilities; -using Xunit; // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore diff --git a/test/EFCore.InMemory.FunctionalTests/ConvertToProviderTypesInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/ConvertToProviderTypesInMemoryTest.cs index ed2e4e2681f..dced737313b 100644 --- a/test/EFCore.InMemory.FunctionalTests/ConvertToProviderTypesInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/ConvertToProviderTypesInMemoryTest.cs @@ -3,7 +3,6 @@ using System; using Microsoft.EntityFrameworkCore.TestUtilities; -using Xunit; namespace Microsoft.EntityFrameworkCore { diff --git a/test/EFCore.InMemory.FunctionalTests/FieldMappingInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/FieldMappingInMemoryTest.cs index e4d9cef8b17..52f4a5e859b 100644 --- a/test/EFCore.InMemory.FunctionalTests/FieldMappingInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/FieldMappingInMemoryTest.cs @@ -3,7 +3,6 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.TestUtilities; -using Xunit; namespace Microsoft.EntityFrameworkCore { diff --git a/test/EFCore.InMemory.FunctionalTests/InMemoryComplianceTest.cs b/test/EFCore.InMemory.FunctionalTests/InMemoryComplianceTest.cs index 678e7fa592b..b2913428e90 100644 --- a/test/EFCore.InMemory.FunctionalTests/InMemoryComplianceTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/InMemoryComplianceTest.cs @@ -16,10 +16,9 @@ public class InMemoryComplianceTest : ComplianceTestBase typeof(FunkyDataQueryTestBase<>), typeof(OptimisticConcurrencyTestBase<>), typeof(StoreGeneratedTestBase<>), - typeof(ConferencePlannerTestBase<>), + typeof(ConferencePlannerTestBase<>) }; protected override Assembly TargetAssembly { get; } = typeof(InMemoryComplianceTest).Assembly; } } - diff --git a/test/EFCore.InMemory.FunctionalTests/LazyLoadProxyInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/LazyLoadProxyInMemoryTest.cs index 60f33c7c2c7..0093e711ee5 100644 --- a/test/EFCore.InMemory.FunctionalTests/LazyLoadProxyInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/LazyLoadProxyInMemoryTest.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.EntityFrameworkCore.TestUtilities; -using Xunit; namespace Microsoft.EntityFrameworkCore { diff --git a/test/EFCore.InMemory.FunctionalTests/MonsterFixupSnapshotInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/MonsterFixupSnapshotInMemoryTest.cs index cb9c08417cc..f04f88df942 100644 --- a/test/EFCore.InMemory.FunctionalTests/MonsterFixupSnapshotInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/MonsterFixupSnapshotInMemoryTest.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.EntityFrameworkCore.TestUtilities; -using Xunit; namespace Microsoft.EntityFrameworkCore { diff --git a/test/EFCore.InMemory.FunctionalTests/PropertyValuesInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/PropertyValuesInMemoryTest.cs index 00253161ad8..a4e64af2a37 100644 --- a/test/EFCore.InMemory.FunctionalTests/PropertyValuesInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/PropertyValuesInMemoryTest.cs @@ -1,9 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.TestUtilities; -using Xunit; namespace Microsoft.EntityFrameworkCore { diff --git a/test/EFCore.InMemory.FunctionalTests/Query/GearsOfWarQueryInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Query/GearsOfWarQueryInMemoryTest.cs index e5ecb432950..b836b33c7c0 100644 --- a/test/EFCore.InMemory.FunctionalTests/Query/GearsOfWarQueryInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Query/GearsOfWarQueryInMemoryTest.cs @@ -58,9 +58,11 @@ public override void Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesc } [ConditionalTheory(Skip = "issue #17540")] - public override Task Null_semantics_is_correctly_applied_for_function_comparisons_that_take_arguments_from_optional_navigation_complex(bool isAsync) + public override Task + Null_semantics_is_correctly_applied_for_function_comparisons_that_take_arguments_from_optional_navigation_complex(bool isAsync) { - return base.Null_semantics_is_correctly_applied_for_function_comparisons_that_take_arguments_from_optional_navigation_complex(isAsync); + return base.Null_semantics_is_correctly_applied_for_function_comparisons_that_take_arguments_from_optional_navigation_complex( + isAsync); } [ConditionalTheory(Skip = "issue #18284")] diff --git a/test/EFCore.InMemory.FunctionalTests/Query/GroupByQueryInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Query/GroupByQueryInMemoryTest.cs index 6224eb64770..4396b58de5c 100644 --- a/test/EFCore.InMemory.FunctionalTests/Query/GroupByQueryInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Query/GroupByQueryInMemoryTest.cs @@ -1,9 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.TestUtilities; -using Xunit; using Xunit.Abstractions; namespace Microsoft.EntityFrameworkCore.Query diff --git a/test/EFCore.InMemory.FunctionalTests/Query/IncludeAsyncInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Query/IncludeAsyncInMemoryTest.cs index 59496e945dd..c278fc5708a 100644 --- a/test/EFCore.InMemory.FunctionalTests/Query/IncludeAsyncInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Query/IncludeAsyncInMemoryTest.cs @@ -1,9 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Threading.Tasks; -using Xunit; - namespace Microsoft.EntityFrameworkCore.Query { public class IncludeAsyncInMemoryTest : IncludeAsyncTestBase diff --git a/test/EFCore.InMemory.FunctionalTests/Query/InheritanceInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Query/InheritanceInMemoryTest.cs index 32b5f5d7c0a..358fec97ad2 100644 --- a/test/EFCore.InMemory.FunctionalTests/Query/InheritanceInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Query/InheritanceInMemoryTest.cs @@ -22,7 +22,8 @@ public override void Can_query_all_animal_views() var message = Assert.Throws(() => base.Can_query_all_animal_views()).Message; Assert.Equal( - CoreStrings.TranslationFailed(@"DbSet + CoreStrings.TranslationFailed( + @"DbSet .Select(b => InheritanceInMemoryFixture.MaterializeView(b)) .OrderBy(a => a.CountryId)"), message); diff --git a/test/EFCore.InMemory.FunctionalTests/Query/SimpleQueryInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/Query/SimpleQueryInMemoryTest.cs index de73f9b4160..45b73d94066 100644 --- a/test/EFCore.InMemory.FunctionalTests/Query/SimpleQueryInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/Query/SimpleQueryInMemoryTest.cs @@ -39,37 +39,44 @@ public override void Min_no_data_subquery() public override Task Where_query_composition_entity_equality_one_element_Single(bool isAsync) { - return Assert.ThrowsAsync(() => base.Where_query_composition_entity_equality_one_element_Single(isAsync)); + return Assert.ThrowsAsync( + () => base.Where_query_composition_entity_equality_one_element_Single(isAsync)); } public override Task Where_query_composition_entity_equality_one_element_First(bool isAsync) { - return Assert.ThrowsAsync(() => base.Where_query_composition_entity_equality_one_element_First(isAsync)); + return Assert.ThrowsAsync( + () => base.Where_query_composition_entity_equality_one_element_First(isAsync)); } public override Task Where_query_composition_entity_equality_no_elements_Single(bool isAsync) { - return Assert.ThrowsAsync(() => base.Where_query_composition_entity_equality_no_elements_Single(isAsync)); + return Assert.ThrowsAsync( + () => base.Where_query_composition_entity_equality_no_elements_Single(isAsync)); } public override Task Where_query_composition_entity_equality_no_elements_First(bool isAsync) { - return Assert.ThrowsAsync(() => base.Where_query_composition_entity_equality_no_elements_First(isAsync)); + return Assert.ThrowsAsync( + () => base.Where_query_composition_entity_equality_no_elements_First(isAsync)); } public override Task Where_query_composition_entity_equality_multiple_elements_SingleOrDefault(bool isAsync) { - return Assert.ThrowsAsync(() => base.Where_query_composition_entity_equality_multiple_elements_SingleOrDefault(isAsync)); + return Assert.ThrowsAsync( + () => base.Where_query_composition_entity_equality_multiple_elements_SingleOrDefault(isAsync)); } public override Task Where_query_composition_entity_equality_multiple_elements_Single(bool isAsync) { - return Assert.ThrowsAsync(() => base.Where_query_composition_entity_equality_multiple_elements_Single(isAsync)); + return Assert.ThrowsAsync( + () => base.Where_query_composition_entity_equality_multiple_elements_Single(isAsync)); } public override Task Collection_Last_member_access_in_projection_translated(bool isAsync) { - return Assert.ThrowsAsync(() => base.Collection_Last_member_access_in_projection_translated(isAsync)); + return Assert.ThrowsAsync( + () => base.Collection_Last_member_access_in_projection_translated(isAsync)); } // Sending client code to server diff --git a/test/EFCore.InMemory.FunctionalTests/WithConstructorsInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/WithConstructorsInMemoryTest.cs index a8dfb8128c5..43ceedaba15 100644 --- a/test/EFCore.InMemory.FunctionalTests/WithConstructorsInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/WithConstructorsInMemoryTest.cs @@ -4,7 +4,6 @@ using System.Linq; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.TestUtilities; -using Xunit; namespace Microsoft.EntityFrameworkCore { diff --git a/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs index 71e21bcc17a..57793d42128 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs @@ -1047,8 +1047,9 @@ public virtual void FromSqlRaw_with_set_operation() var actual = context.Set() .FromSqlRaw(NormalizeDelimetersInRawString("SELECT * FROM [Customers] WHERE [City] = 'London'")) - .Concat(context.Set() - .FromSqlRaw(NormalizeDelimetersInRawString("SELECT * FROM [Customers] WHERE [City] = 'Berlin'"))) + .Concat( + context.Set() + .FromSqlRaw(NormalizeDelimetersInRawString("SELECT * FROM [Customers] WHERE [City] = 'Berlin'"))) .ToArray(); Assert.Equal(7, actual.Length); diff --git a/test/EFCore.Relational.Specification.Tests/Query/FromSqlSprocQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/FromSqlSprocQueryTestBase.cs index 953ea397eed..ad293f32261 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/FromSqlSprocQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/FromSqlSprocQueryTestBase.cs @@ -35,9 +35,10 @@ public virtual async Task From_sql_queryable_stored_procedure(bool async) Assert.Equal(10, actual.Length); - Assert.Contains(actual, mep => - mep.TenMostExpensiveProducts == "Côte de Blaye" - && mep.UnitPrice == 263.50m); + Assert.Contains( + actual, mep => + mep.TenMostExpensiveProducts == "Côte de Blaye" + && mep.UnitPrice == 263.50m); } [ConditionalTheory] @@ -57,9 +58,10 @@ public virtual async Task From_sql_queryable_stored_procedure_with_tag(bool asyn Assert.Equal(10, actual.Length); - Assert.Contains(actual, mep => - mep.TenMostExpensiveProducts == "Côte de Blaye" - && mep.UnitPrice == 263.50m); + Assert.Contains( + actual, mep => + mep.TenMostExpensiveProducts == "Côte de Blaye" + && mep.UnitPrice == 263.50m); } [ConditionalTheory] @@ -97,8 +99,8 @@ public virtual async Task From_sql_queryable_stored_procedure_re_projection(bool Assert.Equal( RelationalStrings.FromSqlNonComposable, (async - ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) - : Assert.Throws(() => query.ToArray())).Message); + ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) + : Assert.Throws(() => query.ToArray())).Message); } [ConditionalTheory] @@ -136,9 +138,10 @@ public virtual async Task From_sql_queryable_stored_procedure_with_parameter(boo Assert.Equal(11, actual.Length); - Assert.Contains(actual, coh => - coh.ProductName == "Aniseed Syrup" - && coh.Total == 6); + Assert.Contains( + actual, coh => + coh.ProductName == "Aniseed Syrup" + && coh.Total == 6); } [ConditionalTheory] @@ -156,8 +159,8 @@ public virtual async Task From_sql_queryable_stored_procedure_composed(bool asyn Assert.Equal( RelationalStrings.FromSqlNonComposable, (async - ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) - : Assert.Throws(() => query.ToArray())).Message); + ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) + : Assert.Throws(() => query.ToArray())).Message); } [ConditionalTheory] @@ -198,8 +201,8 @@ public virtual async Task From_sql_queryable_stored_procedure_with_parameter_com Assert.Equal( RelationalStrings.FromSqlNonComposable, (async - ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) - : Assert.Throws(() => query.ToArray())).Message); + ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) + : Assert.Throws(() => query.ToArray())).Message); } [ConditionalTheory] @@ -239,8 +242,8 @@ public virtual async Task From_sql_queryable_stored_procedure_take(bool async) Assert.Equal( RelationalStrings.FromSqlNonComposable, (async - ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) - : Assert.Throws(() => query.ToArray())).Message); + ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) + : Assert.Throws(() => query.ToArray())).Message); } [ConditionalTheory] @@ -277,8 +280,8 @@ public virtual async Task From_sql_queryable_stored_procedure_min(bool async) Assert.Equal( RelationalStrings.FromSqlNonComposable, (async - ? await Assert.ThrowsAsync(() => query.MinAsync(mep => mep.UnitPrice)) - : Assert.Throws(() => query.Min(mep => mep.UnitPrice))).Message); + ? await Assert.ThrowsAsync(() => query.MinAsync(mep => mep.UnitPrice)) + : Assert.Throws(() => query.Min(mep => mep.UnitPrice))).Message); } [ConditionalTheory] @@ -311,8 +314,8 @@ public virtual async Task From_sql_queryable_stored_procedure_with_include_throw Assert.Equal( RelationalStrings.FromSqlNonComposable, (async - ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) - : Assert.Throws(() => query.ToArray())).Message); + ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) + : Assert.Throws(() => query.ToArray())).Message); } [ConditionalTheory] @@ -331,8 +334,8 @@ from b in context.Set() Assert.Equal( RelationalStrings.FromSqlNonComposable, (async - ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) - : Assert.Throws(() => query.ToArray())).Message); + ? await Assert.ThrowsAsync(() => query.ToArrayAsync()) + : Assert.Throws(() => query.ToArray())).Message); } [ConditionalTheory] diff --git a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs index e5db7fb1c58..1be2aceb005 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs @@ -971,13 +971,17 @@ public virtual void Null_semantics_with_null_check_complex() { using (var ctx = CreateContext()) { - var query1 = ctx.Entities1.Where(e => e.NullableIntA != null && ((e.NullableIntC != e.NullableIntA) || (e.NullableIntB != null && e.NullableIntA != e.NullableIntB))); + var query1 = ctx.Entities1.Where( + e => e.NullableIntA != null && ((e.NullableIntC != e.NullableIntA) + || (e.NullableIntB != null && e.NullableIntA != e.NullableIntB))); var result1 = query1.ToList(); - var query2 = ctx.Entities1.Where(e => e.NullableIntA != null && ((e.NullableIntC != e.NullableIntA) || (e.NullableIntA != e.NullableIntB))); + var query2 = ctx.Entities1.Where( + e => e.NullableIntA != null && ((e.NullableIntC != e.NullableIntA) || (e.NullableIntA != e.NullableIntB))); var result2 = query2.ToList(); - var query3 = ctx.Entities1.Where(e => (e.NullableIntA != null || e.NullableIntB != null) && e.NullableIntA == e.NullableIntC); + var query3 = ctx.Entities1.Where( + e => (e.NullableIntA != null || e.NullableIntB != null) && e.NullableIntA == e.NullableIntC); var result3 = query3.ToList(); } } diff --git a/test/EFCore.Relational.Specification.Tests/Query/QueryNoClientEvalTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/QueryNoClientEvalTestBase.cs index ae31890168e..0aa8266d383 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/QueryNoClientEvalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/QueryNoClientEvalTestBase.cs @@ -111,7 +111,7 @@ public virtual void Throws_when_subquery_main_from_clause() .OrderBy(c => c.CustomerID) .Take(5) select c1) - .ToList()); + .ToList()); } } @@ -128,7 +128,7 @@ public virtual void Throws_when_select_many() () => (from c1 in context.Customers from i in new[] { 1, 2, 3 } select c1) - .ToList()).Message); + .ToList()).Message); } } @@ -141,7 +141,7 @@ public virtual void Throws_when_join() () => (from e1 in context.Employees join i in new uint[] { 1, 2, 3 } on e1.EmployeeID equals i select e1) - .ToList()).Message; + .ToList()).Message; Assert.Equal( CoreStrings.QueryFailed( diff --git a/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs index 8caf6c6b0cc..c436884cffb 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/UdfDbFunctionTestBase.cs @@ -617,10 +617,8 @@ public virtual void Scalar_Function_Non_Static() var custName = (from c in context.Customers where c.Id == 1 - select new - { - Id = context.StarValueInstance(4, c.Id), LastName = context.DollarValueInstance(2, c.LastName) - }).Single(); + select new { Id = context.StarValueInstance(4, c.Id), LastName = context.DollarValueInstance(2, c.LastName) }) + .Single(); Assert.Equal("$$One", custName.LastName); } diff --git a/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs b/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs index 77d583bb27d..49b6d4424f5 100644 --- a/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/TableSplittingTestBase.cs @@ -183,22 +183,27 @@ public virtual void Can_share_required_columns() modelBuilder => { OnModelCreating(modelBuilder); - modelBuilder.Entity(vb => { - vb.Property(v => v.SeatingCapacity).HasColumnName("SeatingCapacity"); - }); - modelBuilder.Entity(cb => - { - cb.Property("SeatingCapacity").HasColumnName("SeatingCapacity"); - }); - modelBuilder.Entity(fb => - { - fb.Ignore(f => f.Engine); - }); + modelBuilder.Entity( + vb => + { + vb.Property(v => v.SeatingCapacity).HasColumnName("SeatingCapacity"); + }); + modelBuilder.Entity( + cb => + { + cb.Property("SeatingCapacity").HasColumnName("SeatingCapacity"); + }); + modelBuilder.Entity( + fb => + { + fb.Ignore(f => f.Engine); + }); }, seed: false)) { using (var context = CreateContext()) { - var scooterEntry = context.Add(new PoweredVehicle { Name = "Electric scooter", SeatingCapacity = 1, Engine = new Engine() }); + var scooterEntry = context.Add( + new PoweredVehicle { Name = "Electric scooter", SeatingCapacity = 1, Engine = new Engine() }); scooterEntry.Reference(v => v.Engine).TargetEntry.Property("SeatingCapacity").CurrentValue = 1; @@ -504,13 +509,14 @@ protected TestStore CreateTestStore(Action onModelCreating, bool s .AddSingleton(TestSqlLoggerFactory) .BuildServiceProvider(validateScopes: true); - TestStore.Initialize(ServiceProvider, CreateContext, c => - { - if (seed) + TestStore.Initialize( + ServiceProvider, CreateContext, c => { - ((TransportationContext)c).Seed(); - } - }); + if (seed) + { + ((TransportationContext)c).Seed(); + } + }); TestSqlLoggerFactory.Clear(); diff --git a/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalDatabaseCleaner.cs b/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalDatabaseCleaner.cs index 1e93681eeaf..20a51fffb14 100644 --- a/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalDatabaseCleaner.cs +++ b/test/EFCore.Relational.Specification.Tests/TestUtilities/RelationalDatabaseCleaner.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Text.RegularExpressions; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; diff --git a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs index ca81a6601ad..8ab66188f88 100644 --- a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs +++ b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs @@ -6,12 +6,10 @@ using System.Linq; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Migrations.Operations; using Microsoft.EntityFrameworkCore.TestUtilities; using Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; using Microsoft.EntityFrameworkCore.ValueGeneration; -using Microsoft.Extensions.DependencyInjection; using Xunit; // ReSharper disable UnusedAutoPropertyAccessor.Local @@ -1440,9 +1438,9 @@ public void Add_seed_data_with_non_writable_column_insert_operations_with_batchi Assert.Collection( ToJaggedArray(m.Values), r => Assert.Collection( - r, - v => Assert.Equal(42, v), - v => Assert.Equal("Firefly 1", v)), + r, + v => Assert.Equal(42, v), + v => Assert.Equal("Firefly 1", v)), r => Assert.Collection( r, v => Assert.Equal(43, v), @@ -1694,15 +1692,15 @@ public void Rename_property_and_column_when_snapshot() { Execute( source => source.Entity( - typeof(Crab).FullName, - x => - { - x.ToTable("Crab"); + typeof(Crab).FullName, + x => + { + x.ToTable("Crab"); - x.Property("CrabId"); + x.Property("CrabId"); - x.HasKey("CrabId"); - }), + x.HasKey("CrabId"); + }), target => target.Entity(), operations => { @@ -7632,17 +7630,18 @@ public void SeedData_type_with_owned_collection_no_changes() c.HasKey(x => x.Id); c.HasData(new Customer { Id = 1 }); - c.OwnsMany(y => y.Orders, x => - { - x.Ignore(o => o.Billing); - x.Ignore(o => o.Shipping); + c.OwnsMany( + y => y.Orders, x => + { + x.Ignore(o => o.Billing); + x.Ignore(o => o.Shipping); - x.WithOwner() - .HasForeignKey("CustomerId"); + x.WithOwner() + .HasForeignKey("CustomerId"); - x.HasKey("CustomerId", "Id"); - x.HasData(new { Id = 2, CustomerId = 1 }); - }); + x.HasKey("CustomerId", "Id"); + x.HasData(new { Id = 2, CustomerId = 1 }); + }); }); }, _ => { }, @@ -7690,35 +7689,37 @@ public void Old_style_ownership_to_new_style() .HasForeignKey("OrderInfo", "OrderId") .OnDelete(DeleteBehavior.Cascade); - b1.OwnsOne("Address", "ShippingAddress", b2 => - { - b2.Property("OrderId") - .ValueGeneratedOnAdd(); + b1.OwnsOne( + "Address", "ShippingAddress", b2 => + { + b2.Property("OrderId") + .ValueGeneratedOnAdd(); - b2.HasKey("OrderId"); + b2.HasKey("OrderId"); - b2.ToTable("Order"); + b2.ToTable("Order"); - b2.HasOne("OrderInfo") - .WithOne("ShippingAddress") - .HasForeignKey("Address", "OrderId") - .OnDelete(DeleteBehavior.Cascade); - }); + b2.HasOne("OrderInfo") + .WithOne("ShippingAddress") + .HasForeignKey("Address", "OrderId") + .OnDelete(DeleteBehavior.Cascade); + }); - b1.OwnsOne("Address", "BillingAddress", b2 => - { - b2.Property("OrderId") - .ValueGeneratedOnAdd(); + b1.OwnsOne( + "Address", "BillingAddress", b2 => + { + b2.Property("OrderId") + .ValueGeneratedOnAdd(); - b2.HasKey("OrderId"); + b2.HasKey("OrderId"); - b2.ToTable("Order"); + b2.ToTable("Order"); - b2.HasOne("OrderInfo") - .WithOne("BillingAddress") - .HasForeignKey("Address", "OrderId") - .OnDelete(DeleteBehavior.Cascade); - }); + b2.HasOne("OrderInfo") + .WithOne("BillingAddress") + .HasForeignKey("Address", "OrderId") + .OnDelete(DeleteBehavior.Cascade); + }); }); }); }, @@ -7740,31 +7741,33 @@ public void Old_style_ownership_to_new_style() b1.WithOwner("Order") .HasForeignKey("OrderId"); - b1.OwnsOne("Address", "ShippingAddress", b2 => - { - b2.Property("OrderId") - .ValueGeneratedOnAdd(); + b1.OwnsOne( + "Address", "ShippingAddress", b2 => + { + b2.Property("OrderId") + .ValueGeneratedOnAdd(); - b2.HasKey("OrderId"); + b2.HasKey("OrderId"); - b2.ToTable("Order"); + b2.ToTable("Order"); - b2.WithOwner() - .HasForeignKey("OrderId"); - }); + b2.WithOwner() + .HasForeignKey("OrderId"); + }); - b1.OwnsOne("Address", "BillingAddress", b2 => - { - b2.Property("OrderId") - .ValueGeneratedOnAdd(); + b1.OwnsOne( + "Address", "BillingAddress", b2 => + { + b2.Property("OrderId") + .ValueGeneratedOnAdd(); - b2.HasKey("OrderId"); + b2.HasKey("OrderId"); - b2.ToTable("Order"); + b2.ToTable("Order"); - b2.WithOwner() - .HasForeignKey("OrderId"); - }); + b2.WithOwner() + .HasForeignKey("OrderId"); + }); }); }); }, @@ -8118,7 +8121,7 @@ public Blog Blog public void Create_table_handles_same_name_but_different_schemas_and_identifying_relationship() { Execute( - (ModelBuilder _) => { }, + _ => { }, modelBuilder => modelBuilder .Entity( "Entity1", @@ -8197,9 +8200,9 @@ public void Construction_of_shadow_values_buffer_account_for_shadow_navigations_ b.HasData(new { Id = 1, UserId = 1, LevelId = 1 }); }) .Entity("BaseType") - .HasOne("User", "User") - .WithMany() - .HasForeignKey("UserId"), + .HasOne("User", "User") + .WithMany() + .HasForeignKey("UserId"), modelBuilder => modelBuilder .Entity( "User", @@ -8229,9 +8232,9 @@ public void Construction_of_shadow_values_buffer_account_for_shadow_navigations_ b.HasData(new { Id = 1, UserId = 1, LevelId = 1 }); }) .Entity("BaseType") - .HasOne("User", "User") - .WithMany() - .HasForeignKey("UserId"), + .HasOne("User", "User") + .WithMany() + .HasForeignKey("UserId"), ops => { }); } @@ -8269,9 +8272,9 @@ public void Construction_of_shadow_values_buffer_account_for_shadow_navigations_ b.HasData(new { Id = 1, UserId = 1, Level1Id = 1, Level2Id = 1.0 }); }) .Entity("BaseType") - .HasOne("User", "User") - .WithMany() - .HasForeignKey("UserId"), + .HasOne("User", "User") + .WithMany() + .HasForeignKey("UserId"), modelBuilder => modelBuilder .Entity( "User", @@ -8302,9 +8305,9 @@ public void Construction_of_shadow_values_buffer_account_for_shadow_navigations_ b.HasData(new { Id = 1, UserId = 1, Level1Id = 1, Level2Id = 1.0 }); }) .Entity("BaseType") - .HasOne("User", "User") - .WithMany() - .HasForeignKey("UserId"), + .HasOne("User", "User") + .WithMany() + .HasForeignKey("UserId"), ops => { }); } diff --git a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTestBase.cs b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTestBase.cs index 16ae20f4290..0b5f5983b76 100644 --- a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTestBase.cs +++ b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTestBase.cs @@ -40,7 +40,8 @@ protected void Execute( Action> assertActionUp, Action> assertActionDown, bool skipSourceConventions = false) - => Execute(buildCommonAction, buildSourceAction, buildTargetAction, assertActionUp, assertActionDown, null, skipSourceConventions); + => Execute( + buildCommonAction, buildSourceAction, buildTargetAction, assertActionUp, assertActionDown, null, skipSourceConventions); protected void Execute( Action buildCommonAction, diff --git a/test/EFCore.Relational.Tests/TestUtilities/RelationalTestHelpers.cs b/test/EFCore.Relational.Tests/TestUtilities/RelationalTestHelpers.cs index 0a93a11dcd9..18552a9eda0 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/RelationalTestHelpers.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/RelationalTestHelpers.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.EntityFrameworkCore.Diagnostics; -using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; using Microsoft.Extensions.DependencyInjection; diff --git a/test/EFCore.Relational.Tests/Update/CommandBatchPreparerTest.cs b/test/EFCore.Relational.Tests/Update/CommandBatchPreparerTest.cs index b23f3ae2ece..367dda796bf 100644 --- a/test/EFCore.Relational.Tests/Update/CommandBatchPreparerTest.cs +++ b/test/EFCore.Relational.Tests/Update/CommandBatchPreparerTest.cs @@ -796,7 +796,7 @@ public void BatchCommands_creates_batch_on_incomplete_updates_for_shared_table_n var modelData = new UpdateAdapter(stateManager); var commandBatches = CreateCommandBatchPreparer(updateAdapter: modelData, sensitiveLogging: true) - .BatchCommands(new[] { firstEntry }, modelData).ToArray(); + .BatchCommands(new[] { firstEntry }, modelData).ToArray(); Assert.Single(commandBatches); Assert.Equal(1, commandBatches.First().ModificationCommands.Count); @@ -890,7 +890,7 @@ public void BatchCommands_creates_batch_on_incomplete_updates_for_shared_table_n var modelData = new UpdateAdapter(stateManager); var commandBatches = CreateCommandBatchPreparer(updateAdapter: modelData, sensitiveLogging: true) - .BatchCommands(new[] { firstEntry, secondEntry }, modelData).ToArray(); + .BatchCommands(new[] { firstEntry, secondEntry }, modelData).ToArray(); Assert.Equal(2, commandBatches.Length); Assert.Equal(1, commandBatches.First().ModificationCommands.Count); diff --git a/test/EFCore.Relational.Tests/Update/ReaderModificationCommandBatchTest.cs b/test/EFCore.Relational.Tests/Update/ReaderModificationCommandBatchTest.cs index a35a6c1e760..0d5e6e6a3a4 100644 --- a/test/EFCore.Relational.Tests/Update/ReaderModificationCommandBatchTest.cs +++ b/test/EFCore.Relational.Tests/Update/ReaderModificationCommandBatchTest.cs @@ -373,7 +373,8 @@ public void PopulateParameters_creates_parameter_for_write_ModificationCommand() entry, property, parameterNameGenerator.GenerateNext, - isRead: false, isWrite: true, isKey: false, isCondition: false, isConcurrencyToken: false, sensitiveLoggingEnabled: true) + isRead: false, isWrite: true, isKey: false, isCondition: false, isConcurrencyToken: false, + sensitiveLoggingEnabled: true) })); var storeCommand = batch.CreateStoreCommandBase(); @@ -406,7 +407,8 @@ public void PopulateParameters_creates_parameter_for_condition_ModificationComma entry, property, parameterNameGenerator.GenerateNext, - isRead: false, isWrite: false, isKey: false, isCondition: true, isConcurrencyToken: false, sensitiveLoggingEnabled: true) + isRead: false, isWrite: false, isKey: false, isCondition: true, isConcurrencyToken: false, + sensitiveLoggingEnabled: true) })); var storeCommand = batch.CreateStoreCommandBase(); @@ -439,7 +441,8 @@ public void PopulateParameters_creates_parameters_for_write_and_condition_Modifi entry, property, parameterNameGenerator.GenerateNext, - isRead: false, isWrite: true, isKey: false, isCondition: true, isConcurrencyToken: false, sensitiveLoggingEnabled: true) + isRead: false, isWrite: true, isKey: false, isCondition: true, isConcurrencyToken: false, + sensitiveLoggingEnabled: true) })); var storeCommand = batch.CreateStoreCommandBase(); @@ -474,7 +477,8 @@ public void PopulateParameters_does_not_create_parameter_for_read_ModificationCo entry, property, parameterNameGenerator.GenerateNext, - isRead: true, isWrite: false, isKey: false, isCondition: false, isConcurrencyToken: false, sensitiveLoggingEnabled: true) + isRead: true, isWrite: false, isKey: false, isCondition: false, isConcurrencyToken: false, + sensitiveLoggingEnabled: true) })); var storeCommand = batch.CreateStoreCommandBase(); diff --git a/test/EFCore.Specification.Tests/BuiltInDataTypesTestBase.cs b/test/EFCore.Specification.Tests/BuiltInDataTypesTestBase.cs index e8e93f1e17b..e30cf2de2fa 100644 --- a/test/EFCore.Specification.Tests/BuiltInDataTypesTestBase.cs +++ b/test/EFCore.Specification.Tests/BuiltInDataTypesTestBase.cs @@ -1986,11 +1986,7 @@ public virtual void Can_read_back_mapped_enum_from_collection_first_or_default() using (var context = CreateContext()) { var query = from animal in context.Set() - select new - { - animal.Id, - animal.IdentificationMethods.FirstOrDefault().Method - }; + select new { animal.Id, animal.IdentificationMethods.FirstOrDefault().Method }; var result = query.SingleOrDefault(); Assert.Equal(IdentificationMethod.EarTag, result.Method); @@ -2004,10 +2000,7 @@ public virtual void Can_read_back_bool_mapped_as_int_through_navigation() { var query = from animal in context.Set() where animal.Details != null - select new - { - animal.Details.BoolField - }; + select new { animal.Details.BoolField }; var result = Assert.Single(query.ToList()); Assert.True(result.BoolField); @@ -2251,28 +2244,15 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con modelBuilder.Entity() .HasData( - new Animal - { - Id = 1 - }); + new Animal { Id = 1 }); modelBuilder.Entity() .HasData( - new AnimalDetails - { - Id = 1, - AnimalId = 1, - BoolField = true - }); + new AnimalDetails { Id = 1, AnimalId = 1, BoolField = true }); modelBuilder.Entity() .HasData( - new AnimalIdentification - { - Id = 1, - AnimalId = 1, - Method = IdentificationMethod.EarTag, - }); + new AnimalIdentification { Id = 1, AnimalId = 1, Method = IdentificationMethod.EarTag }); } protected static void MakeRequired(ModelBuilder modelBuilder) diff --git a/test/EFCore.Specification.Tests/CustomConvertersTestBase.cs b/test/EFCore.Specification.Tests/CustomConvertersTestBase.cs index 5977b003258..0676643e9d9 100644 --- a/test/EFCore.Specification.Tests/CustomConvertersTestBase.cs +++ b/test/EFCore.Specification.Tests/CustomConvertersTestBase.cs @@ -105,8 +105,7 @@ public virtual void Can_query_and_update_with_nullable_converter_on_primary_key( var principal = context.Add( new NullablePrincipal { - Id = 1, - Dependents = new List { new NonNullableDependent { Id = 1 } } + Id = 1, Dependents = new List { new NonNullableDependent { Id = 1 } } }) .Entity; @@ -358,16 +357,17 @@ public virtual async Task Can_query_custom_type_not_mapped_by_default_equality(b { using (var context = CreateContext()) { - context.Set().Add(new SimpleCounter() { CounterId = 1, StyleKey = "Swag" }); + context.Set().Add(new SimpleCounter { CounterId = 1, StyleKey = "Swag" }); context.SaveChanges(); } using (var context = CreateContext()) { var query = context.Set() - .Where(c => c.StyleKey == "Swag" - && c.IsTest == false - && c.Discriminator == new Dictionary()); + .Where( + c => c.StyleKey == "Swag" + && c.IsTest == false + && c.Discriminator == new Dictionary()); var result = isAsync ? await query.SingleAsync() : query.Single(); Assert.NotNull(result); @@ -390,13 +390,8 @@ public virtual void Field_on_derived_type_retrieved_via_cast_applies_value_conve using (var context = CreateContext()) { var query = context.Set() - .Where(b => b.BlogId == 2) - .Select(x => new - { - BlogId = x.BlogId, - Url = x.Url, - RssUrl = x is RssBlog ? ((RssBlog)x).RssUrl : null - }).ToList(); + .Where(b => b.BlogId == 2) + .Select(x => new { x.BlogId, x.Url, RssUrl = x is RssBlog ? ((RssBlog)x).RssUrl : null }).ToList(); var result = Assert.Single(query); Assert.Equal("http://rssblog.com/rss", result.RssUrl); @@ -456,7 +451,8 @@ public virtual void Where_bool_gets_converted_to_equality_when_value_conversion_ public virtual void Value_conversion_with_property_named_value() { using var context = CreateContext(); - Assert.Throws(() => context.Set().SingleOrDefault(e => e.Wrapper.Value == "foo")); + Assert.Throws( + () => context.Set().SingleOrDefault(e => e.Wrapper.Value == "foo")); } protected class Blog @@ -861,12 +857,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con b.Property(e => e.Url).HasConversion(urlConverter); b.Property(e => e.IsVisible).HasConversion(new BoolToStringConverter("N", "Y")); b.HasData( - new Blog - { - BlogId = 1, - Url = "http://blog.com", - IsVisible = true - }); + new Blog { BlogId = 1, Url = "http://blog.com", IsVisible = true }); }); modelBuilder.Entity( @@ -874,27 +865,13 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con { b.Property(e => e.RssUrl).HasConversion(urlConverter); b.HasData( - new RssBlog - { - BlogId = 2, - Url = "http://rssblog.com", - RssUrl = "http://rssblog.com/rss", - IsVisible = false - }); + new RssBlog { BlogId = 2, Url = "http://rssblog.com", RssUrl = "http://rssblog.com/rss", IsVisible = false }); }); modelBuilder.Entity() .HasData( - new Post - { - PostId = 1, - BlogId = 1 - }, - new Post - { - PostId = 2, - BlogId = null - }); + new Post { PostId = 1, BlogId = 1 }, + new Post { PostId = 2, BlogId = null }); modelBuilder.Entity( e => @@ -904,11 +881,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con w => w.Value, v => new ValueWrapper { Value = v } ); - e.HasData(new EntityWithValueWrapper - { - Id = 1, - Wrapper = new ValueWrapper { Value = "foo" } - }); + e.HasData(new EntityWithValueWrapper { Id = 1, Wrapper = new ValueWrapper { Value = "foo" } }); }); } @@ -935,7 +908,8 @@ public static IDictionary Deserialize(string s) private class OrderIdEntityFrameworkValueConverter : ValueConverter { - public OrderIdEntityFrameworkValueConverter() : this(null) + public OrderIdEntityFrameworkValueConverter() + : this(null) { } @@ -951,7 +925,10 @@ public OrderIdEntityFrameworkValueConverter(ConverterMappingHints mappingHints) private class UrlSchemeRemover : ValueConverter { - public UrlSchemeRemover() : base(x => x.Remove(0, 7), x => "http://" + x) { } + public UrlSchemeRemover() + : base(x => x.Remove(0, 7), x => "http://" + x) + { + } } } } diff --git a/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs b/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs index 6673f618705..aa8d823a6de 100644 --- a/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs +++ b/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs @@ -710,7 +710,8 @@ public virtual ModelBuilder Key_property_is_not_used_for_FK_when_set_by_annotati modelBuilder.Entity(); var toy = modelBuilder.Entity(); - Assert.DoesNotContain(toy.Metadata.GetForeignKeys(), fk => fk.IsUnique == false && fk.Properties.Any(p => p.Name == nameof(Toy.IdRow))); + Assert.DoesNotContain( + toy.Metadata.GetForeignKeys(), fk => fk.IsUnique == false && fk.Properties.Any(p => p.Name == nameof(Toy.IdRow))); Validate(modelBuilder); @@ -1892,12 +1893,12 @@ public virtual void InversePropertyAttribute_pointing_to_same_nav_on_base_causes Assert.Equal( CoreStrings.WarningAsErrorTemplate( CoreEventId.MultipleInversePropertiesSameTargetWarning, - CoreResources.LogMultipleInversePropertiesSameTarget(new TestLogger()) - .GenerateMessage( - $"{nameof(MultipleAnswersRepeatingInverse)}.{nameof(MultipleAnswersRepeatingInverse.Answers)}," - + $" {nameof(MultipleAnswersInverse)}.{nameof(MultipleAnswersInverse.Answers)}", - nameof(PartialAnswerInverse.Answer)), - "CoreEventId.MultipleInversePropertiesSameTargetWarning"), + CoreResources.LogMultipleInversePropertiesSameTarget(new TestLogger()) + .GenerateMessage( + $"{nameof(MultipleAnswersRepeatingInverse)}.{nameof(MultipleAnswersRepeatingInverse.Answers)}," + + $" {nameof(MultipleAnswersInverse)}.{nameof(MultipleAnswersInverse.Answers)}", + nameof(PartialAnswerInverse.Answer)), + "CoreEventId.MultipleInversePropertiesSameTargetWarning"), Assert.Throws(() => modelBuilder.FinalizeModel()).Message); } @@ -1908,7 +1909,9 @@ private class PartialAnswerInverse public virtual AnswerBaseInverse Answer { get; set; } } - private class PartialAnswerRepeatingInverse : PartialAnswerInverse { } + private class PartialAnswerRepeatingInverse : PartialAnswerInverse + { + } private abstract class AnswerBaseInverse { diff --git a/test/EFCore.Specification.Tests/GraphUpdatesFixtureBase.cs b/test/EFCore.Specification.Tests/GraphUpdatesFixtureBase.cs index 2501c856518..09aeb7555ce 100644 --- a/test/EFCore.Specification.Tests/GraphUpdatesFixtureBase.cs +++ b/test/EFCore.Specification.Tests/GraphUpdatesFixtureBase.cs @@ -431,8 +431,7 @@ protected virtual object CreateFullGraph() AlternateId = Guid.NewGuid(), Children = new ObservableHashSet(ReferenceEqualityComparer.Instance) { - new RequiredAk2 { AlternateId = Guid.NewGuid() }, - new RequiredAk2 { AlternateId = Guid.NewGuid() } + new RequiredAk2 { AlternateId = Guid.NewGuid() }, new RequiredAk2 { AlternateId = Guid.NewGuid() } }, CompositeChildren = new ObservableHashSet(ReferenceEqualityComparer.Instance) @@ -445,8 +444,7 @@ protected virtual object CreateFullGraph() AlternateId = Guid.NewGuid(), Children = new ObservableHashSet(ReferenceEqualityComparer.Instance) { - new RequiredAk2 { AlternateId = Guid.NewGuid() }, - new RequiredAk2 { AlternateId = Guid.NewGuid() } + new RequiredAk2 { AlternateId = Guid.NewGuid() }, new RequiredAk2 { AlternateId = Guid.NewGuid() } }, CompositeChildren = new ObservableHashSet(ReferenceEqualityComparer.Instance) @@ -463,8 +461,7 @@ protected virtual object CreateFullGraph() AlternateId = Guid.NewGuid(), Children = new ObservableHashSet(ReferenceEqualityComparer.Instance) { - new OptionalAk2 { AlternateId = Guid.NewGuid() }, - new OptionalAk2 { AlternateId = Guid.NewGuid() } + new OptionalAk2 { AlternateId = Guid.NewGuid() }, new OptionalAk2 { AlternateId = Guid.NewGuid() } }, CompositeChildren = new ObservableHashSet(ReferenceEqualityComparer.Instance) @@ -477,8 +474,7 @@ protected virtual object CreateFullGraph() AlternateId = Guid.NewGuid(), Children = new ObservableHashSet(ReferenceEqualityComparer.Instance) { - new OptionalAk2 { AlternateId = Guid.NewGuid() }, - new OptionalAk2 { AlternateId = Guid.NewGuid() } + new OptionalAk2 { AlternateId = Guid.NewGuid() }, new OptionalAk2 { AlternateId = Guid.NewGuid() } }, CompositeChildren = new ObservableHashSet(ReferenceEqualityComparer.Instance) diff --git a/test/EFCore.Specification.Tests/InterceptionTestBase.cs b/test/EFCore.Specification.Tests/InterceptionTestBase.cs index 1dd1909dacf..e678eed898d 100644 --- a/test/EFCore.Specification.Tests/InterceptionTestBase.cs +++ b/test/EFCore.Specification.Tests/InterceptionTestBase.cs @@ -97,7 +97,8 @@ public void Dispose() } } - public class TestDiagnosticListener : ITestDiagnosticListener, IObserver, + public class TestDiagnosticListener : ITestDiagnosticListener, + IObserver, IObserver> { private readonly DbContextId _contextId; diff --git a/test/EFCore.Specification.Tests/LazyLoadProxyTestBase.cs b/test/EFCore.Specification.Tests/LazyLoadProxyTestBase.cs index e4a84ecb2bb..a39ffb8b88a 100644 --- a/test/EFCore.Specification.Tests/LazyLoadProxyTestBase.cs +++ b/test/EFCore.Specification.Tests/LazyLoadProxyTestBase.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; -using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -196,6 +195,7 @@ public virtual void Attached_collections_are_not_marked_as_loaded(EntityState st { context.Entry(child).State = state; } + context.Entry(parent).State = state; context.ChangeTracker.LazyLoadingEnabled = true; @@ -2118,12 +2118,7 @@ private static class DtoFactory { public static object CreateDto(Parent parent) { - return new - { - parent.Id, - parent.Single, - parent.Single.ParentId - }; + return new { parent.Id, parent.Single, parent.Single.ParentId }; } } diff --git a/test/EFCore.Specification.Tests/LoadTestBase.cs b/test/EFCore.Specification.Tests/LoadTestBase.cs index 0c2c87c42e1..1ee75f10566 100644 --- a/test/EFCore.Specification.Tests/LoadTestBase.cs +++ b/test/EFCore.Specification.Tests/LoadTestBase.cs @@ -155,6 +155,7 @@ public virtual void Attached_collections_are_not_marked_as_loaded(EntityState st { context.Entry(child).State = state; } + context.Entry(parent).State = state; context.ChangeTracker.LazyLoadingEnabled = true; diff --git a/test/EFCore.Specification.Tests/MusicStoreTestBase.cs b/test/EFCore.Specification.Tests/MusicStoreTestBase.cs index 0547230993d..26baf02c2eb 100644 --- a/test/EFCore.Specification.Tests/MusicStoreTestBase.cs +++ b/test/EFCore.Specification.Tests/MusicStoreTestBase.cs @@ -25,22 +25,23 @@ public async Task Browse_ReturnsViewWithGenre() { using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - const string genreName = "Genre 1"; - CreateTestGenres(numberOfGenres: 3, numberOfAlbums: 3, context: context); + using (Fixture.BeginTransaction(context)) + { + const string genreName = "Genre 1"; + CreateTestGenres(numberOfGenres: 3, numberOfAlbums: 3, context: context); - var controller = new StoreController(context); + var controller = new StoreController(context); - var result = await controller.Browse(genreName); + var result = await controller.Browse(genreName); - Assert.Equal(genreName, result.Name); - Assert.NotNull(result.Albums); - Assert.Equal(3, result.Albums.Count); - } - }); + Assert.Equal(genreName, result.Name); + Assert.NotNull(result.Albums); + Assert.Equal(3, result.Albums.Count); + } + }); } } @@ -49,19 +50,20 @@ public async Task Index_CreatesViewWithGenres() { using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - CreateTestGenres(numberOfGenres: 10, numberOfAlbums: 1, context: context); + using (Fixture.BeginTransaction(context)) + { + CreateTestGenres(numberOfGenres: 10, numberOfAlbums: 1, context: context); - var controller = new StoreController(context); + var controller = new StoreController(context); - var result = await controller.Index(); + var result = await controller.Index(); - Assert.Equal(10, result.Count); - } - }); + Assert.Equal(10, result.Count); + } + }); } } @@ -70,25 +72,26 @@ public async Task Details_ReturnsAlbumDetail() { using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var genres = CreateTestGenres(numberOfGenres: 3, numberOfAlbums: 3, context: context); - var albumId = genres.First().Albums[2].AlbumId; + using (Fixture.BeginTransaction(context)) + { + var genres = CreateTestGenres(numberOfGenres: 3, numberOfAlbums: 3, context: context); + var albumId = genres.First().Albums[2].AlbumId; - var controller = new StoreController(context); + var controller = new StoreController(context); - var result = await controller.Details(albumId); + var result = await controller.Details(albumId); - Assert.NotNull(result.Genre); - var genre = genres.SingleOrDefault(g => g.GenreId == result.GenreId); - Assert.NotNull(genre); - Assert.NotNull(genre.Albums.SingleOrDefault(a => a.AlbumId == albumId)); - Assert.NotNull(result.Artist); - Assert.NotEqual(0, result.ArtistId); - } - }); + Assert.NotNull(result.Genre); + var genre = genres.SingleOrDefault(g => g.GenreId == result.GenreId); + Assert.NotNull(genre); + Assert.NotNull(genre.Albums.SingleOrDefault(a => a.AlbumId == albumId)); + Assert.NotNull(result.Artist); + Assert.NotEqual(0, result.ArtistId); + } + }); } } @@ -117,26 +120,27 @@ public async Task Index_GetsSixTopAlbums() { using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var controller = new HomeController(); + using (Fixture.BeginTransaction(context)) + { + var controller = new HomeController(); - var albums = TestAlbumDataProvider.GetAlbums(); + var albums = TestAlbumDataProvider.GetAlbums(); - foreach (var album in albums) - { - context.Add(album); - } + foreach (var album in albums) + { + context.Add(album); + } - context.SaveChanges(); + context.SaveChanges(); - var result = await controller.Index(context); + var result = await controller.Index(context); - Assert.Equal(6, result.Count); - } - }); + Assert.Equal(6, result.Count); + } + }); } } @@ -144,14 +148,17 @@ private static class TestAlbumDataProvider { public static Album[] GetAlbums() { - var genres = Enumerable.Range(1, 10).Select(n => - new Genre { Name = "Genre Name " + n }).ToArray(); + var genres = Enumerable.Range(1, 10).Select( + n => + new Genre { Name = "Genre Name " + n }).ToArray(); - var artists = Enumerable.Range(1, 10).Select(n => - new Artist { Name = "Artist Name " + n }).ToArray(); + var artists = Enumerable.Range(1, 10).Select( + n => + new Artist { Name = "Artist Name " + n }).ToArray(); - var albums = Enumerable.Range(1, 10).Select(n => - new Album { Artist = artists[n - 1], Genre = genres[n - 1], Title = "Greatest Hits" }).ToArray(); + var albums = Enumerable.Range(1, 10).Select( + n => + new Album { Artist = artists[n - 1], Genre = genres[n - 1], Title = "Greatest Hits" }).ToArray(); return albums; } @@ -162,23 +169,24 @@ public async Task GenreMenuComponent_Returns_NineGenres() { using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var genreMenuComponent = new GenreMenuComponent(context); + using (Fixture.BeginTransaction(context)) + { + var genreMenuComponent = new GenreMenuComponent(context); - var genres = Enumerable.Range(1, 10).Select( - n => new Genre { Name = $"G{n}" }); + var genres = Enumerable.Range(1, 10).Select( + n => new Genre { Name = $"G{n}" }); - context.AddRange(genres); - context.SaveChanges(); + context.AddRange(genres); + context.SaveChanges(); - var result = await genreMenuComponent.InvokeAsync(); + var result = await genreMenuComponent.InvokeAsync(); - Assert.Equal(9, result.Count); - } - }); + Assert.Equal(9, result.Count); + } + }); } } @@ -193,22 +201,23 @@ public async Task AddressAndPayment_RedirectToCompleteWhenSuccessful() using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var cartItems = CreateTestCartItems(cartId, itemPrice: 10, numberOfItems: 1); - context.AddRange(cartItems.Select(n => n.Album).Distinct()); - context.AddRange(cartItems); - context.SaveChanges(); + using (Fixture.BeginTransaction(context)) + { + var cartItems = CreateTestCartItems(cartId, itemPrice: 10, numberOfItems: 1); + context.AddRange(cartItems.Select(n => n.Album).Distinct()); + context.AddRange(cartItems); + context.SaveChanges(); - var controller = new CheckoutController(formCollection); + var controller = new CheckoutController(formCollection); - var result = await controller.AddressAndPayment(context, cartId, order); + var result = await controller.AddressAndPayment(context, cartId, order); - Assert.Equal(order.OrderId, result); - } - }); + Assert.Equal(order.OrderId, result); + } + }); } } @@ -219,18 +228,19 @@ public async Task AddressAndPayment_ReturnsOrderIfInvalidPromoCode() using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var controller = new CheckoutController(); - var order = CreateOrder(); + using (Fixture.BeginTransaction(context)) + { + var controller = new CheckoutController(); + var order = CreateOrder(); - var result = await controller.AddressAndPayment(context, cartId, order); + var result = await controller.AddressAndPayment(context, cartId, order); - Assert.Null(result); - } - }); + Assert.Null(result); + } + }); } } @@ -254,20 +264,21 @@ public async Task Complete_ReturnsOrderIdIfValid() { using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var controller = new CheckoutController(); + using (Fixture.BeginTransaction(context)) + { + var controller = new CheckoutController(); - var order = context.Add(CreateOrder()).Entity; - context.SaveChanges(); + var order = context.Add(CreateOrder()).Entity; + context.SaveChanges(); - var result = await controller.Complete(context, order.OrderId); + var result = await controller.Complete(context, order.OrderId); - Assert.Equal(order.OrderId, result); - } - }); + Assert.Equal(order.OrderId, result); + } + }); } } @@ -276,17 +287,18 @@ public async Task Complete_ReturnsErrorIfInvalidOrder() { using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var controller = new CheckoutController(); + using (Fixture.BeginTransaction(context)) + { + var controller = new CheckoutController(); - var result = await controller.Complete(context, -3333); + var result = await controller.Complete(context, -3333); - Assert.Equal("Error", result); - } - }); + Assert.Equal("Error", result); + } + }); } } @@ -299,30 +311,29 @@ public async Task CartSummaryComponent_returns_items() using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var album = new Album + using (Fixture.BeginTransaction(context)) { - Title = albumTitle, - Artist = new Artist { Name = "Kung Fu Kenny" }, - Genre = new Genre { Name = "Rap" } - }; + var album = new Album + { + Title = albumTitle, Artist = new Artist { Name = "Kung Fu Kenny" }, Genre = new Genre { Name = "Rap" } + }; - var cartItems = Enumerable.Range(1, itemCount).Select( - n => - new CartItem { Album = album, Count = 1, CartId = cartId }).ToArray(); + var cartItems = Enumerable.Range(1, itemCount).Select( + n => + new CartItem { Album = album, Count = 1, CartId = cartId }).ToArray(); - context.AddRange(cartItems); - context.SaveChanges(); + context.AddRange(cartItems); + context.SaveChanges(); - var result = await new CartSummaryComponent(context, cartId).InvokeAsync(); + var result = await new CartSummaryComponent(context, cartId).InvokeAsync(); - Assert.Equal(itemCount, result.CartCount); - Assert.Equal(albumTitle, result.CartSummary); - } - }); + Assert.Equal(itemCount, result.CartCount); + Assert.Equal(albumTitle, result.CartSummary); + } + }); } } @@ -331,37 +342,38 @@ public async void Music_store_project_to_mapped_entity() { using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var albums = CreateTestAlbums( - 10, - new Artist { Name = "Kung Fu Kenny" }, new Genre { Name = "Rap" }); - - context.Albums.AddRange(albums); - await context.SaveChangesAsync(); - - var q = from album in context.Albums - join genre in context.Genres on album.GenreId equals genre.GenreId - join artist in context.Artists on album.ArtistId equals artist.ArtistId - select new Album - { - ArtistId = album.ArtistId, - AlbumArtUrl = album.AlbumArtUrl, - AlbumId = album.AlbumId, - GenreId = album.GenreId, - Price = album.Price, - Title = album.Title, - Artist = new Artist { ArtistId = album.ArtistId, Name = artist.Name }, - Genre = new Genre { GenreId = album.GenreId, Name = genre.Name } - }; - - var foundAlbums = q.ToList(); - - Assert.Equal(10, foundAlbums.Count); - } - }); + using (Fixture.BeginTransaction(context)) + { + var albums = CreateTestAlbums( + 10, + new Artist { Name = "Kung Fu Kenny" }, new Genre { Name = "Rap" }); + + context.Albums.AddRange(albums); + await context.SaveChangesAsync(); + + var q = from album in context.Albums + join genre in context.Genres on album.GenreId equals genre.GenreId + join artist in context.Artists on album.ArtistId equals artist.ArtistId + select new Album + { + ArtistId = album.ArtistId, + AlbumArtUrl = album.AlbumArtUrl, + AlbumId = album.AlbumId, + GenreId = album.GenreId, + Price = album.Price, + Title = album.Title, + Artist = new Artist { ArtistId = album.ArtistId, Name = artist.Name }, + Genre = new Genre { GenreId = album.GenreId, Name = genre.Name } + }; + + var foundAlbums = q.ToList(); + + Assert.Equal(10, foundAlbums.Count); + } + }); } } @@ -374,28 +386,29 @@ public async Task RemoveFromCart_removes_items_from_cart() using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var cartItems = CreateTestCartItems(cartId, unitPrice, numberOfItems); - context.AddRange(cartItems.Select(n => n.Album).Distinct()); - context.AddRange(cartItems); - context.SaveChanges(); + using (Fixture.BeginTransaction(context)) + { + var cartItems = CreateTestCartItems(cartId, unitPrice, numberOfItems); + context.AddRange(cartItems.Select(n => n.Album).Distinct()); + context.AddRange(cartItems); + context.SaveChanges(); - var controller = new ShoppingCartController(context, cartId); + var controller = new ShoppingCartController(context, cartId); - var cartItemId = cartItems[2].CartItemId; - var viewModel = await controller.RemoveFromCart(cartItemId); + var cartItemId = cartItems[2].CartItemId; + var viewModel = await controller.RemoveFromCart(cartItemId); - Assert.Equal(numberOfItems - 1, viewModel.CartCount); - Assert.Equal((numberOfItems - 1) * 10, viewModel.CartTotal); - Assert.Equal("Greatest Hits has been removed from your shopping cart.", viewModel.Message); + Assert.Equal(numberOfItems - 1, viewModel.CartCount); + Assert.Equal((numberOfItems - 1) * 10, viewModel.CartTotal); + Assert.Equal("Greatest Hits has been removed from your shopping cart.", viewModel.Message); - var cart = ShoppingCart.GetCart(context, cartId); - Assert.DoesNotContain((await cart.GetCartItems()), c => c.CartItemId == cartItemId); - } - }); + var cart = ShoppingCart.GetCart(context, cartId); + Assert.DoesNotContain((await cart.GetCartItems()), c => c.CartItemId == cartItemId); + } + }); } } @@ -406,17 +419,18 @@ public async Task Cart_is_empty_when_no_items_have_been_added(string cartId) { using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var controller = new ShoppingCartController(context, cartId); - var viewModel = await controller.Index(); + using (Fixture.BeginTransaction(context)) + { + var controller = new ShoppingCartController(context, cartId); + var viewModel = await controller.Index(); - Assert.Empty(viewModel.CartItems); - Assert.Equal(0, viewModel.CartTotal); - } - }); + Assert.Empty(viewModel.CartItems); + Assert.Equal(0, viewModel.CartTotal); + } + }); } } @@ -427,26 +441,27 @@ public async Task Cart_has_items_once_they_have_been_added() using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var cartItems = CreateTestCartItems( - cartId, - itemPrice: 10, - numberOfItems: 5); + using (Fixture.BeginTransaction(context)) + { + var cartItems = CreateTestCartItems( + cartId, + itemPrice: 10, + numberOfItems: 5); - context.AddRange(cartItems.Select(n => n.Album).Distinct()); - context.AddRange(cartItems); - context.SaveChanges(); + context.AddRange(cartItems.Select(n => n.Album).Distinct()); + context.AddRange(cartItems); + context.SaveChanges(); - var controller = new ShoppingCartController(context, cartId); - var viewModel = await controller.Index(); + var controller = new ShoppingCartController(context, cartId); + var viewModel = await controller.Index(); - Assert.Equal(5, viewModel.CartItems.Count); - Assert.Equal(5 * 10, viewModel.CartTotal); - } - }); + Assert.Equal(5, viewModel.CartItems.Count); + Assert.Equal(5 * 10, viewModel.CartTotal); + } + }); } } @@ -457,26 +472,27 @@ public async Task Can_add_items_to_cart() using (var context = CreateContext()) { - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (Fixture.BeginTransaction(context)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - var albums = CreateTestAlbums( - 10, - new Artist { Name = "Kung Fu Kenny" }, new Genre { Name = "Rap" }); + using (Fixture.BeginTransaction(context)) + { + var albums = CreateTestAlbums( + 10, + new Artist { Name = "Kung Fu Kenny" }, new Genre { Name = "Rap" }); - context.AddRange(albums); - context.SaveChanges(); + context.AddRange(albums); + context.SaveChanges(); - var controller = new ShoppingCartController(context, cartId); - var albumId = albums[2].AlbumId; - await controller.AddToCart(albumId); + var controller = new ShoppingCartController(context, cartId); + var albumId = albums[2].AlbumId; + await controller.AddToCart(albumId); - var cart = ShoppingCart.GetCart(context, cartId); - Assert.Single(await cart.GetCartItems()); - Assert.Equal(albumId, (await cart.GetCartItems()).Single().AlbumId); - } - }); + var cart = ShoppingCart.GetCart(context, cartId); + Assert.Single(await cart.GetCartItems()); + Assert.Equal(albumId, (await cart.GetCartItems()).Single().AlbumId); + } + }); } } diff --git a/test/EFCore.Specification.Tests/ProxyGraphUpdatesFixtureBase.cs b/test/EFCore.Specification.Tests/ProxyGraphUpdatesFixtureBase.cs index e1e3108b315..f2fa3a029a4 100644 --- a/test/EFCore.Specification.Tests/ProxyGraphUpdatesFixtureBase.cs +++ b/test/EFCore.Specification.Tests/ProxyGraphUpdatesFixtureBase.cs @@ -406,8 +406,7 @@ protected virtual object CreateFullGraph() AlternateId = Guid.NewGuid(), Children = new ObservableHashSet(ReferenceEqualityComparer.Instance) { - new RequiredAk2 { AlternateId = Guid.NewGuid() }, - new RequiredAk2 { AlternateId = Guid.NewGuid() } + new RequiredAk2 { AlternateId = Guid.NewGuid() }, new RequiredAk2 { AlternateId = Guid.NewGuid() } }, CompositeChildren = new ObservableHashSet(ReferenceEqualityComparer.Instance) @@ -420,8 +419,7 @@ protected virtual object CreateFullGraph() AlternateId = Guid.NewGuid(), Children = new ObservableHashSet(ReferenceEqualityComparer.Instance) { - new RequiredAk2 { AlternateId = Guid.NewGuid() }, - new RequiredAk2 { AlternateId = Guid.NewGuid() } + new RequiredAk2 { AlternateId = Guid.NewGuid() }, new RequiredAk2 { AlternateId = Guid.NewGuid() } }, CompositeChildren = new ObservableHashSet(ReferenceEqualityComparer.Instance) @@ -438,8 +436,7 @@ protected virtual object CreateFullGraph() AlternateId = Guid.NewGuid(), Children = new ObservableHashSet(ReferenceEqualityComparer.Instance) { - new OptionalAk2 { AlternateId = Guid.NewGuid() }, - new OptionalAk2 { AlternateId = Guid.NewGuid() } + new OptionalAk2 { AlternateId = Guid.NewGuid() }, new OptionalAk2 { AlternateId = Guid.NewGuid() } }, CompositeChildren = new ObservableHashSet(ReferenceEqualityComparer.Instance) @@ -452,8 +449,7 @@ protected virtual object CreateFullGraph() AlternateId = Guid.NewGuid(), Children = new ObservableHashSet(ReferenceEqualityComparer.Instance) { - new OptionalAk2 { AlternateId = Guid.NewGuid() }, - new OptionalAk2 { AlternateId = Guid.NewGuid() } + new OptionalAk2 { AlternateId = Guid.NewGuid() }, new OptionalAk2 { AlternateId = Guid.NewGuid() } }, CompositeChildren = new ObservableHashSet(ReferenceEqualityComparer.Instance) diff --git a/test/EFCore.Specification.Tests/Query/ComplexNavigationsQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/ComplexNavigationsQueryTestBase.cs index 06610af5479..b69e2c9b801 100644 --- a/test/EFCore.Specification.Tests/Query/ComplexNavigationsQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/ComplexNavigationsQueryTestBase.cs @@ -209,7 +209,8 @@ public virtual Task Multi_level_include_one_to_many_optional_and_one_to_many_opt [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task Multi_level_include_correct_PK_is_chosen_as_the_join_predicate_for_queries_that_join_same_table_multiple_times(bool isAsync) + public virtual Task Multi_level_include_correct_PK_is_chosen_as_the_join_predicate_for_queries_that_join_same_table_multiple_times( + bool isAsync) { var expectedIncludes = new List { @@ -487,7 +488,8 @@ public virtual Task Optional_navigation_inside_nested_method_call_translated_to_ where e1.OneToOne_Optional_FK1.Name.ToUpper().StartsWith("L") select e1, ss => from e1 in ss.Set() - where MaybeScalar(e1.OneToOne_Optional_FK1, () => e1.OneToOne_Optional_FK1.Name.ToUpper().StartsWith("L")) == true + where MaybeScalar(e1.OneToOne_Optional_FK1, () => e1.OneToOne_Optional_FK1.Name.ToUpper().StartsWith("L")) + == true select e1, e => e.Id, (e, a) => Assert.Equal(e.Id, a.Id)); @@ -503,7 +505,9 @@ public virtual Task Method_call_on_optional_navigation_translates_to_null_condit where e1.OneToOne_Optional_FK1.Name.StartsWith(e1.OneToOne_Optional_FK1.Name) select e1, ss => from e1 in ss.Set() - where MaybeScalar(e1.OneToOne_Optional_FK1, () => e1.OneToOne_Optional_FK1.Name.StartsWith(e1.OneToOne_Optional_FK1.Name)) == true + where MaybeScalar( + e1.OneToOne_Optional_FK1, () => e1.OneToOne_Optional_FK1.Name.StartsWith(e1.OneToOne_Optional_FK1.Name)) + == true select e1, e => e.Id, (e, a) => Assert.Equal(e.Id, a.Id)); @@ -582,7 +586,8 @@ join e2 in ss.Set() on e1.OneToOne_Optional_FK1.Id equals e2.Id select new { Id1 = e1.Id, Id2 = e2.Id }, ss => from e1 in ss.Set() - join e2 in ss.Set() on MaybeScalar(e1.OneToOne_Optional_FK1, () => e1.OneToOne_Optional_FK1.Id) equals e2.Id + join e2 in ss.Set() on MaybeScalar( + e1.OneToOne_Optional_FK1, () => e1.OneToOne_Optional_FK1.Id) equals e2.Id select new { Id1 = e1.Id, Id2 = e2.Id }, e => (e.Id1, e.Id2)); } @@ -639,7 +644,8 @@ join e1 in ss.Set() on e2.Id equals e1.OneToOne_Optional_FK1.Id select new { Id2 = e2.Id, Id1 = e1.Id }, ss => from e2 in ss.Set() - join e1 in ss.Set() on e2.Id equals MaybeScalar(e1.OneToOne_Optional_FK1, () => e1.OneToOne_Optional_FK1.Id) + join e1 in ss.Set() on e2.Id equals MaybeScalar( + e1.OneToOne_Optional_FK1, () => e1.OneToOne_Optional_FK1.Id) select new { Id2 = e2.Id, Id1 = e1.Id }, e => (e.Id2, e.Id1)); } @@ -655,7 +661,8 @@ join e1 in ss.Set() on e2.Id equals e1.OneToOne_Optional_FK1.Id join e3 in ss.Set() on e2.Id equals e3.OneToOne_Optional_FK_Inverse3.Id select new { Id2 = e2.Id, Id1 = e1.Id, Id3 = e3.Id }, ss => from e2 in ss.Set() - join e1 in ss.Set() on e2.Id equals MaybeScalar(e1.OneToOne_Optional_FK1, () => e1.OneToOne_Optional_FK1.Id) + join e1 in ss.Set() on e2.Id equals MaybeScalar( + e1.OneToOne_Optional_FK1, () => e1.OneToOne_Optional_FK1.Id) join e3 in ss.Set() on e2.Id equals MaybeScalar( e3.OneToOne_Optional_FK_Inverse3, () => e3.OneToOne_Optional_FK_Inverse3.Id) select new { Id2 = e2.Id, Id1 = e1.Id, Id3 = e3.Id }, @@ -993,8 +1000,9 @@ public virtual Task Where_nav_prop_reference_optional2(bool isAsync) .Where(e => e.OneToOne_Optional_FK1.Name == "L2 05" || e.OneToOne_Optional_FK1.Name != "L2 42") .Select(e => e.Id), ss => ss.Set() - .Where(e => Maybe(e.OneToOne_Optional_FK1, () => e.OneToOne_Optional_FK1.Name) == "L2 05" - || Maybe(e.OneToOne_Optional_FK1, () => e.OneToOne_Optional_FK1.Name) != "L2 42") + .Where( + e => Maybe(e.OneToOne_Optional_FK1, () => e.OneToOne_Optional_FK1.Name) == "L2 05" + || Maybe(e.OneToOne_Optional_FK1, () => e.OneToOne_Optional_FK1.Name) != "L2 42") .Select(e => e.Id)); } @@ -1107,8 +1115,8 @@ from l3 in ss.Set() ss => from l3 in ss.Set() where Maybe( - l3.OneToOne_Optional_FK_Inverse3, - () => l3.OneToOne_Optional_FK_Inverse3.OneToOne_Optional_FK_Inverse2) == null + l3.OneToOne_Optional_FK_Inverse3, + () => l3.OneToOne_Optional_FK_Inverse3.OneToOne_Optional_FK_Inverse2) == null select l3, e => e.Id, (e, a) => Assert.Equal(e.Id, a.Id)); @@ -1146,7 +1154,8 @@ from l3 in ss.Set() select l3, ss => from l3 in ss.Set() - where null != Maybe(l3.OneToOne_Optional_FK_Inverse3, () => l3.OneToOne_Optional_FK_Inverse3.OneToOne_Optional_FK_Inverse2) + where null != Maybe( + l3.OneToOne_Optional_FK_Inverse3, () => l3.OneToOne_Optional_FK_Inverse3.OneToOne_Optional_FK_Inverse2) select l3, e => e.Id, (e, a) => Assert.Equal(e.Id, a.Id)); @@ -1319,13 +1328,13 @@ public virtual Task Where_complex_predicate_with_with_nav_prop_and_OrElse2(bool select l1.Id, ss => from l1 in ss.Set() where Maybe( - l1.OneToOne_Optional_FK1, - () => Maybe( - l1.OneToOne_Optional_FK1.OneToOne_Required_FK2, - () => l1.OneToOne_Optional_FK1.OneToOne_Required_FK2.Name)) == "L3 05" - || Maybe( - l1.OneToOne_Optional_FK1, - () => l1.OneToOne_Optional_FK1.Name) != "L2 05" + l1.OneToOne_Optional_FK1, + () => Maybe( + l1.OneToOne_Optional_FK1.OneToOne_Required_FK2, + () => l1.OneToOne_Optional_FK1.OneToOne_Required_FK2.Name)) == "L3 05" + || Maybe( + l1.OneToOne_Optional_FK1, + () => l1.OneToOne_Optional_FK1.Name) != "L2 05" select l1.Id); } @@ -1340,13 +1349,13 @@ public virtual Task Where_complex_predicate_with_with_nav_prop_and_OrElse3(bool select l1.Id, ss => from l1 in ss.Set() where Maybe( - l1.OneToOne_Optional_FK1, - () => l1.OneToOne_Optional_FK1.Name) != "L2 05" - || Maybe( - l1.OneToOne_Required_FK1, - () => Maybe( - l1.OneToOne_Required_FK1.OneToOne_Optional_FK2, - () => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.Name)) == "L3 05" + l1.OneToOne_Optional_FK1, + () => l1.OneToOne_Optional_FK1.Name) != "L2 05" + || Maybe( + l1.OneToOne_Required_FK1, + () => Maybe( + l1.OneToOne_Required_FK1.OneToOne_Optional_FK2, + () => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.Name)) == "L3 05" select l1.Id); } @@ -1358,15 +1367,15 @@ public virtual Task Where_complex_predicate_with_with_nav_prop_and_OrElse4(bool isAsync, ss => from l3 in ss.Set() where l3.OneToOne_Optional_FK_Inverse3.Name != "L2 05" - || l3.OneToOne_Required_FK_Inverse3.OneToOne_Optional_FK_Inverse2.Name == "L1 05" + || l3.OneToOne_Required_FK_Inverse3.OneToOne_Optional_FK_Inverse2.Name == "L1 05" select l3.Id, ss => from l3 in ss.Set() where Maybe( - l3.OneToOne_Optional_FK_Inverse3, - () => l3.OneToOne_Optional_FK_Inverse3.Name) != "L2 05" - || Maybe( - l3.OneToOne_Required_FK_Inverse3.OneToOne_Optional_FK_Inverse2, - () => l3.OneToOne_Required_FK_Inverse3.OneToOne_Optional_FK_Inverse2.Name) == "L1 05" + l3.OneToOne_Optional_FK_Inverse3, + () => l3.OneToOne_Optional_FK_Inverse3.Name) != "L2 05" + || Maybe( + l3.OneToOne_Required_FK_Inverse3.OneToOne_Optional_FK_Inverse2, + () => l3.OneToOne_Required_FK_Inverse3.OneToOne_Optional_FK_Inverse2.Name) == "L1 05" select l3.Id); } @@ -1560,7 +1569,8 @@ public virtual Task Result_operator_nav_prop_reference_optional_Average_with_ide return AssertAverage( isAsync, ss => ss.Set().Select(e => (int?)e.OneToOne_Optional_FK1.Level1_Required_Id), - ss => ss.Set().Select(e => MaybeScalar(e.OneToOne_Optional_FK1, () => e.OneToOne_Optional_FK1.Level1_Required_Id)), + ss => ss.Set().Select( + e => MaybeScalar(e.OneToOne_Optional_FK1, () => e.OneToOne_Optional_FK1.Level1_Required_Id)), actualSelector: e => e, expectedSelector: e => e); } @@ -1572,7 +1582,8 @@ public virtual Task Result_operator_nav_prop_reference_optional_Average_without_ return AssertAverage( isAsync, ss => ss.Set().Select(e => (int?)e.OneToOne_Optional_FK1.Level1_Required_Id), - ss => ss.Set().Select(e => MaybeScalar(e.OneToOne_Optional_FK1, () => e.OneToOne_Optional_FK1.Level1_Required_Id))); + ss => ss.Set().Select( + e => MaybeScalar(e.OneToOne_Optional_FK1, () => e.OneToOne_Optional_FK1.Level1_Required_Id))); } [ConditionalTheory] @@ -1851,8 +1862,8 @@ public virtual Task Where_navigation_property_to_collection_of_original_entity_t ss => ss.Set().Where(l2 => l2.OneToMany_Required_Inverse2.OneToMany_Optional1.Count() > 0), ss => ss.Set().Where( l2 => MaybeScalar( - l2.OneToMany_Required_Inverse2.OneToMany_Optional1, - () => l2.OneToMany_Required_Inverse2.OneToMany_Optional1.Count()) > 0), + l2.OneToMany_Required_Inverse2.OneToMany_Optional1, + () => l2.OneToMany_Required_Inverse2.OneToMany_Optional1.Count()) > 0), e => e.Id, (e, a) => Assert.Equal(e.Id, a.Id)); } @@ -2033,12 +2044,12 @@ public virtual Task GroupJoin_on_complex_subquery_and_set_operation_on_grouping_ return AssertQuery( isAsync, ss => ss.Set().GroupJoin( - ss.Set().Where(l1 => l1.Name != "L1 01").Select(l1 => l1.OneToOne_Required_FK1), - l1 => l1.Id, - l2 => l2 != null ? l2.Level1_Optional_Id : null, - (l1, l2s) => new { l1, l2s }) - .Where(r => r.l2s.Any()) - .Select(r => r.l1), + ss.Set().Where(l1 => l1.Name != "L1 01").Select(l1 => l1.OneToOne_Required_FK1), + l1 => l1.Id, + l2 => l2 != null ? l2.Level1_Optional_Id : null, + (l1, l2s) => new { l1, l2s }) + .Where(r => r.l2s.Any()) + .Select(r => r.l1), e => e.Id, (e, a) => Assert.Equal(e.Id, a.Id)); } @@ -2091,18 +2102,18 @@ public virtual Task Null_protection_logic_work_for_outer_key_access_of_manually_ return AssertQuery( isAsync, ss => ss.Set().Select(l1 => l1.OneToOne_Required_FK1).GroupJoin( - ss.Set(), - l2 => l2.Level1_Optional_Id, - l1 => l1.Id, - (l2, l1g) => new { l2, l1g }) - .Select(r => r.l2), - ss => - ss.Set().Select(l1 => l1.OneToOne_Required_FK1).GroupJoin( ss.Set(), - l2 => MaybeScalar(l2, () => l2.Level1_Optional_Id), + l2 => l2.Level1_Optional_Id, l1 => l1.Id, (l2, l1g) => new { l2, l1g }) - .Select(r => r.l2), + .Select(r => r.l2), + ss => + ss.Set().Select(l1 => l1.OneToOne_Required_FK1).GroupJoin( + ss.Set(), + l2 => MaybeScalar(l2, () => l2.Level1_Optional_Id), + l1 => l1.Id, + (l2, l1g) => new { l2, l1g }) + .Select(r => r.l2), e => e?.Id, (e, a) => { @@ -2172,8 +2183,8 @@ public virtual Task Order_by_key_of_navigation_similar_to_projected_gets_optimiz return AssertQuery( isAsync, ss => from l3 in ss.Set() - orderby l3.OneToOne_Required_FK_Inverse3.Id - select l3.OneToOne_Required_FK_Inverse3.OneToOne_Required_FK_Inverse2, + orderby l3.OneToOne_Required_FK_Inverse3.Id + select l3.OneToOne_Required_FK_Inverse3.OneToOne_Required_FK_Inverse2, elementAsserter: (e, a) => AssertEqual(e, a), assertOrder: true); } @@ -2248,9 +2259,9 @@ join l3 in ss.Set() on l1.Id equals l3.Level2_Required_Id where l1.Name == "L1 03" where l3.Name == "L3 08" select new { l2, l1 }) - .OrderBy(l => l.l1.Id) - .Take(3) - .Select(l => l.l2.Name)); + .OrderBy(l => l.l1.Id) + .Take(3) + .Select(l => l.l2.Name)); } [ConditionalTheory] @@ -2809,10 +2820,11 @@ equals l2.Level1_Optional_Id ss => from l1 in ss.Set() join l2 in ss.Set().SelectMany( l4 => Maybe( - l4.OneToOne_Required_FK_Inverse4, - () => Maybe( - l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3, - () => l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3.OneToMany_Required_Self2)) ?? new List()) on l1.Id + l4.OneToOne_Required_FK_Inverse4, + () => Maybe( + l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3, + () => l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3.OneToMany_Required_Self2)) + ?? new List()) on l1.Id equals l2.Level1_Optional_Id select new { l1, l2 }, elementSorter: e => (e.l1.Id, e.l2.Id), @@ -2825,7 +2837,8 @@ equals l2.Level1_Optional_Id [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany(bool isAsync) + public virtual Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany( + bool isAsync) { return AssertQuery( isAsync, @@ -2858,7 +2871,8 @@ l1.Id equals MaybeScalar(l2, () => l2.Level1_Optional_Id) [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany2(bool isAsync) + public virtual Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany2( + bool isAsync) { return AssertQuery( isAsync, @@ -2887,11 +2901,13 @@ join l1 in ss.Set() on MaybeScalar(l2, () => l2.Level1_Optional_Id) equa [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany3(bool isAsync) + public virtual Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany3( + bool isAsync) { return AssertQuery( isAsync, - ss => from l4 in ss.Set().SelectMany(l1 => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.OneToMany_Required3.DefaultIfEmpty()) + ss => from l4 in ss.Set().SelectMany( + l1 => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.OneToMany_Required3.DefaultIfEmpty()) join l2 in ss.Set() on l4.Id equals l2.Id select new { l4, l2 }, ss => from l4 in ss.Set().SelectMany( @@ -2913,12 +2929,14 @@ join l2 in ss.Set() on MaybeScalar(l4, () => l4.Id) equals l2.Id [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany4(bool isAsync) + public virtual Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany4( + bool isAsync) { return AssertQuery( isAsync, ss - => from l4 in ss.Set().SelectMany(l1 => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.OneToMany_Required3.DefaultIfEmpty()) + => from l4 in ss.Set().SelectMany( + l1 => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.OneToMany_Required3.DefaultIfEmpty()) join l2 in ss.Set() on l4.Id equals l2.Id into grouping from l2 in grouping.DefaultIfEmpty() select new { l4, l2 }, @@ -2947,10 +2965,12 @@ public virtual Task Multiple_SelectMany_with_nested_navigations_and_explicit_Def { return AssertQuery( isAsync, - ss => from l4 in ss.Set().SelectMany(l1 => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.OneToMany_Required3.DefaultIfEmpty()) + ss => from l4 in ss.Set().SelectMany( + l1 => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.OneToMany_Required3.DefaultIfEmpty()) join l2 in ss.Set().SelectMany( - l4 => l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3.OneToMany_Required_Self2.DefaultIfEmpty()) - on l4.Id equals l2.Id + l4 => l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3.OneToMany_Required_Self2 + .DefaultIfEmpty()) + on l4.Id equals l2.Id select new { l4, l2 }, ss => from l4 in ss.Set().SelectMany( l1 => MaybeDefaultIfEmpty( @@ -2959,16 +2979,16 @@ on l4.Id equals l2.Id () => Maybe( l1.OneToOne_Required_FK1.OneToOne_Optional_FK2, () => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.OneToMany_Required3)))) - join l2 in ss.Set().SelectMany( - l4 => MaybeDefaultIfEmpty( - Maybe( - l4.OneToOne_Required_FK_Inverse4, - () => Maybe( - l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3, - () => l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3 - .OneToMany_Required_Self2)))) - on MaybeScalar(l4, () => l4.Id) equals MaybeScalar(l2, () => l2.Id) - select new { l4, l2 }, + join l2 in ss.Set().SelectMany( + l4 => MaybeDefaultIfEmpty( + Maybe( + l4.OneToOne_Required_FK_Inverse4, + () => Maybe( + l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3, + () => l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3 + .OneToMany_Required_Self2)))) + on MaybeScalar(l4, () => l4.Id) equals MaybeScalar(l2, () => l2.Id) + select new { l4, l2 }, elementSorter: e => (e.l4?.Id, e.l2?.Id), elementAsserter: (e, a) => { @@ -2979,65 +2999,72 @@ on MaybeScalar(l4, () => l4.Id) equals MaybeScalar(l2, () => l2.Id) [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_same_navs(bool isAsync) + public virtual Task + SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_same_navs( + bool isAsync) { return AssertQuery( isAsync, ss => from l3 in ss.Set().SelectMany( - l4 => l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3.OneToMany_Required2.DefaultIfEmpty()) - select l3.OneToOne_Required_FK_Inverse3.OneToOne_Required_PK_Inverse2, + l4 => l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3.OneToMany_Required2.DefaultIfEmpty()) + select l3.OneToOne_Required_FK_Inverse3.OneToOne_Required_PK_Inverse2, ss => from l3 in ss.Set().SelectMany( - l4 => MaybeDefaultIfEmpty( - Maybe( - l4.OneToOne_Required_FK_Inverse4, - () => Maybe( - l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3, - () => l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3.OneToMany_Required2)))) - select Maybe( - l3, - () => l3.OneToOne_Required_FK_Inverse3.OneToOne_Required_PK_Inverse2)); + l4 => MaybeDefaultIfEmpty( + Maybe( + l4.OneToOne_Required_FK_Inverse4, + () => Maybe( + l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3, + () => l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3.OneToMany_Required2)))) + select Maybe( + l3, + () => l3.OneToOne_Required_FK_Inverse3.OneToOne_Required_PK_Inverse2)); } [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_different_navs(bool isAsync) + public virtual Task + SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_different_navs( + bool isAsync) { return AssertQuery( isAsync, ss => from l3 in ss.Set().SelectMany(l1 => l1.OneToOne_Optional_FK1.OneToMany_Optional2.DefaultIfEmpty()) - select l3.OneToOne_Required_FK_Inverse3.OneToOne_Required_PK_Inverse2, + select l3.OneToOne_Required_FK_Inverse3.OneToOne_Required_PK_Inverse2, ss => from l3 in ss.Set().SelectMany( - l1 => MaybeDefaultIfEmpty( - Maybe( - l1.OneToOne_Optional_FK1, - () => l1.OneToOne_Optional_FK1.OneToMany_Optional2))) - select Maybe( - l3, - () => l3.OneToOne_Required_FK_Inverse3.OneToOne_Required_PK_Inverse2)); + l1 => MaybeDefaultIfEmpty( + Maybe( + l1.OneToOne_Optional_FK1, + () => l1.OneToOne_Optional_FK1.OneToMany_Optional2))) + select Maybe( + l3, + () => l3.OneToOne_Required_FK_Inverse3.OneToOne_Required_PK_Inverse2)); } [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task Complex_SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_with_other_query_operators_composed_on_top(bool isAsync) + public virtual Task + Complex_SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_with_other_query_operators_composed_on_top(bool isAsync) { return AssertQuery( isAsync, - ss => from l4 in ss.Set().SelectMany(l1 => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.OneToMany_Required3.DefaultIfEmpty()) + ss => from l4 in ss.Set().SelectMany( + l1 => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.OneToMany_Required3.DefaultIfEmpty()) join l2 in ss.Set().SelectMany( - l4 => l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3.OneToMany_Required_Self2.DefaultIfEmpty()) - on l4.Id equals l2.Id - join l3 in ss.Set().SelectMany( - l4 => l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3.OneToMany_Required2.DefaultIfEmpty()) - on l2.Id equals l3.Id into grouping - from l3 in grouping.DefaultIfEmpty() - where l4.OneToMany_Optional_Inverse4.Name != "Foo" - orderby l2.OneToOne_Optional_FK2.Id - select new - { - Entity = l4, - Collection = l2.OneToMany_Optional_Self2.Where(e => e.Id != 42).ToList(), - Property = l3.OneToOne_Optional_FK_Inverse3.OneToOne_Required_FK2.Name - }, + l4 => l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3.OneToMany_Required_Self2 + .DefaultIfEmpty()) + on l4.Id equals l2.Id + join l3 in ss.Set().SelectMany( + l4 => l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3.OneToMany_Required2.DefaultIfEmpty()) + on l2.Id equals l3.Id into grouping + from l3 in grouping.DefaultIfEmpty() + where l4.OneToMany_Optional_Inverse4.Name != "Foo" + orderby l2.OneToOne_Optional_FK2.Id + select new + { + Entity = l4, + Collection = l2.OneToMany_Optional_Self2.Where(e => e.Id != 42).ToList(), + Property = l3.OneToOne_Optional_FK_Inverse3.OneToOne_Required_FK2.Name + }, ss => from l4 in ss.Set().SelectMany( l1 => MaybeDefaultIfEmpty( Maybe( @@ -3045,49 +3072,49 @@ orderby l2.OneToOne_Optional_FK2.Id () => Maybe( l1.OneToOne_Required_FK1.OneToOne_Optional_FK2, () => l1.OneToOne_Required_FK1.OneToOne_Optional_FK2.OneToMany_Required3)))) - join l2 in ss.Set().SelectMany( - l4 => MaybeDefaultIfEmpty( - Maybe( - l4.OneToOne_Required_FK_Inverse4, - () => Maybe( - l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3, - () => l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3.OneToMany_Required_Self2)))) - on MaybeScalar(l4, () => l4.Id) equals MaybeScalar(l2, () => l2.Id) - join l3 in ss.Set().SelectMany( - l4 => MaybeDefaultIfEmpty( - Maybe( - l4.OneToOne_Required_FK_Inverse4, - () => Maybe( - l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3, - () => l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3.OneToMany_Required2)))) - on MaybeScalar(l2, () => l2.Id) equals MaybeScalar(l3, () => l3.Id) into grouping - from l3 in grouping.DefaultIfEmpty() - where Maybe( - l4, - () => Maybe( - l4.OneToMany_Optional_Inverse4, - () => l4.OneToMany_Optional_Inverse4.Name)) != "Foo" - orderby MaybeScalar( - l2, - () => MaybeScalar( - l2.OneToOne_Optional_FK2, - () => l2.OneToOne_Optional_FK2.Id)) - select new - { - Entity = l4, - Collection = Maybe( - l2, - () => Maybe( - l2.OneToMany_Optional_Self2, - () => l2.OneToMany_Optional_Self2.Where(e => e.Id != 42).ToList())), - Property = Maybe( - l3, - () => Maybe( - l3.OneToOne_Optional_FK_Inverse3, - () => Maybe( - l3.OneToOne_Optional_FK_Inverse3.OneToOne_Required_FK2, - () => l3.OneToOne_Optional_FK_Inverse3.OneToOne_Required_FK2.Name))) - }, + join l2 in ss.Set().SelectMany( + l4 => MaybeDefaultIfEmpty( + Maybe( + l4.OneToOne_Required_FK_Inverse4, + () => Maybe( + l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3, + () => l4.OneToOne_Required_FK_Inverse4.OneToOne_Optional_FK_Inverse3.OneToMany_Required_Self2)))) + on MaybeScalar(l4, () => l4.Id) equals MaybeScalar(l2, () => l2.Id) + join l3 in ss.Set().SelectMany( + l4 => MaybeDefaultIfEmpty( + Maybe( + l4.OneToOne_Required_FK_Inverse4, + () => Maybe( + l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3, + () => l4.OneToOne_Required_FK_Inverse4.OneToOne_Required_FK_Inverse3.OneToMany_Required2)))) + on MaybeScalar(l2, () => l2.Id) equals MaybeScalar(l3, () => l3.Id) into grouping + from l3 in grouping.DefaultIfEmpty() + where Maybe( + l4, + () => Maybe( + l4.OneToMany_Optional_Inverse4, + () => l4.OneToMany_Optional_Inverse4.Name)) != "Foo" + orderby MaybeScalar( + l2, + () => MaybeScalar( + l2.OneToOne_Optional_FK2, + () => l2.OneToOne_Optional_FK2.Id)) + select new + { + Entity = l4, + Collection = Maybe( + l2, + () => Maybe( + l2.OneToMany_Optional_Self2, + () => l2.OneToMany_Optional_Self2.Where(e => e.Id != 42).ToList())), + Property = Maybe( + l3, + () => Maybe( + l3.OneToOne_Optional_FK_Inverse3, + () => Maybe( + l3.OneToOne_Optional_FK_Inverse3.OneToOne_Required_FK2, + () => l3.OneToOne_Optional_FK_Inverse3.OneToOne_Required_FK2.Name))) + }, elementSorter: e => e.Entity.Id, elementAsserter: (e, a) => { @@ -3104,10 +3131,10 @@ public virtual Task Multiple_SelectMany_with_navigation_and_explicit_DefaultIfEm return AssertQuery( isAsync, ss => from l1 in ss.Set() - from l2 in l1.OneToMany_Optional1 - from l3 in l2.OneToMany_Optional2.Where(l => l.Id > 5).DefaultIfEmpty() - where l3 != null - select l1, + from l2 in l1.OneToMany_Optional1 + from l3 in l2.OneToMany_Optional2.Where(l => l.Id > 5).DefaultIfEmpty() + where l3 != null + select l1, e => e.Id, (e, a) => Assert.Equal(e.Id, a.Id)); } @@ -3119,9 +3146,9 @@ public virtual Task SelectMany_with_navigation_filter_paging_and_explicit_Defaul return AssertQuery( isAsync, ss => from l1 in ss.Set() - from l2 in l1.OneToMany_Required1.Where(l => l.Id > 5).OrderBy(l => l.Id).Take(3).DefaultIfEmpty() - where l2 != null - select l1, + from l2 in l1.OneToMany_Required1.Where(l => l.Id > 5).OrderBy(l => l.Id).Take(3).DefaultIfEmpty() + where l2 != null + select l1, e => e.Id, (e, a) => Assert.Equal(e.Id, a.Id)); } @@ -3231,7 +3258,9 @@ public virtual Task Required_navigation_on_a_subquery_with_First_in_predicate(bo isAsync, ss => ss.Set() .Where(l2o => l2o.Id == 7) - .Where(l1 => EF.Property(ss.Set().OrderBy(l2i => l2i.Id).First().OneToOne_Required_FK_Inverse2, "Name") == "L1 02"), + .Where( + l1 => EF.Property(ss.Set().OrderBy(l2i => l2i.Id).First().OneToOne_Required_FK_Inverse2, "Name") + == "L1 02"), ss => ss.Set() .Where(l2o => l2o.Id == 7) .Where(l1 => ss.Set().OrderBy(l2i => l2i.Id).First().OneToOne_Required_FK_Inverse2.Name == "L1 02")); @@ -3284,7 +3313,8 @@ public virtual Task Optional_navigation_propagates_nullability_to_manually_creat isAsync, ss => from l3 in ss.Set() - join l2_nav in ss.Set().Select(ll => ll.OneToOne_Optional_FK1) on l3.Level2_Required_Id equals l2_nav.Id into grouping + join l2_nav in ss.Set().Select(ll => ll.OneToOne_Optional_FK1) on l3.Level2_Required_Id equals l2_nav.Id into + grouping from l2_nav in grouping.DefaultIfEmpty() select new { Name1 = l3.Name, Name2 = l2_nav.Name }, ss => @@ -3308,7 +3338,7 @@ from l1_inner in ss.Set() join l2_inner in ss.Set() on l1_inner.Id equals l2_inner.Level1_Optional_Id into grouping_inner from l2_inner in grouping_inner.DefaultIfEmpty() select l2_inner - on l3.Level2_Required_Id equals l2_outer.Id into grouping_outer + on l3.Level2_Required_Id equals l2_outer.Id into grouping_outer from l2_outer in grouping_outer.DefaultIfEmpty() select l2_outer.Name, ss => from l3 in ss.Set() @@ -3317,7 +3347,7 @@ from l1_inner in ss.Set() join l2_inner in ss.Set() on l1_inner.Id equals l2_inner.Level1_Optional_Id into grouping_inner from l2_inner in grouping_inner.DefaultIfEmpty() select l2_inner - on l3.Level2_Required_Id equals MaybeScalar(l2_outer, () => l2_outer.Id) into grouping_outer + on l3.Level2_Required_Id equals MaybeScalar(l2_outer, () => l2_outer.Id) into grouping_outer from l2_outer in grouping_outer.DefaultIfEmpty() select Maybe(l2_outer, () => l2_outer.Name)); } @@ -3334,7 +3364,7 @@ from l1_inner in ss.Set() join l2_inner in ss.Set() on l1_inner.Id equals l2_inner.Level1_Optional_Id into grouping_inner from l2_inner in grouping_inner.DefaultIfEmpty() select l2_inner - on l3.Level2_Required_Id equals l2_outer.Id into grouping_outer + on l3.Level2_Required_Id equals l2_outer.Id into grouping_outer from l2_outer in grouping_outer.DefaultIfEmpty() select new { entity = l2_outer, property = l2_outer.Name }, ss => from l3 in ss.Set() @@ -3343,13 +3373,13 @@ from l1_inner in ss.Set() join l2_inner in ss.Set() on l1_inner.Id equals l2_inner.Level1_Optional_Id into grouping_inner from l2_inner in grouping_inner.DefaultIfEmpty() select l2_inner - on l3.Level2_Required_Id equals MaybeScalar(l2_outer, () => l2_outer.Id) into grouping_outer + on l3.Level2_Required_Id equals MaybeScalar(l2_outer, () => l2_outer.Id) into grouping_outer from l2_outer in grouping_outer.DefaultIfEmpty() select new { entity = l2_outer, property = Maybe(l2_outer, () => l2_outer.Name) }, elementSorter: e => e.property, elementAsserter: (e, a) => { - AssertEqual(e.entity, a.entity); + AssertEqual(e.entity, a.entity); Assert.Equal(e.property, a.property); }); } @@ -3371,7 +3401,7 @@ from l1_inner in ss.Set() join l2_inner in ss.Set() on l1_inner.Id equals l2_inner.Level1_Optional_Id into grouping_inner from l2_inner in grouping_inner.DefaultIfEmpty() select l2_inner - on l3.Level2_Required_Id equals l2_outer.Id into grouping_outer + on l3.Level2_Required_Id equals l2_outer.Id into grouping_outer from l2_outer in grouping_outer.DefaultIfEmpty() select ClientMethodReturnSelf(l2_outer.Name), ss => from l3 in ss.Set() @@ -3380,7 +3410,7 @@ from l1_inner in ss.Set() join l2_inner in ss.Set() on l1_inner.Id equals l2_inner.Level1_Optional_Id into grouping_inner from l2_inner in grouping_inner.DefaultIfEmpty() select l2_inner - on l3.Level2_Required_Id equals MaybeScalar(l2_outer, () => l2_outer.Id) into grouping_outer + on l3.Level2_Required_Id equals MaybeScalar(l2_outer, () => l2_outer.Id) into grouping_outer from l2_outer in grouping_outer.DefaultIfEmpty() select ClientMethodReturnSelf(Maybe(l2_outer, () => l2_outer.Name))); } @@ -3396,7 +3426,7 @@ join subquery in from l2_inner in ss.Set() join l1_inner in ss.Set() on l2_inner.Level1_Required_Id equals l1_inner.Id select l2_inner - on l1_outer.Id equals subquery.Level1_Optional_Id into grouping + on l1_outer.Id equals subquery.Level1_Optional_Id into grouping from subquery in grouping.DefaultIfEmpty() select (int?)subquery.Id, ss => from l1_outer in ss.Set() @@ -3404,7 +3434,7 @@ join subquery in from l2_inner in ss.Set() join l1_inner in ss.Set() on l2_inner.Level1_Required_Id equals l1_inner.Id select l2_inner - on l1_outer.Id equals subquery.Level1_Optional_Id into grouping + on l1_outer.Id equals subquery.Level1_Optional_Id into grouping from subquery in grouping.DefaultIfEmpty() select MaybeScalar(subquery, () => subquery.Id)); } @@ -3420,7 +3450,7 @@ join subquery in from l2_inner in ss.Set() join l1_inner in ss.Set() on l2_inner.Level1_Required_Id equals l1_inner.Id select l2_inner - on l1_outer.Id equals subquery.Level1_Optional_Id into grouping + on l1_outer.Id equals subquery.Level1_Optional_Id into grouping from subquery in grouping.DefaultIfEmpty() select subquery != null ? (int?)subquery.Id : null, ss => from l1_outer in ss.Set() @@ -3428,7 +3458,7 @@ join subquery in from l2_inner in ss.Set() join l1_inner in ss.Set() on l2_inner.Level1_Required_Id equals l1_inner.Id select l2_inner - on l1_outer.Id equals subquery.Level1_Optional_Id into grouping + on l1_outer.Id equals subquery.Level1_Optional_Id into grouping from subquery in grouping.DefaultIfEmpty() select MaybeScalar(subquery, () => subquery.Id)); } @@ -3445,7 +3475,7 @@ from l2_inner in ss.Set() join l1_inner in ss.Set() on l2_inner.Level1_Required_Id equals l1_inner.Id into grouping_inner from l1_inner in grouping_inner.DefaultIfEmpty() select l2_inner - on l1_outer.Id equals subquery.Level1_Required_Id into grouping + on l1_outer.Id equals subquery.Level1_Required_Id into grouping from subquery in grouping.DefaultIfEmpty() select (int?)subquery.Id, ss => from l1_outer in ss.Set() @@ -3454,7 +3484,7 @@ from l2_inner in ss.Set() join l1_inner in ss.Set() on l2_inner.Level1_Required_Id equals l1_inner.Id into grouping_inner from l1_inner in grouping_inner.DefaultIfEmpty() select l2_inner - on l1_outer.Id equals MaybeScalar(subquery, () => subquery.Level1_Required_Id) into grouping + on l1_outer.Id equals MaybeScalar(subquery, () => subquery.Level1_Required_Id) into grouping from subquery in grouping.DefaultIfEmpty() select MaybeScalar(subquery, () => subquery.Id)); } @@ -3470,7 +3500,7 @@ join subquery in from l2_inner in ss.Set() join l1_inner in ss.Set() on l2_inner.Level1_Required_Id equals l1_inner.Id select l2_inner - on l1_outer.Id equals subquery.Level1_Optional_Id into grouping + on l1_outer.Id equals subquery.Level1_Optional_Id into grouping where grouping.Any() from subquery in grouping.DefaultIfEmpty() select subquery.Id); @@ -3487,7 +3517,7 @@ join subquery in from l2_inner in ss.Set() join l1_inner in ss.Set() on l2_inner.Level1_Required_Id equals l1_inner.Id select l2_inner - on l1_outer.Id equals subquery.Level1_Optional_Id into grouping + on l1_outer.Id equals subquery.Level1_Optional_Id into grouping from subquery in grouping.DefaultIfEmpty() where grouping.Any() select subquery.Id); @@ -3636,7 +3666,8 @@ public virtual Task GroupJoin_on_right_side_being_a_subquery(bool isAsync) isAsync, ss => from l2 in ss.Set() - join l1 in ss.Set().OrderBy(x => x.OneToOne_Optional_FK1.Name).Take(2) on l2.Level1_Optional_Id equals l1.Id into grouping + join l1 in ss.Set().OrderBy(x => x.OneToOne_Optional_FK1.Name).Take(2) on l2.Level1_Optional_Id equals l1.Id + into grouping from l1 in grouping.DefaultIfEmpty() #pragma warning disable IDE0031 // Use null propagation select new { l2.Id, Name = l1 != null ? l1.Name : null }, @@ -4046,7 +4077,8 @@ orderby l1_inner.Id join l2_inner in ss.Set() on l1_inner.Id equals l2_inner.Level1_Optional_Id into grouping_inner from l2_inner in grouping_inner.DefaultIfEmpty() select l2_inner).Take(2) - join l2_outer in ss.Set() on MaybeScalar(l1_outer, () => l1_outer.Id) equals l2_outer.Level1_Optional_Id into + join l2_outer in ss.Set() on MaybeScalar(l1_outer, () => l1_outer.Id) equals l2_outer.Level1_Optional_Id + into grouping_outer from l2_outer in grouping_outer.DefaultIfEmpty() select Maybe(l2_outer, () => l2_outer.Name)); @@ -4073,7 +4105,8 @@ public virtual Task Multi_level_navigation_compared_to_null(bool isAsync) where l3.OneToMany_Optional_Inverse3.OneToOne_Required_FK_Inverse2 != null select l3.Id, ss => from l3 in ss.Set() - where Maybe(l3.OneToMany_Optional_Inverse3, () => l3.OneToMany_Optional_Inverse3.OneToOne_Required_FK_Inverse2) != null + where Maybe(l3.OneToMany_Optional_Inverse3, () => l3.OneToMany_Optional_Inverse3.OneToOne_Required_FK_Inverse2) + != null select l3.Id); } @@ -4089,11 +4122,12 @@ public virtual Task Multi_level_navigation_with_same_navigation_compared_to_null select l3.Id, ss => from l3 in ss.Set() where Maybe( - l3.OneToMany_Optional_Inverse3, - () => Maybe( - l3.OneToMany_Optional_Inverse3.OneToOne_Required_FK_Inverse2, - () => l3.OneToMany_Optional_Inverse3.OneToOne_Required_FK_Inverse2.Name)) != "L1 07" - where Maybe(l3.OneToMany_Optional_Inverse3, () => l3.OneToMany_Optional_Inverse3.OneToOne_Required_FK_Inverse2) != null + l3.OneToMany_Optional_Inverse3, + () => Maybe( + l3.OneToMany_Optional_Inverse3.OneToOne_Required_FK_Inverse2, + () => l3.OneToMany_Optional_Inverse3.OneToOne_Required_FK_Inverse2.Name)) != "L1 07" + where Maybe(l3.OneToMany_Optional_Inverse3, () => l3.OneToMany_Optional_Inverse3.OneToOne_Required_FK_Inverse2) + != null select l3.Id); } @@ -4138,15 +4172,15 @@ public virtual Task Navigations_compared_to_each_other4(bool isAsync) isAsync, ss => from l2 in ss.Set() where l2.OneToOne_Required_FK2.OneToMany_Optional3 - .Select(i => i.OneToOne_Optional_PK_Inverse4 == l2.OneToOne_Required_FK2).Any() + .Select(i => i.OneToOne_Optional_PK_Inverse4 == l2.OneToOne_Required_FK2).Any() select l2.Name, ss => from l2 in ss.Set() where MaybeScalar( - l2.OneToOne_Required_FK2, - () => MaybeScalar( - l2.OneToOne_Required_FK2.OneToMany_Optional3, - () => l2.OneToOne_Required_FK2.OneToMany_Optional3 - .Select(i => i.OneToOne_Optional_PK_Inverse4 == l2.OneToOne_Required_FK2).Any())) == true + l2.OneToOne_Required_FK2, + () => MaybeScalar( + l2.OneToOne_Required_FK2.OneToMany_Optional3, + () => l2.OneToOne_Required_FK2.OneToMany_Optional3 + .Select(i => i.OneToOne_Optional_PK_Inverse4 == l2.OneToOne_Required_FK2).Any())) == true select l2.Name); } @@ -4162,12 +4196,12 @@ where l2.OneToOne_Required_FK2.OneToMany_Optional3 select l2.Name, ss => from l2 in ss.Set() where MaybeScalar( - l2.OneToOne_Required_FK2, - () => MaybeScalar( - l2.OneToOne_Required_FK2.OneToMany_Optional3, - () => l2.OneToOne_Required_FK2.OneToMany_Optional3 - .Select(i => i.OneToOne_Optional_PK_Inverse4 == l2.OneToOne_Optional_PK2).Any())) == true - select l2.Name); + l2.OneToOne_Required_FK2, + () => MaybeScalar( + l2.OneToOne_Required_FK2.OneToMany_Optional3, + () => l2.OneToOne_Required_FK2.OneToMany_Optional3 + .Select(i => i.OneToOne_Optional_PK_Inverse4 == l2.OneToOne_Optional_PK2).Any())) == true + select l2.Name); } [ConditionalTheory(Skip = "Issue#16752")] @@ -4198,7 +4232,8 @@ public virtual Task Comparing_collection_navigation_on_optional_reference_to_nul return AssertQueryScalar( isAsync, ss => ss.Set().Where(l1 => l1.OneToOne_Optional_FK1.OneToMany_Optional2 == null).Select(l1 => l1.Id), - ss => ss.Set().Where(l1 => Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.OneToMany_Optional2) == null) + ss => ss.Set() + .Where(l1 => Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.OneToMany_Optional2) == null) .Select(l1 => l1.Id)); } @@ -4217,7 +4252,8 @@ public virtual Task Select_subquery_with_client_eval_and_navigation2(bool isAsyn { return AssertQueryScalar( isAsync, - ss => ss.Set().Select(l2 => ss.Set().OrderBy(l => l.Id).First().OneToOne_Required_FK_Inverse2.Name == "L1 02")); + ss => ss.Set().Select( + l2 => ss.Set().OrderBy(l => l.Id).First().OneToOne_Required_FK_Inverse2.Name == "L1 02")); } [ConditionalTheory] @@ -4226,7 +4262,8 @@ public virtual Task Select_subquery_with_client_eval_and_multi_level_navigation( { return AssertQuery( isAsync, - ss => ss.Set().Select(l3 => ss.Set().OrderBy(l => l.Id).First().OneToOne_Required_FK_Inverse3.OneToOne_Required_FK_Inverse2.Name)); + ss => ss.Set().Select( + l3 => ss.Set().OrderBy(l => l.Id).First().OneToOne_Required_FK_Inverse3.OneToOne_Required_FK_Inverse2.Name)); } [ConditionalTheory] @@ -4263,7 +4300,7 @@ public virtual Task Project_collection_navigation(bool isAsync) return AssertQuery( isAsync, ss => from l1 in ss.Set() - select l1.OneToMany_Optional1, + select l1.OneToMany_Optional1, elementSorter: e => e != null ? e.Count : 0, elementAsserter: (e, a) => AssertCollection(e, a)); } @@ -4275,9 +4312,9 @@ public virtual Task Project_collection_navigation_nested(bool isAsync) return AssertQuery( isAsync, ss => from l1 in ss.Set() - select l1.OneToOne_Optional_FK1.OneToMany_Optional2, + select l1.OneToOne_Optional_FK1.OneToMany_Optional2, ss => from l1 in ss.Set() - select Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.OneToMany_Optional2) ?? new List(), + select Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.OneToMany_Optional2) ?? new List(), elementSorter: e => e.Count, elementAsserter: (e, a) => AssertCollection(e, a)); } @@ -4289,9 +4326,10 @@ public virtual Task Project_collection_navigation_nested_with_take(bool isAsync) return AssertQuery( isAsync, ss => from l1 in ss.Set() - select l1.OneToOne_Optional_FK1.OneToMany_Optional2.Take(50), + select l1.OneToOne_Optional_FK1.OneToMany_Optional2.Take(50), ss => from l1 in ss.Set() - select Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.OneToMany_Optional2.Take(50)) ?? new List(), + select Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.OneToMany_Optional2.Take(50)) + ?? new List(), elementSorter: e => e?.Count() ?? 0, elementAsserter: (e, a) => AssertCollection(e, a)); } @@ -4303,13 +4341,13 @@ public virtual Task Project_collection_navigation_using_ef_property(bool isAsync return AssertQuery( isAsync, ss => from l1 in ss.Set() - select EF.Property>( - EF.Property( - l1, - "OneToOne_Optional_FK1"), - "OneToMany_Optional2"), + select EF.Property>( + EF.Property( + l1, + "OneToOne_Optional_FK1"), + "OneToMany_Optional2"), ss => from l1 in ss.Set() - select Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.OneToMany_Optional2) ?? new List(), + select Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.OneToMany_Optional2) ?? new List(), elementSorter: e => e.Count, elementAsserter: (e, a) => AssertCollection(e, a)); } @@ -4321,15 +4359,15 @@ public virtual Task Project_collection_navigation_nested_anonymous(bool isAsync) return AssertQuery( isAsync, ss => from l1 in ss.Set() - select new { l1.Id, l1.OneToOne_Optional_FK1.OneToMany_Optional2 }, + select new { l1.Id, l1.OneToOne_Optional_FK1.OneToMany_Optional2 }, ss => from l1 in ss.Set() - select new - { - l1.Id, - OneToMany_Optional2 = Maybe( - l1.OneToOne_Optional_FK1, - () => l1.OneToOne_Optional_FK1.OneToMany_Optional2) ?? new List() - }, + select new + { + l1.Id, + OneToMany_Optional2 = Maybe( + l1.OneToOne_Optional_FK1, + () => l1.OneToOne_Optional_FK1.OneToMany_Optional2) ?? new List() + }, elementSorter: e => e.Id, elementAsserter: (e, a) => { @@ -4345,17 +4383,17 @@ public virtual Task Project_collection_navigation_count(bool isAsync) return AssertQuery( isAsync, ss => from l1 in ss.Set() - select new { l1.Id, l1.OneToOne_Optional_FK1.OneToMany_Optional2.Count }, + select new { l1.Id, l1.OneToOne_Optional_FK1.OneToMany_Optional2.Count }, ss => from l1 in ss.Set() - select new - { - l1.Id, - Count = MaybeScalar( - l1.OneToOne_Optional_FK1, - () => MaybeScalar( - l1.OneToOne_Optional_FK1.OneToMany_Optional2, - () => l1.OneToOne_Optional_FK1.OneToMany_Optional2.Count)) ?? 0 - }, + select new + { + l1.Id, + Count = MaybeScalar( + l1.OneToOne_Optional_FK1, + () => MaybeScalar( + l1.OneToOne_Optional_FK1.OneToMany_Optional2, + () => l1.OneToOne_Optional_FK1.OneToMany_Optional2.Count)) ?? 0 + }, elementSorter: e => e.Id); } @@ -4366,8 +4404,8 @@ public virtual Task Project_collection_navigation_composed(bool isAsync) return AssertQuery( isAsync, ss => from l1 in ss.Set() - where l1.Id < 3 - select new { l1.Id, collection = l1.OneToMany_Optional1.Where(l2 => l2.Name != "Foo").ToList() }, + where l1.Id < 3 + select new { l1.Id, collection = l1.OneToMany_Optional1.Where(l2 => l2.Name != "Foo").ToList() }, elementSorter: e => e.Id, elementAsserter: (e, a) => { @@ -4383,7 +4421,7 @@ public virtual Task Project_collection_and_root_entity(bool isAsync) return AssertQuery( isAsync, ss => from l1 in ss.Set() - select new { l1, l1.OneToMany_Optional1 }, + select new { l1, l1.OneToMany_Optional1 }, elementSorter: e => e.l1.Id, elementAsserter: (e, a) => { @@ -4399,7 +4437,7 @@ public virtual Task Project_collection_and_include(bool isAsync) return AssertQuery( isAsync, ss => from l1 in ss.Set().Include(l => l.OneToMany_Optional1) - select new { l1, l1.OneToMany_Optional1 }, + select new { l1, l1.OneToMany_Optional1 }, elementSorter: e => e.l1.Id, elementAsserter: (e, a) => { @@ -4415,13 +4453,14 @@ public virtual Task Project_navigation_and_collection(bool isAsync) return AssertQuery( isAsync, ss => from l1 in ss.Set() - select new { l1.OneToOne_Optional_FK1, l1.OneToOne_Optional_FK1.OneToMany_Optional2 }, + select new { l1.OneToOne_Optional_FK1, l1.OneToOne_Optional_FK1.OneToMany_Optional2 }, ss => from l1 in ss.Set() - select new - { - l1.OneToOne_Optional_FK1, - OneToMany_Optional2 = Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.OneToMany_Optional2) ?? new List() - }, + select new + { + l1.OneToOne_Optional_FK1, + OneToMany_Optional2 = Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.OneToMany_Optional2) + ?? new List() + }, elementSorter: e => e.OneToOne_Optional_FK1?.Id, elementAsserter: (e, a) => { @@ -4438,7 +4477,7 @@ public virtual Task Include_inside_subquery(bool isAsync) return AssertQuery( isAsync, ss => ss.Set() - .Where(l1 => l1.Id <3) + .Where(l1 => l1.Id < 3) .OrderBy(l1 => l1.Id) .Select(l1 => new { subquery = ss.Set().Include(l => l.OneToMany_Optional2).Where(l => l.Id > 0).ToList() }), assertOrder: true, @@ -4793,7 +4832,8 @@ public virtual Task Accessing_optional_property_inside_result_operator_subquery( return AssertQuery( isAsync, ss => ss.Set().Where(l1 => names.All(n => l1.OneToOne_Optional_FK1.Name != n)), - ss => ss.Set().Where(l1 => names.All(n => Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.Name) != n))); + ss => ss.Set().Where( + l1 => names.All(n => Maybe(l1.OneToOne_Optional_FK1, () => l1.OneToOne_Optional_FK1.Name) != n))); } [ConditionalTheory(Skip = "Issue#16752")] @@ -4838,7 +4878,7 @@ public virtual Task Include_after_SelectMany_and_reference_navigation_with_anoth return AssertIncludeQuery( isAsync, ss => from lOuter in ss.Set().SelectMany(l1 => l1.OneToMany_Required1).Select(l2 => l2.OneToOne_Optional_FK2) - .Include(l3 => l3.OneToMany_Optional3) + .Include(l3 => l3.OneToMany_Optional3) from lInner in lOuter.OneToMany_Optional3.Distinct() where lInner != null select lOuter, @@ -5076,8 +5116,10 @@ public virtual Task Include8(bool isAsync) return AssertIncludeQuery( isAsync, - ss => ss.Set().Where(l2 => l2.OneToOne_Optional_FK_Inverse2.Name != "Fubar").Include(l2 => l2.OneToOne_Optional_FK_Inverse2), - ss => ss.Set().Where(l2 => Maybe(l2.OneToOne_Optional_FK_Inverse2, () => l2.OneToOne_Optional_FK_Inverse2.Name) != "Fubar") + ss => ss.Set().Where(l2 => l2.OneToOne_Optional_FK_Inverse2.Name != "Fubar") + .Include(l2 => l2.OneToOne_Optional_FK_Inverse2), + ss => ss.Set().Where( + l2 => Maybe(l2.OneToOne_Optional_FK_Inverse2, () => l2.OneToOne_Optional_FK_Inverse2.Name) != "Fubar") .Include(l2 => l2.OneToOne_Optional_FK_Inverse2), expectedIncludes); } @@ -5093,7 +5135,8 @@ public virtual Task Include9(bool isAsync) return AssertIncludeQuery( isAsync, - ss => ss.Set().Include(l2 => l2.OneToOne_Optional_FK_Inverse2).Where(l2 => l2.OneToOne_Optional_FK_Inverse2.Name != "Fubar"), + ss => ss.Set().Include(l2 => l2.OneToOne_Optional_FK_Inverse2) + .Where(l2 => l2.OneToOne_Optional_FK_Inverse2.Name != "Fubar"), ss => ss.Set().Include(l2 => l2.OneToOne_Optional_FK_Inverse2).Where( l2 => Maybe(l2.OneToOne_Optional_FK_Inverse2, () => l2.OneToOne_Optional_FK_Inverse2.Name) != "Fubar"), expectedIncludes); @@ -5344,7 +5387,8 @@ public virtual Task Include18_3_3(bool isAsync) return AssertIncludeQuery( isAsync, - ss => ss.Set().Include(x => x.OneToOne_Optional_FK1.OneToOne_Optional_FK2).Select(l1 => l1.OneToOne_Optional_FK1).Distinct(), + ss => ss.Set().Include(x => x.OneToOne_Optional_FK1.OneToOne_Optional_FK2).Select(l1 => l1.OneToOne_Optional_FK1) + .Distinct(), expectedIncludes); } @@ -5517,7 +5561,8 @@ public virtual Task IncludeCollection8(bool isAsync) { new ExpectedInclude(e => e.OneToMany_Optional1, "OneToMany_Optional1"), new ExpectedInclude(e => e.OneToOne_Optional_PK2, "OneToOne_Optional_PK2", "OneToMany_Optional1"), - new ExpectedInclude(e => e.OneToOne_Optional_FK3, "OneToOne_Optional_FK3", "OneToMany_Optional1.OneToOne_Optional_PK2"), + new ExpectedInclude( + e => e.OneToOne_Optional_FK3, "OneToOne_Optional_FK3", "OneToMany_Optional1.OneToOne_Optional_PK2") }; return AssertIncludeQuery( @@ -5531,7 +5576,9 @@ public virtual Task IncludeCollection8(bool isAsync) .Include(l1 => l1.OneToMany_Optional1) .ThenInclude(l2 => l2.OneToOne_Optional_PK2) .ThenInclude(l3 => l3.OneToOne_Optional_FK3) - .Where(l1 => l1.OneToMany_Optional1.Where(l2 => Maybe(l2.OneToOne_Optional_PK2, () => l2.OneToOne_Optional_PK2.Name) != "Foo").Count() > 0), + .Where( + l1 => l1.OneToMany_Optional1 + .Where(l2 => Maybe(l2.OneToOne_Optional_PK2, () => l2.OneToOne_Optional_PK2.Name) != "Foo").Count() > 0), expectedIncludes); } @@ -5551,7 +5598,8 @@ public virtual Task Join_with_navigations_in_the_result_selector1(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Join(ss.Set(), l1 => l1.Id, l2 => l2.Level1_Required_Id, (o, i) => new { o.OneToOne_Optional_FK1, i })); + ss => ss.Set().Join( + ss.Set(), l1 => l1.Id, l2 => l2.Level1_Required_Id, (o, i) => new { o.OneToOne_Optional_FK1, i })); } [ConditionalFact] @@ -5718,9 +5766,10 @@ public virtual void Union_over_entities_with_different_nullability() var query = ctx.Set() .GroupJoin(ctx.Set(), l1 => l1.Id, l2 => l2.Level1_Optional_Id, (l1, l2s) => new { l1, l2s }) .SelectMany(g => g.l2s.DefaultIfEmpty(), (g, l2) => new { g.l1, l2 }) - .Concat(ctx.Set().GroupJoin(ctx.Set(), l2 => l2.Level1_Optional_Id, l1 => l1.Id, (l2, l1s) => new { l2, l1s }) - .SelectMany(g => g.l1s.DefaultIfEmpty(), (g, l1) => new { l1, g.l2 }) - .Where(e => e.l1.Equals(null))) + .Concat( + ctx.Set().GroupJoin(ctx.Set(), l2 => l2.Level1_Optional_Id, l1 => l1.Id, (l2, l1s) => new { l2, l1s }) + .SelectMany(g => g.l1s.DefaultIfEmpty(), (g, l1) => new { l1, g.l2 }) + .Where(e => e.l1.Equals(null))) .Select(e => e.l1.Id); var result = query.ToList(); @@ -5734,12 +5783,13 @@ public virtual Task Lift_projection_mapping_when_pushing_down_subquery(bool isAs isAsync, ss => ss.Set() .Take(25) - .Select(l1 => new - { - l1.Id, - c1 = l1.OneToMany_Required1.Select(l2 => new { l2.Id }).FirstOrDefault(), - c2 = l1.OneToMany_Required1.Select(l2 => new { l2.Id }) - }), + .Select( + l1 => new + { + l1.Id, + c1 = l1.OneToMany_Required1.Select(l2 => new { l2.Id }).FirstOrDefault(), + c2 = l1.OneToMany_Required1.Select(l2 => new { l2.Id }) + }), elementSorter: t => t.Id, elementAsserter: (e, a) => { diff --git a/test/EFCore.Specification.Tests/Query/ComplexNavigationsWeakQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/ComplexNavigationsWeakQueryTestBase.cs index 4cb29354172..53077176ef1 100644 --- a/test/EFCore.Specification.Tests/Query/ComplexNavigationsWeakQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/ComplexNavigationsWeakQueryTestBase.cs @@ -81,13 +81,15 @@ public override Task Multiple_SelectMany_with_nested_navigations_and_explicit_De } [ConditionalTheory(Skip = "issue #13560")] - public override Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany(bool isAsync) + public override Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany( + bool isAsync) { return base.SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany(isAsync); } [ConditionalTheory(Skip = "issue #13560")] - public override Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany2(bool isAsync) + public override Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany2( + bool isAsync) { return base.SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany2(isAsync); } @@ -99,9 +101,11 @@ public override Task SelectMany_with_nested_navigations_and_additional_joins_out } [ConditionalTheory(Skip = "issue #13560")] - public override Task Complex_SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_with_other_query_operators_composed_on_top(bool isAsync) + public override Task + Complex_SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_with_other_query_operators_composed_on_top(bool isAsync) { - return base.Complex_SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_with_other_query_operators_composed_on_top(isAsync); + return base.Complex_SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_with_other_query_operators_composed_on_top( + isAsync); } [ConditionalTheory(Skip = "Issue#16752")] diff --git a/test/EFCore.Specification.Tests/Query/FiltersTestBase.cs b/test/EFCore.Specification.Tests/Query/FiltersTestBase.cs index f9d48d84957..85a011393b4 100644 --- a/test/EFCore.Specification.Tests/Query/FiltersTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/FiltersTestBase.cs @@ -52,8 +52,9 @@ public virtual void Client_eval() { Assert.Equal( CoreStrings.TranslationFailed("DbSet .Where(p => NorthwindContext.ClientMethod(p))"), - RemoveNewLines(Assert.Throws( - () => _context.Products.ToList()).Message)); + RemoveNewLines( + Assert.Throws( + () => _context.Products.ToList()).Message)); } [ConditionalFact] @@ -136,8 +137,9 @@ public virtual void Included_one_to_many_query_with_client_eval() { Assert.Equal( CoreStrings.TranslationFailed("DbSet .Where(p => NorthwindContext.ClientMethod(p))"), - RemoveNewLines(Assert.Throws( - () => _context.Products.Include(p => p.OrderDetails).ToList()).Message)); + RemoveNewLines( + Assert.Throws( + () => _context.Products.Include(p => p.OrderDetails).ToList()).Message)); } [ConditionalFact] diff --git a/test/EFCore.Specification.Tests/Query/FunkyDataQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/FunkyDataQueryTestBase.cs index 8f85c95152c..65ab4c5f9e2 100644 --- a/test/EFCore.Specification.Tests/Query/FunkyDataQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/FunkyDataQueryTestBase.cs @@ -30,12 +30,14 @@ public virtual async Task String_contains_on_argument_with_wildcard_constant(boo await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.Contains("%B")).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains("%B")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains("%B")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.Contains("a_")).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains("a_")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains("a_")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, @@ -50,17 +52,20 @@ await AssertQuery( await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.Contains("_Ba_")).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains("_Ba_")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains("_Ba_")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, ss => ss.Set().Where(c => !c.FirstName.Contains("%B%a%r")).Select(c => c.FirstName), - ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.Contains("%B%a%r")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.Contains("%B%a%r")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, ss => ss.Set().Where(c => !c.FirstName.Contains("")).Select(c => c.FirstName), - ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.Contains("")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.Contains("")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, @@ -76,13 +81,15 @@ public virtual async Task String_contains_on_argument_with_wildcard_parameter(bo await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.Contains(prm1)).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains(prm1)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains(prm1)) == true) + .Select(c => c.FirstName)); var prm2 = "a_"; await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.Contains(prm2)).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains(prm2)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains(prm2)) == true) + .Select(c => c.FirstName)); var prm3 = (string)null; await AssertQuery( @@ -100,13 +107,15 @@ await AssertQuery( await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.Contains(prm5)).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains(prm5)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.Contains(prm5)) == true) + .Select(c => c.FirstName)); var prm6 = "%B%a%r"; await AssertQuery( isAsync, ss => ss.Set().Where(c => !c.FirstName.Contains(prm6)).Select(c => c.FirstName), - ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.Contains(prm6)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.Contains(prm6)) == true) + .Select(c => c.FirstName)); var prm7 = ""; await AssertQuery( @@ -148,10 +157,10 @@ public virtual Task String_contains_on_argument_with_wildcard_column_negated(boo return AssertQuery( isAsync, ss => ss.Set().Select(c => c.FirstName) - .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) + .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) .Where(r => !r.fn.Contains(r.ln)), ss => ss.Set().Select(c => c.FirstName) - .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) + .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) .Where(r => r.ln != "" && !MaybeScalar(r.fn, () => MaybeScalar(r.ln, () => r.fn.Contains(r.ln))) == true)); } @@ -162,12 +171,14 @@ public virtual async Task String_starts_with_on_argument_with_wildcard_constant( await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.StartsWith("%B")).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith("%B")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith("%B")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.StartsWith("a_")).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith("a_")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith("a_")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, @@ -182,17 +193,20 @@ await AssertQuery( await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.StartsWith("_Ba_")).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith("_Ba_")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith("_Ba_")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, ss => ss.Set().Where(c => !c.FirstName.StartsWith("%B%a%r")).Select(c => c.FirstName), - ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.StartsWith("%B%a%r")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.StartsWith("%B%a%r")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, ss => ss.Set().Where(c => !c.FirstName.StartsWith("")).Select(c => c.FirstName), - ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.StartsWith("")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.StartsWith("")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, @@ -208,13 +222,15 @@ public virtual async Task String_starts_with_on_argument_with_wildcard_parameter await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.StartsWith(prm1)).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith(prm1)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith(prm1)) == true) + .Select(c => c.FirstName)); var prm2 = "a_"; await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.StartsWith(prm2)).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith(prm2)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith(prm2)) == true) + .Select(c => c.FirstName)); var prm3 = (string)null; await AssertQuery( @@ -232,13 +248,15 @@ await AssertQuery( await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.StartsWith(prm5)).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith(prm5)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.StartsWith(prm5)) == true) + .Select(c => c.FirstName)); var prm6 = "%B%a%r"; await AssertQuery( isAsync, ss => ss.Set().Where(c => !c.FirstName.StartsWith(prm6)).Select(c => c.FirstName), - ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.StartsWith(prm6)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.StartsWith(prm6)) == true) + .Select(c => c.FirstName)); var prm7 = ""; await AssertQuery( @@ -293,7 +311,8 @@ await AssertQuery( await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.StartsWith(c.LastName)), - ss => ss.Set().Where(c => c.LastName != null && MaybeScalar(c.FirstName, () => c.FirstName.StartsWith(c.LastName)) == true)); + ss => ss.Set().Where( + c => c.LastName != null && MaybeScalar(c.FirstName, () => c.FirstName.StartsWith(c.LastName)) == true)); } [ConditionalTheory] @@ -323,10 +342,10 @@ public virtual Task String_starts_with_on_argument_with_wildcard_column_negated( return AssertQuery( isAsync, ss => ss.Set().Select(c => c.FirstName) - .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) + .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) .Where(r => !r.fn.StartsWith(r.ln)), ss => ss.Set().Select(c => c.FirstName) - .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) + .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) .Where(r => r.ln != "" && !MaybeScalar(r.fn, () => MaybeScalar(r.ln, () => r.fn.StartsWith(r.ln))) == true)); } @@ -337,12 +356,14 @@ public virtual async Task String_ends_with_on_argument_with_wildcard_constant(bo await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.EndsWith("%B")).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith("%B")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith("%B")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.EndsWith("a_")).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith("a_")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith("a_")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, @@ -357,17 +378,20 @@ await AssertQuery( await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.EndsWith("_Ba_")).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith("_Ba_")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith("_Ba_")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, ss => ss.Set().Where(c => !c.FirstName.EndsWith("%B%a%r")).Select(c => c.FirstName), - ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.EndsWith("%B%a%r")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.EndsWith("%B%a%r")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, ss => ss.Set().Where(c => !c.FirstName.EndsWith("")).Select(c => c.FirstName), - ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.EndsWith("")) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.EndsWith("")) == true) + .Select(c => c.FirstName)); await AssertQuery( isAsync, @@ -383,13 +407,15 @@ public virtual async Task String_ends_with_on_argument_with_wildcard_parameter(b await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.EndsWith(prm1)).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith(prm1)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith(prm1)) == true) + .Select(c => c.FirstName)); var prm2 = "a_"; await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.EndsWith(prm2)).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith(prm2)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith(prm2)) == true) + .Select(c => c.FirstName)); var prm3 = (string)null; await AssertQuery( @@ -407,13 +433,15 @@ await AssertQuery( await AssertQuery( isAsync, ss => ss.Set().Where(c => c.FirstName.EndsWith(prm5)).Select(c => c.FirstName), - ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith(prm5)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => MaybeScalar(c.FirstName, () => c.FirstName.EndsWith(prm5)) == true) + .Select(c => c.FirstName)); var prm6 = "%B%a%r"; await AssertQuery( isAsync, ss => ss.Set().Where(c => !c.FirstName.EndsWith(prm6)).Select(c => c.FirstName), - ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.EndsWith(prm6)) == true).Select(c => c.FirstName)); + ss => ss.Set().Where(c => !MaybeScalar(c.FirstName, () => c.FirstName.EndsWith(prm6)) == true) + .Select(c => c.FirstName)); var prm7 = ""; await AssertQuery( @@ -455,12 +483,11 @@ public virtual Task String_ends_with_on_argument_with_wildcard_column_negated(bo return AssertQuery( isAsync, ss => ss.Set().Select(c => c.FirstName) - .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) + .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) .Where(r => !r.fn.EndsWith(r.ln)), ss => ss.Set().Select(c => c.FirstName) - .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) + .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) .Where(r => r.ln != "" && !MaybeScalar(r.fn, () => MaybeScalar(r.ln, () => r.fn.EndsWith(r.ln))) == true)); - } [ConditionalTheory] @@ -474,7 +501,10 @@ public virtual Task String_ends_with_inside_conditional(bool isAsync) .Where(r => r.fn.EndsWith(r.ln) ? true : false), ss => ss.Set().Select(c => c.FirstName) .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) - .Where(r => r.ln == "" || MaybeScalar(r.fn, () => MaybeScalar(r.ln, () => r.fn.EndsWith(r.ln))) == true ? true : false), + .Where( + r => r.ln == "" || MaybeScalar(r.fn, () => MaybeScalar(r.ln, () => r.fn.EndsWith(r.ln))) == true + ? true + : false), elementSorter: e => (e.fn, e.ln), elementAsserter: (e, a) => { @@ -490,12 +520,14 @@ public virtual Task String_ends_with_inside_conditional_negated(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Select(c => c.FirstName) - .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) + .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) .Where(r => !r.fn.EndsWith(r.ln) ? true : false), ss => ss.Set().Select(c => c.FirstName) - .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) - .Where(r => r.ln != "" && !MaybeScalar(r.fn, () => MaybeScalar(r.ln, () => r.fn.EndsWith(r.ln))) == true ? true : false)); - + .SelectMany(c => ss.Set().Select(c2 => c2.LastName), (fn, ln) => new { fn, ln }) + .Where( + r => r.ln != "" && !MaybeScalar(r.fn, () => MaybeScalar(r.ln, () => r.fn.EndsWith(r.ln))) == true + ? true + : false)); } [ConditionalTheory] @@ -507,8 +539,11 @@ public virtual Task String_ends_with_equals_nullable_column(bool isAsync) ss => ss.Set().SelectMany(c => ss.Set(), (c1, c2) => new { c1, c2 }) .Where(r => r.c1.FirstName.EndsWith(r.c2.LastName) == r.c1.NullableBool.Value), ss => ss.Set().SelectMany(c => ss.Set(), (c1, c2) => new { c1, c2 }) - .Where(r => MaybeScalar(r.c1.FirstName, () => MaybeScalar(r.c2.LastName, () => r.c1.FirstName.EndsWith(r.c2.LastName))) == true - == MaybeScalar(r.c1.NullableBool, () => r.c1.NullableBool.Value) == true), + .Where( + r => MaybeScalar( + r.c1.FirstName, () => MaybeScalar(r.c2.LastName, () => r.c1.FirstName.EndsWith(r.c2.LastName))) + == true + == MaybeScalar(r.c1.NullableBool, () => r.c1.NullableBool.Value)), elementSorter: e => (e.c1.Id, e.c2.Id), elementAsserter: (e, a) => { @@ -526,8 +561,11 @@ public virtual Task String_ends_with_not_equals_nullable_column(bool isAsync) ss => ss.Set().SelectMany(c => ss.Set(), (c1, c2) => new { c1, c2 }) .Where(r => r.c1.FirstName.EndsWith(r.c2.LastName) != r.c1.NullableBool.Value), ss => ss.Set().SelectMany(c => ss.Set(), (c1, c2) => new { c1, c2 }) - .Where(r => MaybeScalar(r.c1.FirstName, () => MaybeScalar(r.c2.LastName, () => r.c1.FirstName.EndsWith(r.c2.LastName))) == true - != MaybeScalar(r.c1.NullableBool, () => r.c1.NullableBool.Value) == true), + .Where( + r => MaybeScalar( + r.c1.FirstName, () => MaybeScalar(r.c2.LastName, () => r.c1.FirstName.EndsWith(r.c2.LastName))) + == true + != MaybeScalar(r.c1.NullableBool, () => r.c1.NullableBool.Value)), elementSorter: e => (e.c1.Id, e.c2.Id), elementAsserter: (e, a) => { @@ -546,10 +584,10 @@ public abstract class FunkyDataQueryFixtureBase : SharedStoreFixtureBase> - { - { typeof(FunkyCustomer), e => e?.Id }, - }.ToDictionary(e => e.Key, e => (object)e.Value); ; + var entitySorters = + new Dictionary> { { typeof(FunkyCustomer), e => e?.Id } }.ToDictionary( + e => e.Key, e => (object)e.Value); + ; var entityAsserters = new Dictionary> { @@ -565,8 +603,9 @@ public FunkyDataQueryFixtureBase() Assert.Equal(e.NullableBool, a.NullableBool); } } - }, - }.ToDictionary(e => e.Key, e => (object)e.Value); ; + } + }.ToDictionary(e => e.Key, e => (object)e.Value); + ; QueryAsserter = new QueryAsserter( CreateContext, diff --git a/test/EFCore.Specification.Tests/Query/GearsOfWarQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/GearsOfWarQueryTestBase.cs index c137abca516..f84e742025b 100644 --- a/test/EFCore.Specification.Tests/Query/GearsOfWarQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/GearsOfWarQueryTestBase.cs @@ -7,7 +7,6 @@ using System.Linq.Expressions; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Diagnostics; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.TestModels.GearsOfWarModel; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; @@ -69,11 +68,7 @@ public virtual Task ToString_guid_property_projection(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Select( - ct => new - { - A = ct.GearNickName, - B = ct.Id.ToString() - }), + ct => new { A = ct.GearNickName, B = ct.Id.ToString() }), elementSorter: e => e.B, elementAsserter: (e, a) => { @@ -155,8 +150,7 @@ public virtual Task Include_using_alternate_key(bool isAsync) { var expectedIncludes = new List { - new ExpectedInclude(g => g.Weapons, "Weapons"), - new ExpectedInclude(o => o.Weapons, "Weapons") + new ExpectedInclude(g => g.Weapons, "Weapons"), new ExpectedInclude(o => o.Weapons, "Weapons") }; return AssertIncludeQuery( @@ -184,10 +178,7 @@ public virtual Task Include_multiple_include_then_include(bool isAsync) [MemberData(nameof(IsAsyncData))] public virtual Task Include_navigation_on_derived_type(bool isAsync) { - var expectedIncludes = new List - { - new ExpectedInclude(o => o.Reports, "Reports") - }; + var expectedIncludes = new List { new ExpectedInclude(o => o.Reports, "Reports") }; return AssertIncludeQuery( isAsync, @@ -199,10 +190,7 @@ public virtual Task Include_navigation_on_derived_type(bool isAsync) [MemberData(nameof(IsAsyncData))] public virtual Task String_based_Include_navigation_on_derived_type(bool isAsync) { - var expectedIncludes = new List - { - new ExpectedInclude(o => o.Reports, "Reports") - }; + var expectedIncludes = new List { new ExpectedInclude(o => o.Reports, "Reports") }; return AssertIncludeQuery( isAsync, @@ -214,10 +202,7 @@ public virtual Task String_based_Include_navigation_on_derived_type(bool isAsync [MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Included(bool isAsync) { - var expectedIncludes = new List - { - new ExpectedInclude(t => t.Gear, "Gear") - }; + var expectedIncludes = new List { new ExpectedInclude(t => t.Gear, "Gear") }; return AssertIncludeQuery( isAsync, @@ -244,16 +229,8 @@ public virtual Task Include_with_join_reference1(bool isAsync) isAsync, ss => ss.Set().Join( ss.Set(), - g => new - { - SquadId = (int?)g.SquadId, - g.Nickname - }, - t => new - { - SquadId = t.GearSquadId, - Nickname = t.GearNickName - }, + g => new { SquadId = (int?)g.SquadId, g.Nickname }, + t => new { SquadId = t.GearSquadId, Nickname = t.GearNickName }, (g, t) => g).Include(g => g.CityOfBirth), expectedIncludes); } @@ -272,16 +249,8 @@ public virtual Task Include_with_join_reference2(bool isAsync) isAsync, ss => ss.Set().Join( ss.Set(), - t => new - { - SquadId = t.GearSquadId, - Nickname = t.GearNickName - }, - g => new - { - SquadId = (int?)g.SquadId, - g.Nickname - }, + t => new { SquadId = t.GearSquadId, Nickname = t.GearNickName }, + g => new { SquadId = (int?)g.SquadId, g.Nickname }, (t, g) => g).Include(g => g.CityOfBirth), expectedIncludes); } @@ -292,24 +261,15 @@ public virtual Task Include_with_join_collection1(bool isAsync) { var expectedIncludes = new List { - new ExpectedInclude(g => g.Weapons, "Weapons"), - new ExpectedInclude(o => o.Weapons, "Weapons") + new ExpectedInclude(g => g.Weapons, "Weapons"), new ExpectedInclude(o => o.Weapons, "Weapons") }; return AssertIncludeQuery( isAsync, ss => ss.Set().Join( ss.Set(), - g => new - { - SquadId = (int?)g.SquadId, - g.Nickname - }, - t => new - { - SquadId = t.GearSquadId, - Nickname = t.GearNickName - }, + g => new { SquadId = (int?)g.SquadId, g.Nickname }, + t => new { SquadId = t.GearSquadId, Nickname = t.GearNickName }, (g, t) => g).Include(g => g.Weapons), expectedIncludes); } @@ -320,24 +280,15 @@ public virtual Task Include_with_join_collection2(bool isAsync) { var expectedIncludes = new List { - new ExpectedInclude(g => g.Weapons, "Weapons"), - new ExpectedInclude(o => o.Weapons, "Weapons") + new ExpectedInclude(g => g.Weapons, "Weapons"), new ExpectedInclude(o => o.Weapons, "Weapons") }; return AssertIncludeQuery( isAsync, ss => ss.Set().Join( ss.Set(), - t => new - { - SquadId = t.GearSquadId, - Nickname = t.GearNickName - }, - g => new - { - SquadId = (int?)g.SquadId, - g.Nickname - }, + t => new { SquadId = t.GearSquadId, Nickname = t.GearNickName }, + g => new { SquadId = (int?)g.SquadId, g.Nickname }, (t, g) => g).Include(g => g.Weapons), expectedIncludes); } @@ -428,16 +379,8 @@ public virtual Task Include_with_join_multi_level(bool isAsync) isAsync, ss => ss.Set().Join( ss.Set(), - g => new - { - SquadId = (int?)g.SquadId, - g.Nickname - }, - t => new - { - SquadId = t.GearSquadId, - Nickname = t.GearNickName - }, + g => new { SquadId = (int?)g.SquadId, g.Nickname }, + t => new { SquadId = t.GearSquadId, Nickname = t.GearNickName }, (g, t) => g).Include(g => g.CityOfBirth.StationedGears), expectedIncludes); } @@ -446,25 +389,14 @@ public virtual Task Include_with_join_multi_level(bool isAsync) [MemberData(nameof(IsAsyncData))] public virtual Task Include_with_join_and_inheritance1(bool isAsync) { - var expectedIncludes = new List - { - new ExpectedInclude(o => o.CityOfBirth, "CityOfBirth") - }; + var expectedIncludes = new List { new ExpectedInclude(o => o.CityOfBirth, "CityOfBirth") }; return AssertIncludeQuery( isAsync, ss => ss.Set().Join( ss.Set().OfType(), - t => new - { - SquadId = t.GearSquadId, - Nickname = t.GearNickName - }, - o => new - { - SquadId = (int?)o.SquadId, - o.Nickname - }, + t => new { SquadId = t.GearSquadId, Nickname = t.GearNickName }, + o => new { SquadId = (int?)o.SquadId, o.Nickname }, (t, o) => o).Include(o => o.CityOfBirth), expectedIncludes); } @@ -473,26 +405,16 @@ public virtual Task Include_with_join_and_inheritance1(bool isAsync) [MemberData(nameof(IsAsyncData))] public virtual Task Include_with_join_and_inheritance_with_orderby_before_and_after_include(bool isAsync) { - var expectedIncludes = new List - { - new ExpectedInclude(o => o.Reports, "Reports") - }; + var expectedIncludes = new List { new ExpectedInclude(o => o.Reports, "Reports") }; return AssertIncludeQuery( isAsync, ss => ss.Set().Join( - ss.Set().OfType().OrderBy(ee => ee.SquadId), - t => new - { - SquadId = t.GearSquadId, - Nickname = t.GearNickName - }, - o => new - { - SquadId = (int?)o.SquadId, - o.Nickname - }, - (t, o) => o).OrderBy(ee => ee.FullName).Include(o => o.Reports).OrderBy(oo => oo.HasSoulPatch).ThenByDescending(oo => oo.Nickname), + ss.Set().OfType().OrderBy(ee => ee.SquadId), + t => new { SquadId = t.GearSquadId, Nickname = t.GearNickName }, + o => new { SquadId = (int?)o.SquadId, o.Nickname }, + (t, o) => o).OrderBy(ee => ee.FullName).Include(o => o.Reports).OrderBy(oo => oo.HasSoulPatch) + .ThenByDescending(oo => oo.Nickname), expectedIncludes, assertOrder: true); } @@ -501,25 +423,14 @@ public virtual Task Include_with_join_and_inheritance_with_orderby_before_and_af [MemberData(nameof(IsAsyncData))] public virtual Task Include_with_join_and_inheritance2(bool isAsync) { - var expectedIncludes = new List - { - new ExpectedInclude(o => o.Weapons, "Weapons") - }; + var expectedIncludes = new List { new ExpectedInclude(o => o.Weapons, "Weapons") }; return AssertIncludeQuery( isAsync, ss => ss.Set().OfType().Join( ss.Set(), - o => new - { - SquadId = (int?)o.SquadId, - o.Nickname - }, - t => new - { - SquadId = t.GearSquadId, - Nickname = t.GearNickName - }, + o => new { SquadId = (int?)o.SquadId, o.Nickname }, + t => new { SquadId = t.GearSquadId, Nickname = t.GearNickName }, (o, t) => o).Include(g => g.Weapons), expectedIncludes); } @@ -528,25 +439,14 @@ public virtual Task Include_with_join_and_inheritance2(bool isAsync) [MemberData(nameof(IsAsyncData))] public virtual Task Include_with_join_and_inheritance3(bool isAsync) { - var expectedIncludes = new List - { - new ExpectedInclude(o => o.Reports, "Reports") - }; + var expectedIncludes = new List { new ExpectedInclude(o => o.Reports, "Reports") }; return AssertIncludeQuery( isAsync, ss => ss.Set().Join( ss.Set().OfType(), - t => new - { - SquadId = t.GearSquadId, - Nickname = t.GearNickName - }, - g => new - { - SquadId = (int?)g.SquadId, - g.Nickname - }, + t => new { SquadId = t.GearSquadId, Nickname = t.GearNickName }, + g => new { SquadId = (int?)g.SquadId, g.Nickname }, (t, o) => o).Include(o => o.Reports), expectedIncludes); } @@ -555,10 +455,7 @@ public virtual Task Include_with_join_and_inheritance3(bool isAsync) [MemberData(nameof(IsAsyncData))] public virtual Task Include_with_nested_navigation_in_order_by(bool isAsync) { - var expectedIncludes = new List - { - new ExpectedInclude(w => w.Owner, "Owner") - }; + var expectedIncludes = new List { new ExpectedInclude(w => w.Owner, "Owner") }; return AssertIncludeQuery( isAsync, @@ -787,12 +684,14 @@ public virtual async Task Where_enum_has_flag_subquery_with_pushdown(bool isAsyn { await AssertQuery( isAsync, - ss => ss.Set().Where(g => g.Rank.HasFlag(ss.Set().OrderBy(x => x.Nickname).ThenBy(x => x.SquadId).FirstOrDefault().Rank))); + ss => ss.Set().Where( + g => g.Rank.HasFlag(ss.Set().OrderBy(x => x.Nickname).ThenBy(x => x.SquadId).FirstOrDefault().Rank))); await AssertQuery( isAsync, ss => ss.Set().Where( - g => MilitaryRank.Corporal.HasFlag(ss.Set().OrderBy(x => x.Nickname).ThenBy(x => x.SquadId).FirstOrDefault().Rank))); + g => MilitaryRank.Corporal.HasFlag( + ss.Set().OrderBy(x => x.Nickname).ThenBy(x => x.SquadId).FirstOrDefault().Rank))); } [ConditionalTheory] @@ -801,7 +700,8 @@ public virtual Task Where_enum_has_flag_subquery_client_eval(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(g => g.Rank.HasFlag(ss.Set().OrderBy(x => x.Nickname).ThenBy(x => x.SquadId).First().Rank))); + ss => ss.Set().Where( + g => g.Rank.HasFlag(ss.Set().OrderBy(x => x.Nickname).ThenBy(x => x.SquadId).First().Rank))); } [ConditionalTheory] @@ -837,8 +737,7 @@ public virtual Task Select_enum_has_flag(bool isAsync) .Select( b => new { - hasFlagTrue = b.Rank.HasFlag(MilitaryRank.Corporal), - hasFlagFalse = b.Rank.HasFlag(MilitaryRank.Sergeant) + hasFlagTrue = b.Rank.HasFlag(MilitaryRank.Corporal), hasFlagFalse = b.Rank.HasFlag(MilitaryRank.Sergeant) })); } @@ -869,11 +768,7 @@ public virtual Task Select_inverted_boolean(bool isAsync) ss => ss.Set() .Where(w => w.IsAutomatic) .Select( - w => new - { - w.Id, - Manual = !w.IsAutomatic - }), + w => new { w.Id, Manual = !w.IsAutomatic }), elementSorter: e => e.Id); } @@ -888,11 +783,7 @@ await AssertQuery( ss => ss.Set() .Where(w => w.AmmunitionType == ammunitionType) .Select( - w => new - { - w.Id, - Cartridge = w.AmmunitionType == ammunitionType - }), + w => new { w.Id, Cartridge = w.AmmunitionType == ammunitionType }), elementSorter: e => e.Id); ammunitionType = null; @@ -902,11 +793,7 @@ await AssertQuery( ss => ss.Set() .Where(w => w.AmmunitionType == ammunitionType) .Select( - w => new - { - w.Id, - Cartridge = w.AmmunitionType == ammunitionType - }), + w => new { w.Id, Cartridge = w.AmmunitionType == ammunitionType }), elementSorter: e => e.Id); } @@ -920,11 +807,7 @@ await AssertQuery( isAsync, ss => ss.Set() .Select( - w => new - { - w.Id, - AmmoType = ammunitionType - }), + w => new { w.Id, AmmoType = ammunitionType }), elementSorter: e => e.Id); ammunitionType = null; @@ -933,11 +816,7 @@ await AssertQuery( isAsync, ss => ss.Set() .Select( - w => new - { - w.Id, - AmmoType = ammunitionType - }), + w => new { w.Id, AmmoType = ammunitionType }), elementSorter: e => e.Id); ammunitionType = AmmunitionType.Shell; @@ -946,11 +825,7 @@ await AssertQuery( isAsync, ss => ss.Set() .Select( - w => new - { - w.Id, - AmmoType = ammunitionType - }), + w => new { w.Id, AmmoType = ammunitionType }), elementSorter: e => e.Id); ammunitionType = null; @@ -959,11 +834,7 @@ await AssertQuery( isAsync, ss => ss.Set() .Select( - w => new - { - w.Id, - AmmoType = ammunitionType - }), + w => new { w.Id, AmmoType = ammunitionType }), elementSorter: e => e.Id); } @@ -974,11 +845,7 @@ public virtual Task Select_ternary_operation_with_boolean(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Select( - w => new - { - w.Id, - Num = w.IsAutomatic ? 1 : 0 - }), + w => new { w.Id, Num = w.IsAutomatic ? 1 : 0 }), elementSorter: e => e.Id); } @@ -989,11 +856,7 @@ public virtual Task Select_ternary_operation_with_inverted_boolean(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Select( - w => new - { - w.Id, - Num = !w.IsAutomatic ? 1 : 0 - }), + w => new { w.Id, Num = !w.IsAutomatic ? 1 : 0 }), elementSorter: e => e.Id); } @@ -1021,11 +884,7 @@ public virtual Task Select_ternary_operation_multiple_conditions(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Select( - w => new - { - w.Id, - IsCartridge = w.AmmunitionType == AmmunitionType.Shell && w.SynergyWithId == 1 ? "Yes" : "No" - }), + w => new { w.Id, IsCartridge = w.AmmunitionType == AmmunitionType.Shell && w.SynergyWithId == 1 ? "Yes" : "No" }), elementSorter: e => e.Id); } @@ -1036,11 +895,7 @@ public virtual Task Select_ternary_operation_multiple_conditions_2(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Select( - w => new - { - w.Id, - IsCartridge = !w.IsAutomatic && w.SynergyWithId == 1 ? "Yes" : "No" - }), + w => new { w.Id, IsCartridge = !w.IsAutomatic && w.SynergyWithId == 1 ? "Yes" : "No" }), elementSorter: e => e.Id); } @@ -1051,11 +906,7 @@ public virtual Task Select_multiple_conditions(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Select( - w => new - { - w.Id, - IsCartridge = !w.IsAutomatic && w.SynergyWithId == 1 - }), + w => new { w.Id, IsCartridge = !w.IsAutomatic && w.SynergyWithId == 1 }), elementSorter: e => e.Id); } @@ -1091,7 +942,8 @@ public virtual Task Null_propagation_optimization2(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(g => (g.LeaderNickname == null ? (bool?)null : (bool?)g.LeaderNickname.EndsWith("us")) == (bool?)true)); + ss => ss.Set().Where( + g => (g.LeaderNickname == null ? (bool?)null : (bool?)g.LeaderNickname.EndsWith("us")) == (bool?)true)); } [ConditionalTheory] @@ -1100,7 +952,8 @@ public virtual Task Null_propagation_optimization3(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(g => (g.LeaderNickname != null ? (bool?)g.LeaderNickname.EndsWith("us") : (bool?)null) == (bool?)true)); + ss => ss.Set().Where( + g => (g.LeaderNickname != null ? (bool?)g.LeaderNickname.EndsWith("us") : (bool?)null) == (bool?)true)); } [ConditionalTheory] @@ -1123,7 +976,8 @@ public virtual Task Null_propagation_optimization5(bool isAsync) ss => ss.Set().Where( g => (null != g.LeaderNickname ? (int?)(EF.Property(g, "LeaderNickname").Length) : (int?)null) == 5 == (bool?)true), - ss => ss.Set().Where(g => (null != g.LeaderNickname ? (int?)(g.LeaderNickname.Length) : (int?)null) == 5 == (bool?)true)); + ss => ss.Set().Where( + g => (null != g.LeaderNickname ? (int?)(g.LeaderNickname.Length) : (int?)null) == 5 == (bool?)true)); } [ConditionalTheory] @@ -1133,8 +987,10 @@ public virtual Task Null_propagation_optimization6(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Where( - g => (null != g.LeaderNickname ? (int?)EF.Property(g, "LeaderNickname").Length : (int?)null) == 5 == (bool?)true), - ss => ss.Set().Where(g => (null != g.LeaderNickname ? (int?)g.LeaderNickname.Length : (int?)null) == 5 == (bool?)true)); + g => (null != g.LeaderNickname ? (int?)EF.Property(g, "LeaderNickname").Length : (int?)null) == 5 + == (bool?)true), + ss => ss.Set().Where( + g => (null != g.LeaderNickname ? (int?)g.LeaderNickname.Length : (int?)null) == 5 == (bool?)true)); } [ConditionalTheory] @@ -1194,11 +1050,7 @@ public virtual Task Select_null_propagation_negative3(bool isAsync) join g2 in ss.Set() on g1.HasSoulPatch equals true into grouping from g2 in grouping.DefaultIfEmpty() orderby g2.Nickname - select new - { - g2.Nickname, - Condition = g2 != null ? (bool?)(g2.LeaderNickname != null) : (bool?)null - }, + select new { g2.Nickname, Condition = g2 != null ? (bool?)(g2.LeaderNickname != null) : (bool?)null }, ss => from g1 in ss.Set() join g2 in ss.Set() on g1.HasSoulPatch equals true into grouping from g2 in grouping.DefaultIfEmpty() @@ -1241,22 +1093,14 @@ join g2 in ss.Set() on g1.HasSoulPatch equals true into grouping from g2 in grouping.DefaultIfEmpty() orderby g2.Nickname select g2 != null - ? new - { - g2.Nickname, - Five = 5 - } + ? new { g2.Nickname, Five = 5 } : null, ss => from g1 in ss.Set() join g2 in ss.Set() on g1.HasSoulPatch equals true into grouping from g2 in grouping.DefaultIfEmpty() orderby Maybe(g2, () => g2.Nickname) select g2 != null - ? new - { - Nickname = Maybe(g2, () => g2.Nickname), - Five = 5 - } + ? new { Nickname = Maybe(g2, () => g2.Nickname), Five = 5 } : null, assertOrder: true); } @@ -1271,7 +1115,8 @@ public virtual Task Select_null_propagation_negative6(bool isAsync) g => null != g.LeaderNickname ? EF.Property(g, "LeaderNickname").Length != EF.Property(g, "LeaderNickname").Length : (bool?)null), - ss => ss.Set().Select(g => null != g.LeaderNickname ? g.LeaderNickname.Length != g.LeaderNickname.Length : (bool?)null)); + ss => ss.Set().Select( + g => null != g.LeaderNickname ? g.LeaderNickname.Length != g.LeaderNickname.Length : (bool?)null)); } [ConditionalTheory] @@ -1335,10 +1180,7 @@ public virtual Task Select_conditional_with_anonymous_type_and_null_constant(boo ss => from g in ss.Set() orderby g.Nickname select g.LeaderNickname != null - ? new - { - g.HasSoulPatch - } + ? new { g.HasSoulPatch } : null, assertOrder: true); } @@ -1352,14 +1194,8 @@ public virtual Task Select_conditional_with_anonymous_types(bool isAsync) ss => from g in ss.Set() orderby g.Nickname select g.LeaderNickname != null - ? new - { - Name = g.Nickname - } - : new - { - Name = g.FullName - }, + ? new { Name = g.Nickname } + : new { Name = g.FullName }, assertOrder: true); } @@ -1369,17 +1205,14 @@ public virtual Task Where_conditional_with_anonymous_type(bool isAsync) { return AssertTranslationFailed( () => AssertQuery( - isAsync, - ss => from g in ss.Set() - orderby g.Nickname - where (g.LeaderNickname != null - ? new - { - g.HasSoulPatch - } - : null) == null - select g.Nickname, - assertOrder: true)); + isAsync, + ss => from g in ss.Set() + orderby g.Nickname + where (g.LeaderNickname != null + ? new { g.HasSoulPatch } + : null) == null + select g.Nickname, + assertOrder: true)); } [ConditionalTheory] @@ -1390,13 +1223,7 @@ public virtual Task Select_coalesce_with_anonymous_types(bool isAsync) isAsync, ss => from g in ss.Set() orderby g.Nickname - select new - { - Name = g.LeaderNickname - } ?? new - { - Name = g.FullName - }, + select new { Name = g.LeaderNickname } ?? new { Name = g.FullName }, assertOrder: true); } @@ -1406,16 +1233,10 @@ public virtual Task Where_coalesce_with_anonymous_types(bool isAsync) { return AssertTranslationFailed( () => AssertQuery( - isAsync, - ss => from g in ss.Set() - where (new - { - Name = g.LeaderNickname - } ?? new - { - Name = g.FullName - }) != null - select g.Nickname)); + isAsync, + ss => from g in ss.Set() + where (new { Name = g.LeaderNickname } ?? new { Name = g.FullName }) != null + select g.Nickname)); } [ConditionalTheory(Skip = "issue #8421")] @@ -1426,17 +1247,8 @@ public virtual Task Where_compare_anonymous_types(bool isAsync) isAsync, ss => from g in ss.Set() from o in ss.Set().OfType() - where new - { - Name = g.LeaderNickname, - Squad = g.LeaderSquadId, - Five = 5 - } == new - { - Name = o.Nickname, - Squad = o.SquadId, - Five = 5 - } + where new { Name = g.LeaderNickname, Squad = g.LeaderSquadId, Five = 5 } + == new { Name = o.Nickname, Squad = o.SquadId, Five = 5 } select g.Nickname); } @@ -1447,11 +1259,7 @@ public virtual Task Where_member_access_on_anonymous_type(bool isAsync) return AssertQuery( isAsync, ss => from g in ss.Set() - where new - { - Name = g.LeaderNickname, - Squad = g.LeaderSquadId - }.Name == "Marcus" + where new { Name = g.LeaderNickname, Squad = g.LeaderSquadId }.Name == "Marcus" select g.Nickname); } @@ -1462,14 +1270,8 @@ public virtual Task Where_compare_anonymous_types_with_uncorrelated_members(bool return AssertQuery( isAsync, ss => from g in ss.Set() - // ReSharper disable once EqualExpressionComparison - where new - { - Five = 5 - } == new - { - Five = 5 - } + // ReSharper disable once EqualExpressionComparison + where new { Five = 5 } == new { Five = 5 } select g.Nickname); } @@ -1496,19 +1298,11 @@ public virtual Task Select_Where_Navigation_Scalar_Equals_Navigation_Scalar(bool ss => from t1 in ss.Set() from t2 in ss.Set() where t1.Gear.Nickname == t2.Gear.Nickname - select new - { - Tag1 = t1, - Tag2 = t2 - }, + select new { Tag1 = t1, Tag2 = t2 }, ss => from t1 in ss.Set() from t2 in ss.Set() where Maybe(t1.Gear, () => t1.Gear.Nickname) == Maybe(t2.Gear, () => t2.Gear.Nickname) - select new - { - Tag1 = t1, - Tag2 = t2 - }, + select new { Tag1 = t1, Tag2 = t2 }, elementSorter: e => (e.Tag1.Id, e.Tag2.Id), elementAsserter: (e, a) => { @@ -1526,19 +1320,11 @@ public virtual Task Select_Where_Navigation_Scalar_Equals_Navigation_Scalar_Proj ss => from t1 in ss.Set() from t2 in ss.Set() where t1.Gear.Nickname == t2.Gear.Nickname - select new - { - Id1 = t1.Id, - Id2 = t2.Id - }, + select new { Id1 = t1.Id, Id2 = t2.Id }, ss => from t1 in ss.Set() from t2 in ss.Set() where Maybe(t1.Gear, () => t1.Gear.Nickname) == Maybe(t2.Gear, () => t2.Gear.Nickname) - select new - { - Id1 = t1.Id, - Id2 = t2.Id - }, + select new { Id1 = t1.Id, Id2 = t2.Id }, elementSorter: e => (e.Id1, e.Id2)); } @@ -1549,15 +1335,9 @@ public virtual Task Optional_Navigation_Null_Coalesce_To_Clr_Type(bool isAsync) return AssertFirst( isAsync, ss => ss.Set().OrderBy(w => w.Id).Select( - w => new Weapon - { - IsAutomatic = (bool?)w.SynergyWith.IsAutomatic ?? false - }), + w => new Weapon { IsAutomatic = (bool?)w.SynergyWith.IsAutomatic ?? false }), ss => ss.Set().OrderBy(w => w.Id).Select( - w => new Weapon - { - IsAutomatic = MaybeScalar(w.SynergyWith, () => w.SynergyWith.IsAutomatic) ?? false - })); + w => new Weapon { IsAutomatic = MaybeScalar(w.SynergyWith, () => w.SynergyWith.IsAutomatic) ?? false })); } [ConditionalTheory] @@ -1584,7 +1364,8 @@ public virtual Task Where_subquery_distinct_firstordefault_boolean(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(g => g.HasSoulPatch && g.Weapons.Distinct().OrderBy(w => w.Id).Select(w => w.IsAutomatic).FirstOrDefault())); + ss => ss.Set().Where( + g => g.HasSoulPatch && g.Weapons.Distinct().OrderBy(w => w.Id).Select(w => w.IsAutomatic).FirstOrDefault())); } [ConditionalTheory] @@ -1602,7 +1383,8 @@ public virtual Task Where_subquery_distinct_first_boolean(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().OrderBy(g => g.Nickname).Where(g => g.HasSoulPatch && g.Weapons.Distinct().OrderBy(w => w.Id).First().IsAutomatic), + ss => ss.Set().OrderBy(g => g.Nickname) + .Where(g => g.HasSoulPatch && g.Weapons.Distinct().OrderBy(w => w.Id).First().IsAutomatic), assertOrder: true); } @@ -1671,7 +1453,8 @@ public virtual Task Where_subquery_distinct_orderby_firstordefault_boolean(bool { return AssertQuery( isAsync, - ss => ss.Set().Where(g => g.HasSoulPatch && g.Weapons.Distinct().OrderBy(w => w.Id).Select(w => w.IsAutomatic).FirstOrDefault())); + ss => ss.Set().Where( + g => g.HasSoulPatch && g.Weapons.Distinct().OrderBy(w => w.Id).Select(w => w.IsAutomatic).FirstOrDefault())); } [ConditionalTheory] @@ -1689,7 +1472,8 @@ public virtual Task Where_subquery_union_firstordefault_boolean(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(g => g.HasSoulPatch && g.Weapons.Union(g.Weapons).OrderBy(w => w.Id).FirstOrDefault().IsAutomatic)); + ss => ss.Set().Where( + g => g.HasSoulPatch && g.Weapons.Union(g.Weapons).OrderBy(w => w.Id).FirstOrDefault().IsAutomatic)); } [ConditionalTheory] @@ -1698,8 +1482,9 @@ public virtual async Task Where_subquery_concat_firstordefault_boolean(bool isAs { var message = (await Assert.ThrowsAsync( () => AssertQuery( - isAsync, - ss => ss.Set().Where(g => g.HasSoulPatch && g.Weapons.Concat(g.Weapons).OrderBy(w => w.Id).FirstOrDefault().IsAutomatic)))).Message; + isAsync, + ss => ss.Set().Where( + g => g.HasSoulPatch && g.Weapons.Concat(g.Weapons).OrderBy(w => w.Id).FirstOrDefault().IsAutomatic)))).Message; } [ConditionalTheory] @@ -1728,18 +1513,10 @@ public virtual Task Concat_anonymous_with_count(bool isAsync) isAsync, ss => ss.Set() .Select( - g => new - { - Gear = g, - Name = g.Nickname - }) + g => new { Gear = g, Name = g.Nickname }) .Concat( ss.Set().Select( - g2 => new - { - Gear = g2, - Name = g2.FullName - }))); + g2 => new { Gear = g2, Name = g2.FullName }))); } [ConditionalTheory] @@ -1768,11 +1545,12 @@ public virtual async Task Select_navigation_with_concat_and_count(bool isAsync) { var message = (await Assert.ThrowsAsync( () => AssertQueryScalar( - isAsync, - ss => ss.Set().Where(g => !g.HasSoulPatch).Select(g => g.Weapons.Concat(g.Weapons).Count())))).Message; + isAsync, + ss => ss.Set().Where(g => !g.HasSoulPatch).Select(g => g.Weapons.Concat(g.Weapons).Count())))).Message; Assert.Equal( - CoreStrings.QueryFailed(@"(MaterializeCollectionNavigation( + CoreStrings.QueryFailed( + @"(MaterializeCollectionNavigation( navigation: Navigation: Gear.Weapons, subquery: (NavigationExpansionExpression Source: DbSet @@ -1821,11 +1599,12 @@ public virtual async Task Concat_with_collection_navigations(bool isAsync) { var message = (await Assert.ThrowsAsync( () => AssertQueryScalar( - isAsync, - ss => ss.Set().Where(g => g.HasSoulPatch).Select(g => g.Weapons.Union(g.Weapons).Count())))).Message; + isAsync, + ss => ss.Set().Where(g => g.HasSoulPatch).Select(g => g.Weapons.Union(g.Weapons).Count())))).Message; Assert.Equal( - CoreStrings.QueryFailed(@"(MaterializeCollectionNavigation( + CoreStrings.QueryFailed( + @"(MaterializeCollectionNavigation( navigation: Navigation: Gear.Weapons, subquery: (NavigationExpansionExpression Source: DbSet @@ -1863,8 +1642,8 @@ public virtual async Task Union_with_collection_navigations(bool isAsync) { var message = (await Assert.ThrowsAsync( () => AssertQueryScalar( - isAsync, - ss => ss.Set().OfType().Select(o => o.Reports.Union(o.Reports).Count())))).Message; + isAsync, + ss => ss.Set().OfType().Select(o => o.Reports.Union(o.Reports).Count())))).Message; } [ConditionalTheory] @@ -1882,10 +1661,10 @@ public virtual Task Select_Where_Navigation_Client(bool isAsync) { return AssertTranslationFailed( () => AssertQuery( - isAsync, - ss => from t in ss.Set() - where t.Gear != null && t.Gear.IsMarcus - select t)); + isAsync, + ss => from t in ss.Set() + where t.Gear != null && t.Gear.IsMarcus + select t)); } [ConditionalTheory] @@ -1919,11 +1698,7 @@ public virtual Task Select_Where_Navigation_Equals_Navigation(bool isAsync) ss => from t1 in ss.Set() from t2 in ss.Set() where t1.Gear == t2.Gear - select new - { - t1, - t2 - }, + select new { t1, t2 }, elementSorter: e => e.t1.Id + " " + e.t2.Id, elementAsserter: (e, a) => { @@ -1941,17 +1716,11 @@ public virtual Task Singleton_Navigation_With_Member_Access(bool isAsync) ss => from ct in ss.Set() where ct.Gear.Nickname == "Marcus" where ct.Gear.CityOfBirthName != "Ephyra" - select new - { - B = ct.Gear.CityOfBirthName - }, + select new { B = ct.Gear.CityOfBirthName }, ss => from ct in ss.Set() where Maybe(ct.Gear, () => ct.Gear.Nickname) == "Marcus" where Maybe(ct.Gear, () => ct.Gear.CityOfBirthName) != "Ephyra" - select new - { - B = Maybe(ct.Gear, () => ct.Gear.CityOfBirthName) - }, + select new { B = Maybe(ct.Gear, () => ct.Gear.CityOfBirthName) }, elementSorter: e => e.B); } @@ -1964,19 +1733,11 @@ public virtual Task Select_Singleton_Navigation_With_Member_Access(bool isAsync) ss => from ct in ss.Set() where ct.Gear.Nickname == "Marcus" where ct.Gear.CityOfBirthName != "Ephyra" - select new - { - A = ct.Gear, - B = ct.Gear.CityOfBirthName - }, + select new { A = ct.Gear, B = ct.Gear.CityOfBirthName }, ss => from ct in ss.Set() where Maybe(ct.Gear, () => ct.Gear.Nickname) == "Marcus" where Maybe(ct.Gear, () => ct.Gear.CityOfBirthName) != "Ephyra" - select new - { - A = ct.Gear, - B = Maybe(ct.Gear, () => ct.Gear.CityOfBirthName) - }, + select new { A = ct.Gear, B = Maybe(ct.Gear, () => ct.Gear.CityOfBirthName) }, elementSorter: e => e.A.Nickname, elementAsserter: (e, a) => { @@ -1994,16 +1755,8 @@ public virtual Task GroupJoin_Composite_Key(bool isAsync) ss => from t in ss.Set() join g in ss.Set() - on new - { - N = t.GearNickName, - S = t.GearSquadId - } - equals new - { - N = g.Nickname, - S = (int?)g.SquadId - } into grouping + on new { N = t.GearNickName, S = t.GearSquadId } + equals new { N = g.Nickname, S = (int?)g.SquadId } into grouping from g in grouping select g); } @@ -2017,19 +1770,11 @@ public virtual Task Join_navigation_translated_to_subquery_composite_key(bool is ss => from g in ss.Set() join t in ss.Set() on g.FullName equals t.Gear.FullName - select new - { - g.FullName, - t.Note - }, + select new { g.FullName, t.Note }, ss => from g in ss.Set() join t in ss.Set() on g.FullName equals Maybe(t.Gear, () => t.Gear.FullName) - select new - { - g.FullName, - t.Note - }, + select new { g.FullName, t.Note }, elementSorter: e => e.FullName); } @@ -2042,19 +1787,11 @@ public virtual Task Join_with_order_by_on_inner_sequence_navigation_translated_t ss => from g in ss.Set() join t in ss.Set().OrderBy(tt => tt.Id) on g.FullName equals t.Gear.FullName - select new - { - g.FullName, - t.Note - }, + select new { g.FullName, t.Note }, ss => from g in ss.Set() join t in ss.Set().OrderBy(tt => tt.Id) on g.FullName equals Maybe(t.Gear, () => t.Gear.FullName) - select new - { - g.FullName, - t.Note - }, + select new { g.FullName, t.Note }, elementSorter: e => e.FullName); } @@ -2090,21 +1827,10 @@ public virtual Task Collection_with_inheritance_and_join_include_joined(bool isA return AssertIncludeQuery( isAsync, ss => (from t in ss.Set() - join g in ss.Set().OfType() on new - { - id1 = t.GearSquadId, - id2 = t.GearNickName - } - equals new - { - id1 = (int?)g.SquadId, - id2 = g.Nickname - } + join g in ss.Set().OfType() on new { id1 = t.GearSquadId, id2 = t.GearNickName } + equals new { id1 = (int?)g.SquadId, id2 = g.Nickname } select g).Include(g => g.Tag), - new List - { - new ExpectedInclude(o => o.Tag, "Tag") - }); + new List { new ExpectedInclude(o => o.Tag, "Tag") }); } [ConditionalTheory] @@ -2114,21 +1840,10 @@ public virtual Task Collection_with_inheritance_and_join_include_source(bool isA return AssertIncludeQuery( isAsync, ss => (from g in ss.Set().OfType() - join t in ss.Set() on new - { - id1 = (int?)g.SquadId, - id2 = g.Nickname - } - equals new - { - id1 = t.GearSquadId, - id2 = t.GearNickName - } + join t in ss.Set() on new { id1 = (int?)g.SquadId, id2 = g.Nickname } + equals new { id1 = t.GearSquadId, id2 = t.GearNickName } select g).Include(g => g.Tag), - new List - { - new ExpectedInclude(o => o.Tag, "Tag") - }); + new List { new ExpectedInclude(o => o.Tag, "Tag") }); } [ConditionalTheory] @@ -2170,12 +1885,7 @@ public virtual Task Non_unicode_parameter_is_used_for_non_unicode_column(bool is [MemberData(nameof(IsAsyncData))] public virtual Task Non_unicode_string_literals_in_contains_is_used_for_non_unicode_column(bool isAsync) { - var cities = new List - { - "Unknown", - "Jacinto's location", - "Ephyra's location" - }; + var cities = new List { "Unknown", "Jacinto's location", "Ephyra's location" }; return AssertQuery( isAsync, @@ -2270,8 +1980,7 @@ public virtual Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce { var expectedIncludes = new List { - new ExpectedInclude(g => g.Weapons, "Weapons"), - new ExpectedInclude(g => g.Weapons, "Weapons") + new ExpectedInclude(g => g.Weapons, "Weapons"), new ExpectedInclude(g => g.Weapons, "Weapons") }; return AssertIncludeQuery( @@ -2290,8 +1999,7 @@ public virtual Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce { var expectedIncludes = new List { - new ExpectedInclude(g => g.Weapons, "Weapons"), - new ExpectedInclude(g => g.Weapons, "Weapons") + new ExpectedInclude(g => g.Weapons, "Weapons"), new ExpectedInclude(g => g.Weapons, "Weapons") }; return AssertIncludeQuery( @@ -2300,20 +2008,10 @@ public virtual Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce join g2 in ss.Set().Include(g => g.Weapons) on g1.LeaderNickname equals g2.Nickname into grouping from g2 in grouping.DefaultIfEmpty() - select new - { - g1, - g2, - coalesce = g2 ?? g1 - }, + select new { g1, g2, coalesce = g2 ?? g1 }, expectedIncludes, elementSorter: e => e.g1.Nickname, - clientProjections: new List> - { - r => r.g1, - r => r.g2, - r => r.coalesce - }); + clientProjections: new List> { r => r.g1, r => r.g2, r => r.coalesce }); } [ConditionalTheory] @@ -2322,8 +2020,7 @@ public virtual Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_inherita { var expectedIncludes = new List { - new ExpectedInclude(g => g.Weapons, "Weapons"), - new ExpectedInclude(g => g.Weapons, "Weapons") + new ExpectedInclude(g => g.Weapons, "Weapons"), new ExpectedInclude(g => g.Weapons, "Weapons") }; return AssertIncludeQuery( @@ -2342,8 +2039,7 @@ public virtual Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_conditio { var expectedIncludes = new List { - new ExpectedInclude(g => g.Weapons, "Weapons"), - new ExpectedInclude(g => g.Weapons, "Weapons") + new ExpectedInclude(g => g.Weapons, "Weapons"), new ExpectedInclude(g => g.Weapons, "Weapons") }; return AssertIncludeQuery( @@ -2364,8 +2060,7 @@ public virtual Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_complex_ { var expectedIncludes = new List { - new ExpectedInclude(g => g.Weapons, "Weapons"), - new ExpectedInclude(g => g.Weapons, "Weapons") + new ExpectedInclude(g => g.Weapons, "Weapons"), new ExpectedInclude(g => g.Weapons, "Weapons") }; return AssertIncludeQuery( @@ -2375,23 +2070,11 @@ join g2 in ss.Set().Include(g => g.Weapons) on g1.LeaderNickname equals g2.Nickname into grouping from g2 in grouping.DefaultIfEmpty() #pragma warning disable IDE0029 // Use coalesce expression - select new - { - g1, - g2, - coalesce = g2 ?? g1, - conditional = g2 != null ? g2 : g1 - }, + select new { g1, g2, coalesce = g2 ?? g1, conditional = g2 != null ? g2 : g1 }, #pragma warning restore IDE0029 // Use coalesce expression expectedIncludes, elementSorter: e => e.g1.Nickname + " " + e.g2?.Nickname, - clientProjections: new List> - { - e => e.g1, - e => e.g2, - e => e.coalesce, - e => e.conditional - }); + clientProjections: new List> { e => e.g1, e => e.g2, e => e.coalesce, e => e.conditional }); } [ConditionalTheory] @@ -2457,9 +2140,10 @@ public virtual Task Optional_navigation_type_compensation_works_with_predicate_n return AssertQuery( isAsync, ss => ss.Set().Where(t => !(t.Gear.HasSoulPatch ? true : t.Gear.HasSoulPatch)), - ss => ss.Set().Where(t => !(MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch) == true - ? (bool?)true - : MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch)) == true)); + ss => ss.Set().Where( + t => !(MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch) == true + ? true + : MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch)) == true)); } [ConditionalTheory] @@ -2469,9 +2153,10 @@ public virtual Task Optional_navigation_type_compensation_works_with_predicate_n return AssertQuery( isAsync, ss => ss.Set().Where(t => !(!t.Gear.HasSoulPatch ? false : t.Gear.HasSoulPatch)), - ss => ss.Set().Where(t => !(MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch) == false - ? (bool?)false - : MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch)) == true)); + ss => ss.Set().Where( + t => !(MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch) == false + ? false + : MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch)) == true)); } [ConditionalTheory] @@ -2503,7 +2188,8 @@ public virtual Task Optional_navigation_type_compensation_works_with_binary_and_ return AssertQueryScalar( isAsync, ss => ss.Set().Select(t => t.Gear.HasSoulPatch && t.Note.Contains("Cole")), - ss => ss.Set().Select(t => MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch) == true && t.Note.Contains("Cole"))); + ss => ss.Set().Select( + t => MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch) == true && t.Note.Contains("Cole"))); } [ConditionalTheory] @@ -2522,10 +2208,7 @@ public virtual Task Optional_navigation_type_compensation_works_with_projection_ return AssertQuery( isAsync, ss => ss.Set().Where(t => t.Note != "K.I.A.").Select( - t => new - { - t.Gear.SquadId - }), + t => new { t.Gear.SquadId }), elementSorter: e => e.SquadId); } @@ -2536,10 +2219,7 @@ public virtual Task Optional_navigation_type_compensation_works_with_DTOs(bool i return AssertQuery( isAsync, ss => ss.Set().Where(t => t.Note != "K.I.A.").Select( - t => new Squad - { - Id = t.Gear.SquadId - }), + t => new Squad { Id = t.Gear.SquadId }), elementSorter: e => e.Id); } @@ -2550,12 +2230,7 @@ public virtual Task Optional_navigation_type_compensation_works_with_list_initia return AssertQuery( isAsync, ss => ss.Set().Where(t => t.Note != "K.I.A.").OrderBy(t => t.Note).Select( - t => new List - { - t.Gear.SquadId, - t.Gear.SquadId + 1, - 42 - }), + t => new List { t.Gear.SquadId, t.Gear.SquadId + 1, 42 }), assertOrder: true); } @@ -2567,8 +2242,8 @@ public virtual Task Optional_navigation_type_compensation_works_with_array_initi isAsync, ss => ss.Set().Where(t => t.Note != "K.I.A.").Select(t => new[] { t.Gear.SquadId }), elementSorter: e => e[0]); - } + [ConditionalTheory] [MemberData(nameof(IsAsyncData))] public virtual Task Optional_navigation_type_compensation_works_with_orderby(bool isAsync) @@ -2661,7 +2336,8 @@ public virtual Task Select_correlated_filtered_collection_with_composite_key(boo { return AssertQuery( isAsync, - ss => ss.Set().OfType().OrderBy(g => g.Nickname).Select(g => g.Reports.Where(r => r.Nickname != "Dom").ToList()), + ss => ss.Set().OfType().OrderBy(g => g.Nickname) + .Select(g => g.Reports.Where(r => r.Nickname != "Dom").ToList()), assertOrder: true, elementAsserter: (e, a) => AssertCollection(e, a)); } @@ -2984,11 +2660,7 @@ from t in ss.Set() join g in ss.Set() on t.GearNickName equals g.Nickname into grouping from g in ClientDefaultIfEmpty(grouping) #pragma warning disable IDE0031 // Use null propagation - select new - { - t.Note, - Nickname = g != null ? g.Nickname : null - }, + select new { t.Note, Nickname = g != null ? g.Nickname : null }, #pragma warning restore IDE0031 // Use null propagation elementSorter: e => e.Note); } @@ -3064,16 +2736,8 @@ public virtual Task Distinct_with_unflattened_groupjoin_is_evaluated_on_client(b isAsync, ss => ss.Set().GroupJoin( ss.Set(), - g => new - { - k1 = g.Nickname, - k2 = (int?)g.SquadId - }, - t => new - { - k1 = t.GearNickName, - k2 = t.GearSquadId - }, + g => new { k1 = g.Nickname, k2 = (int?)g.SquadId }, + t => new { k1 = t.GearNickName, k2 = t.GearSquadId }, (g, t) => g.HasSoulPatch) .Distinct()); } @@ -3087,16 +2751,8 @@ public virtual Task Count_with_unflattened_groupjoin_is_evaluated_on_client(bool ss => ss.Set() .GroupJoin( ss.Set(), - g => new - { - k1 = g.Nickname, - k2 = (int?)g.SquadId - }, - t => new - { - k1 = t.GearNickName, - k2 = t.GearSquadId - }, + g => new { k1 = g.Nickname, k2 = (int?)g.SquadId }, + t => new { k1 = t.GearNickName, k2 = t.GearSquadId }, (g, t) => g)); } @@ -3143,16 +2799,8 @@ public virtual Task Non_flattened_GroupJoin_with_result_operator_evaluates_on_th isAsync, ss => ss.Set().GroupJoin( ss.Set(), - t => new - { - k1 = t.GearNickName, - k2 = t.GearSquadId - }, - g => new - { - k1 = g.Nickname, - k2 = (int?)g.SquadId - }, + t => new { k1 = t.GearNickName, k2 = t.GearSquadId }, + g => new { k1 = g.Nickname, k2 = (int?)g.SquadId }, (k, r) => r.Count())); } @@ -3164,8 +2812,8 @@ public virtual Task Client_side_equality_with_parameter_works_with_optional_navi return AssertTranslationFailed( () => AssertQuery( - isAsync, - ss => ss.Set().Where(g => ClientEquals(g.Tag.Note, prm)))); + isAsync, + ss => ss.Set().Where(g => ClientEquals(g.Tag.Note, prm)))); } private static bool ClientEquals(string first, string second) @@ -3200,19 +2848,13 @@ public virtual Task Unnecessary_include_doesnt_get_added_complex_when_projecting .Include(g => g.Tag) .Where(g => g.HasSoulPatch) .Select( - g => new - { - FullName = EF.Property(g, "FullName") - }), + g => new { FullName = EF.Property(g, "FullName") }), ss => ss.Set() .OrderBy(g => g.Rank) .Include(g => g.Tag) .Where(g => g.HasSoulPatch) .Select( - g => new - { - g.FullName - }), + g => new { g.FullName }), assertOrder: true); } @@ -3273,11 +2915,7 @@ public virtual Task Subquery_is_lifted_from_main_from_clause_of_SelectMany(bool from g2 in ss.Set() orderby g1.FullName where g1.HasSoulPatch && !g2.HasSoulPatch - select new - { - Name1 = g1.FullName, - Name2 = g2.FullName - }); + select new { Name1 = g1.FullName, Name2 = g2.FullName }); } [ConditionalTheory] @@ -3373,11 +3011,7 @@ from g1 in ss.Set() from g2 in ss.Set().OrderBy(g => g.Rank).Include(g => g.Tag) orderby g1.FullName where g1.HasSoulPatch && !g2.HasSoulPatch - select new - { - Name1 = g1.FullName, - Name2 = g2.FullName - }, + select new { Name1 = g1.FullName, Name2 = g2.FullName }, elementSorter: e => (e.Name1, e.Name2)); } @@ -3449,11 +3083,7 @@ public virtual Task Select_length_of_string_property(bool isAsync) return AssertQuery( isAsync, ss => from w in ss.Set() - select new - { - w.Name, - w.Name.Length - }, + select new { w.Name, w.Name.Length }, elementSorter: e => e.Name); } @@ -3463,10 +3093,10 @@ public virtual Task Client_method_on_collection_navigation_in_predicate(bool isA { return AssertTranslationFailed( () => AssertQuery( - isAsync, - ss => from g in ss.Set() - where g.HasSoulPatch && FavoriteWeapon(g.Weapons).Name == "Marcus' Lancer" - select g.Nickname)); + isAsync, + ss => from g in ss.Set() + where g.HasSoulPatch && FavoriteWeapon(g.Weapons).Name == "Marcus' Lancer" + select g.Nickname)); } [ConditionalTheory] @@ -3475,13 +3105,13 @@ public virtual Task Client_method_on_collection_navigation_in_predicate_accessed { return AssertTranslationFailed( () => AssertQuery( - isAsync, - ss => from g in ss.Set() - where !g.HasSoulPatch && FavoriteWeapon(EF.Property>(g, "Weapons")).Name == "Cole's Gnasher" - select g.Nickname, - ss => from g in ss.Set() - where !g.HasSoulPatch && FavoriteWeapon(g.Weapons).Name == "Cole's Gnasher" - select g.Nickname)); + isAsync, + ss => from g in ss.Set() + where !g.HasSoulPatch && FavoriteWeapon(EF.Property>(g, "Weapons")).Name == "Cole's Gnasher" + select g.Nickname, + ss => from g in ss.Set() + where !g.HasSoulPatch && FavoriteWeapon(g.Weapons).Name == "Cole's Gnasher" + select g.Nickname)); } [ConditionalTheory] @@ -3490,12 +3120,12 @@ public virtual Task Client_method_on_collection_navigation_in_order_by(bool isAs { return AssertTranslationFailed( () => AssertQuery( - isAsync, - ss => from g in ss.Set() - where !g.HasSoulPatch - orderby FavoriteWeapon(g.Weapons).Name descending - select g.Nickname, - assertOrder: true)); + isAsync, + ss => from g in ss.Set() + where !g.HasSoulPatch + orderby FavoriteWeapon(g.Weapons).Name descending + select g.Nickname, + assertOrder: true)); } [ConditionalTheory] @@ -3507,11 +3137,7 @@ public virtual async Task Client_method_on_collection_navigation_in_additional_f isAsync, ss => from g in ss.Set().OfType() from v in Veterans(g.Reports) - select new - { - g = g.Nickname, - v = v.Nickname - }, + select new { g = g.Nickname, v = v.Nickname }, elementSorter: e => e.g + e.v))).Message; Assert.StartsWith( @@ -3525,16 +3151,12 @@ public virtual async Task Client_method_on_collection_navigation_in_outer_join_k { var message = (await Assert.ThrowsAsync( () => AssertQuery( - isAsync, - ss => from o in ss.Set().OfType() - join g in ss.Set() on FavoriteWeapon(o.Weapons).Name equals FavoriteWeapon(g.Weapons).Name - where o.HasSoulPatch - select new - { - o = o.Nickname, - g = g.Nickname - }, - elementSorter: e => e.o + e.g))).Message; + isAsync, + ss => from o in ss.Set().OfType() + join g in ss.Set() on FavoriteWeapon(o.Weapons).Name equals FavoriteWeapon(g.Weapons).Name + where o.HasSoulPatch + select new { o = o.Nickname, g = g.Nickname }, + elementSorter: e => e.o + e.g))).Message; } private static Weapon FavoriteWeapon(IEnumerable weapons) @@ -3556,11 +3178,7 @@ public virtual Task Member_access_on_derived_entity_using_cast(bool isAsync) ss => from f in ss.Set() where f is LocustHorde orderby ((LocustHorde)f).Name - select new - { - ((LocustHorde)f).Name, - ((LocustHorde)f).Eradicated - }, + select new { ((LocustHorde)f).Name, ((LocustHorde)f).Eradicated }, assertOrder: true); } @@ -3573,11 +3191,7 @@ public virtual Task Member_access_on_derived_materialized_entity_using_cast(bool ss => from f in ss.Set() where f is LocustHorde orderby f.Name - select new - { - f, - ((LocustHorde)f).Eradicated - }, + select new { f, ((LocustHorde)f).Eradicated }, assertOrder: true, elementAsserter: (e, a) => { @@ -3596,11 +3210,7 @@ public virtual Task Member_access_on_derived_entity_using_cast_and_let(bool isAs where f is LocustHorde let horde = (LocustHorde)f orderby horde.Name - select new - { - horde.Name, - horde.Eradicated - }, + select new { horde.Name, horde.Eradicated }, assertOrder: true); } @@ -3616,18 +3226,13 @@ where f is LocustHorde orderby f.Name select new { - Name = EF.Property(horde, "Name"), - Eradicated = EF.Property((LocustHorde)f, "Eradicated") + Name = EF.Property(horde, "Name"), Eradicated = EF.Property((LocustHorde)f, "Eradicated") }, ss => from f in ss.Set() where f is LocustHorde let horde = (LocustHorde)f orderby f.Name - select new - { - horde.Name, - Eradicated = (bool)((LocustHorde)f).Eradicated - }, + select new { horde.Name, Eradicated = (bool)((LocustHorde)f).Eradicated }, assertOrder: true); } @@ -3640,11 +3245,7 @@ public virtual Task Navigation_access_on_derived_entity_using_cast(bool isAsync) ss => from f in ss.Set() where f is LocustHorde orderby f.Name - select new - { - f.Name, - Threat = ((LocustHorde)f).Commander.ThreatLevel - }, + select new { f.Name, Threat = ((LocustHorde)f).Commander.ThreatLevel }, assertOrder: true); } @@ -3657,19 +3258,13 @@ public virtual Task Navigation_access_on_derived_materialized_entity_using_cast( ss => from f in ss.Set() where f is LocustHorde orderby f.Name - select new - { - f, - f.Name, - Threat = ((LocustHorde)f).Commander.ThreatLevel - }, + select new { f, f.Name, Threat = ((LocustHorde)f).Commander.ThreatLevel }, assertOrder: true, elementAsserter: (e, a) => { AssertEqual(e.f, a.f); Assert.Equal(e.Name, a.Name); Assert.Equal(e.Threat, a.Threat); - }); } @@ -3682,19 +3277,11 @@ public virtual Task Navigation_access_via_EFProperty_on_derived_entity_using_cas ss => from f in ss.Set() where f is LocustHorde orderby f.Name - select new - { - f.Name, - Threat = EF.Property((LocustHorde)f, "Commander").ThreatLevel - }, + select new { f.Name, Threat = EF.Property((LocustHorde)f, "Commander").ThreatLevel }, ss => from f in ss.Set() where f is LocustHorde orderby f.Name - select new - { - f.Name, - Threat = ((LocustHorde)f).Commander.ThreatLevel - }, + select new { f.Name, Threat = ((LocustHorde)f).Commander.ThreatLevel }, assertOrder: true); } @@ -3707,11 +3294,7 @@ public virtual Task Navigation_access_fk_on_derived_entity_using_cast(bool isAsy ss => from f in ss.Set() where f is LocustHorde orderby f.Name - select new - { - f.Name, - CommanderName = ((LocustHorde)f).Commander.Name - }, + select new { f.Name, CommanderName = ((LocustHorde)f).Commander.Name }, assertOrder: true); } @@ -3724,11 +3307,7 @@ public virtual Task Collection_navigation_access_on_derived_entity_using_cast(bo ss => from f in ss.Set() where f is LocustHorde orderby f.Name - select new - { - f.Name, - LeadersCount = ((LocustHorde)f).Leaders.Count - }, + select new { f.Name, LeadersCount = ((LocustHorde)f).Leaders.Count }, assertOrder: true); } @@ -3741,11 +3320,7 @@ public virtual Task Collection_navigation_access_on_derived_entity_using_cast_in ss => from f in ss.Set().Where(f => f is LocustHorde) from l in ((LocustHorde)f).Leaders orderby l.Name - select new - { - f.Name, - LeaderName = l.Name - }, + select new { f.Name, LeaderName = l.Name }, elementSorter: e => (e.Name, e.LeaderName)); } @@ -3770,12 +3345,9 @@ orderby lh.Name [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task Include_on_derived_entity_with_cast(bool isAsync) - { - var expectedIncludes = new List - { - new ExpectedInclude(e => e.Capital, "Capital"), - }; + public virtual Task Include_on_derived_entity_with_cast(bool isAsync) + { + var expectedIncludes = new List { new ExpectedInclude(e => e.Capital, "Capital") }; // TODO: should we disable this scenario? see #14671 return AssertIncludeQuery( @@ -3817,14 +3389,10 @@ public virtual Task Comparing_two_collection_navigations_composite_key(bool isAs isAsync, ss => from g1 in ss.Set() from g2 in ss.Set() - // ReSharper disable once PossibleUnintendedReferenceComparison + // ReSharper disable once PossibleUnintendedReferenceComparison where g1.Weapons == g2.Weapons orderby g1.Nickname - select new - { - Nickname1 = g1.Nickname, - Nickname2 = g2.Nickname - }, + select new { Nickname1 = g1.Nickname, Nickname2 = g2.Nickname }, elementSorter: e => (e.Nickname1, e.Nickname2)); } @@ -3839,22 +3407,14 @@ from o in ss.Set().OfType() where f is LocustHorde && o.HasSoulPatch // ReSharper disable once PossibleUnintendedReferenceComparison where ((LocustHorde)f).Commander.DefeatedBy.Weapons == o.Weapons - select new - { - f.Name, - o.Nickname - }, + select new { f.Name, o.Nickname }, ss => from f in ss.Set() from o in ss.Set().OfType() where f is LocustHorde && o.HasSoulPatch where Maybe( - ((LocustHorde)f).Commander, - () => ((LocustHorde)f).Commander.DefeatedBy) == o - select new - { - f.Name, - o.Nickname - }, + ((LocustHorde)f).Commander, + () => ((LocustHorde)f).Commander.DefeatedBy) == o + select new { f.Name, o.Nickname }, elementSorter: e => (e.Name, e.Nickname)); } @@ -3862,16 +3422,13 @@ where Maybe( [MemberData(nameof(IsAsyncData))] public virtual Task Comparing_entities_using_Equals_inheritance(bool isAsync) { - return AssertQuery(isAsync, + return AssertQuery( + isAsync, ss => from g in ss.Set() from o in ss.Set().OfType() where g.Equals(o) orderby g.Nickname, o.Nickname - select new - { - Nickname1 = g.Nickname, - Nickname2 = o.Nickname - }, + select new { Nickname1 = g.Nickname, Nickname2 = o.Nickname }, assertOrder: true); } @@ -3932,18 +3489,10 @@ public virtual Task Project_collection_navigation_with_inheritance1(bool isAsync isAsync, ss => ss.Set().OfType() .Select( - h => new - { - h.Id, - Leaders = EF.Property>(h.Commander.CommandingFaction, "Leaders") - }), + h => new { h.Id, Leaders = EF.Property>(h.Commander.CommandingFaction, "Leaders") }), ss => ss.Set().OfType() .Select( - h => new - { - h.Id, - Leaders = (ICollection)h.Commander.CommandingFaction.Leaders - }), + h => new { h.Id, Leaders = (ICollection)h.Commander.CommandingFaction.Leaders }), elementSorter: e => e.Id, elementAsserter: (e, a) => { @@ -3960,21 +3509,17 @@ public virtual Task Project_collection_navigation_with_inheritance2(bool isAsync isAsync, ss => ss.Set().OfType() .Select( - h => new - { - h.Id, - Gears = EF.Property>((Officer)h.Commander.DefeatedBy, "Reports") - }), + h => new { h.Id, Gears = EF.Property>((Officer)h.Commander.DefeatedBy, "Reports") }), ss => ss.Set().OfType() .Select( h => new { h.Id, Gears = Maybe( - h.Commander, - () => Maybe( - h.Commander.DefeatedBy, - () => ((Officer)h.Commander.DefeatedBy).Reports)) ?? new List() + h.Commander, + () => Maybe( + h.Commander.DefeatedBy, + () => ((Officer)h.Commander.DefeatedBy).Reports)) ?? new List() }), elementSorter: e => e.Id, elementAsserter: (e, a) => @@ -3995,8 +3540,7 @@ public virtual Task Project_collection_navigation_with_inheritance3(bool isAsync .Select( f => new { - f.Id, - Gears = EF.Property>((Officer)((LocustHorde)f).Commander.DefeatedBy, "Reports") + f.Id, Gears = EF.Property>((Officer)((LocustHorde)f).Commander.DefeatedBy, "Reports") }), ss => ss.Set() .Where(f => f is LocustHorde) @@ -4005,10 +3549,10 @@ public virtual Task Project_collection_navigation_with_inheritance3(bool isAsync { f.Id, Gears = Maybe( - ((LocustHorde)f).Commander, - () => Maybe( - ((LocustHorde)f).Commander.DefeatedBy, - () => ((Officer)((LocustHorde)f).Commander.DefeatedBy).Reports)) ?? new List() + ((LocustHorde)f).Commander, + () => Maybe( + ((LocustHorde)f).Commander.DefeatedBy, + () => ((Officer)((LocustHorde)f).Commander.DefeatedBy).Reports)) ?? new List() }), elementSorter: e => e.Id, elementAsserter: (e, a) => @@ -4025,10 +3569,7 @@ public virtual Task Include_reference_on_derived_type_using_string(bool isAsync) return AssertIncludeQuery( isAsync, ss => ss.Set().Include("DefeatedBy"), - new List - { - new ExpectedInclude(lc => lc.DefeatedBy, "DefeatedBy") - }); + new List { new ExpectedInclude(lc => lc.DefeatedBy, "DefeatedBy") }); } [ConditionalTheory] @@ -4071,10 +3612,7 @@ public virtual Task Include_reference_on_derived_type_using_lambda(bool isAsync) return AssertIncludeQuery( isAsync, ss => ss.Set().Include(ll => ((LocustCommander)ll).DefeatedBy), - new List - { - new ExpectedInclude(lc => lc.DefeatedBy, "DefeatedBy") - }); + new List { new ExpectedInclude(lc => lc.DefeatedBy, "DefeatedBy") }); } [ConditionalTheory] @@ -4084,10 +3622,7 @@ public virtual Task Include_reference_on_derived_type_using_lambda_with_soft_cas return AssertIncludeQuery( isAsync, ss => ss.Set().Include(ll => (ll as LocustCommander).DefeatedBy), - new List - { - new ExpectedInclude(lc => lc.DefeatedBy, "DefeatedBy") - }); + new List { new ExpectedInclude(lc => lc.DefeatedBy, "DefeatedBy") }); } [ConditionalTheory] @@ -4097,10 +3632,7 @@ public virtual Task Include_reference_on_derived_type_using_lambda_with_tracking return AssertIncludeQuery( isAsync, ss => ss.Set().AsTracking().Include(ll => ((LocustCommander)ll).DefeatedBy), - new List - { - new ExpectedInclude(lc => lc.DefeatedBy, "DefeatedBy") - }, + new List { new ExpectedInclude(lc => lc.DefeatedBy, "DefeatedBy") }, entryCount: 7); } @@ -4111,10 +3643,7 @@ public virtual Task Include_collection_on_derived_type_using_string(bool isAsync return AssertIncludeQuery( isAsync, ss => ss.Set().Include("Reports"), - new List - { - new ExpectedInclude(o => o.Reports, "Reports") - }); + new List { new ExpectedInclude(o => o.Reports, "Reports") }); } [ConditionalTheory] @@ -4124,10 +3653,7 @@ public virtual Task Include_collection_on_derived_type_using_lambda(bool isAsync return AssertIncludeQuery( isAsync, ss => ss.Set().Include(g => ((Officer)g).Reports), - new List - { - new ExpectedInclude(o => o.Reports, "Reports") - }); + new List { new ExpectedInclude(o => o.Reports, "Reports") }); } [ConditionalTheory] @@ -4137,10 +3663,7 @@ public virtual Task Include_collection_on_derived_type_using_lambda_with_soft_ca return AssertIncludeQuery( isAsync, ss => ss.Set().Include(g => (g as Officer).Reports), - new List - { - new ExpectedInclude(o => o.Reports, "Reports") - }); + new List { new ExpectedInclude(o => o.Reports, "Reports") }); } [ConditionalTheory] @@ -4149,8 +3672,7 @@ public virtual Task Include_base_navigation_on_derived_entity(bool isAsync) { var expectedIncludes = new List { - new ExpectedInclude(e => e.Tag, "Tag"), - new ExpectedInclude(e => e.Weapons, "Weapons") + new ExpectedInclude(e => e.Tag, "Tag"), new ExpectedInclude(e => e.Weapons, "Weapons") }; return AssertIncludeQuery( @@ -4165,8 +3687,7 @@ public virtual Task ThenInclude_collection_on_derived_after_base_reference(bool { var expectedIncludes = new List { - new ExpectedInclude(e => e.Gear, "Gear"), - new ExpectedInclude(e => e.Weapons, "Weapons", "Gear") + new ExpectedInclude(e => e.Gear, "Gear"), new ExpectedInclude(e => e.Weapons, "Weapons", "Gear") }; return AssertIncludeQuery( @@ -4264,8 +3785,8 @@ public virtual async Task Include_collection_and_invalid_navigation_using_string { var message = (await Assert.ThrowsAsync( () => AssertQuery( - isAsync, - ss => ss.Set().Include("Reports.Foo")))).Message; + isAsync, + ss => ss.Set().Include("Reports.Foo")))).Message; Assert.Equal( CoreStrings.IncludeBadNavigation("Foo", "Gear"), @@ -4281,10 +3802,7 @@ public virtual Task Projecting_nullable_bool_in_conditional_works(bool isAsync) ss => ss.Set().Select( cg => - new - { - Prop = cg.Gear != null ? cg.Gear.HasSoulPatch : false - }), + new { Prop = cg.Gear != null ? cg.Gear.HasSoulPatch : false }), e => e.Prop); } @@ -4420,11 +3938,7 @@ from o in ss.Set().OfType() o.Nickname, Collection = (from r in o.Reports where !r.HasSoulPatch - select new - { - r.Nickname, - r.FullName - }).ToArray() + select new { r.Nickname, r.FullName }).ToArray() }, elementSorter: e => e.Nickname, elementAsserter: (e, a) => @@ -4516,11 +4030,7 @@ where s.Id < 20 { s.Name, Collection = (from m in s.Members - select new - { - m.FullName, - m.Rank - }).ToList() + select new { m.FullName, m.Rank }).ToList() }, elementSorter: e => e.Name, elementAsserter: (e, a) => @@ -4691,17 +4201,9 @@ orderby o.FullName { o.Nickname, First = o.Weapons.Where(w => w.IsAutomatic).Select( - w => new - { - w.Name, - w.IsAutomatic - }).ToArray(), + w => new { w.Name, w.IsAutomatic }).ToArray(), Second = o.Reports.OrderBy(r => r.FullName).Select( - r => new - { - r.Nickname, - r.Rank - }).ToList() + r => new { r.Nickname, r.Rank }).ToList() }, assertOrder: true, elementAsserter: (e, a) => @@ -4753,7 +4255,8 @@ where o.Reports.Any() [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys_inside_subquery_duplicated_orderings(bool isAsync) + public virtual Task Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys_inside_subquery_duplicated_orderings( + bool isAsync) { return AssertQuery( isAsync, @@ -4779,7 +4282,8 @@ where o.Reports.Any() [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys_inside_subquery_complex_orderings(bool isAsync) + public virtual Task Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys_inside_subquery_complex_orderings( + bool isAsync) { return AssertQuery( isAsync, @@ -4828,17 +4332,9 @@ orderby w.IsAutomatic { w.Id, InnerFirst = w.Owner.Weapons.Select( - ww => new - { - ww.Name, - ww.IsAutomatic - }).ToList(), + ww => new { ww.Name, ww.IsAutomatic }).ToList(), InnerSecond = w.Owner.Squad.Members.OrderBy(mm => mm.Nickname).Select( - mm => new - { - mm.Nickname, - mm.HasSoulPatch - }).ToList() + mm => new { mm.Nickname, mm.HasSoulPatch }).ToList() }).ToList() }).ToList(), OuterCollection2 = (from www in o.Tag.Gear.Weapons @@ -4889,11 +4385,7 @@ from o in ss.Set().OfType() { o.FullName, Collection = from r in o.Reports - select new - { - ReportName = r.FullName, - OfficerName = o.FullName - } + select new { ReportName = r.FullName, OfficerName = o.FullName } }, elementSorter: e => e.FullName, elementAsserter: (e, a) => @@ -4916,10 +4408,7 @@ from o in ss.Set().OfType() o.FullName, Collection = from r in o.Reports where o.FullName != "Foo" - select new - { - ReportName = r.FullName - } + select new { ReportName = r.FullName } }, elementSorter: e => e.FullName, elementAsserter: (e, a) => @@ -4947,11 +4436,7 @@ from o in ss.Set().OfType() r.FullName, InnerCollection = (from w in r.Weapons where w.Name != "Bar" - select new - { - w.Name, - r.Nickname - }).ToList() + select new { w.Name, r.Nickname }).ToList() }).ToList() }, elementSorter: e => e.FullName, @@ -4988,11 +4473,7 @@ from o in ss.Set().OfType() r.FullName, InnerCollection = from w in r.Weapons where w.Name != "Bar" - select new - { - w.Name, - o.Nickname - } + select new { w.Name, o.Nickname } } }, elementSorter: e => e.FullName, @@ -5083,7 +4564,8 @@ public virtual Task Correlated_collections_with_FirstOrDefault(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().OrderBy(s => s.Name).Select(s => s.Members.OrderBy(m => m.Nickname).Select(m => m.FullName).FirstOrDefault()), + ss => ss.Set().OrderBy(s => s.Name) + .Select(s => s.Members.OrderBy(m => m.Nickname).Select(m => m.FullName).FirstOrDefault()), assertOrder: true); } @@ -5098,11 +4580,7 @@ from t in ss.Set() join g in ss.Set() on t.GearNickName equals g.Nickname into grouping from g in grouping.DefaultIfEmpty() where !g.HasSoulPatch - select new - { - g.Nickname, - WeaponNames = g.Weapons.Select(w => w.Name).ToList() - }, + select new { g.Nickname, WeaponNames = g.Weapons.Select(w => w.Name).ToList() }, ss => from t in ss.Set() join g in ss.Set() on t.GearNickName equals g.Nickname into grouping @@ -5153,20 +4631,12 @@ public virtual Task Correlated_collections_left_join_with_self_reference(bool is from t in ss.Set() join o in ss.Set().OfType() on t.GearNickName equals o.Nickname into grouping from o in grouping.DefaultIfEmpty() - select new - { - t.Note, - ReportNames = o.Reports.Select(r => r.FullName).ToList() - }, + select new { t.Note, ReportNames = o.Reports.Select(r => r.FullName).ToList() }, ss => from t in ss.Set() join o in ss.Set().OfType() on t.GearNickName equals o.Nickname into grouping from o in grouping.DefaultIfEmpty() - select new - { - t.Note, - ReportNames = o != null ? o.Reports.Select(r => r.FullName).ToList() : new List() - }, + select new { t.Note, ReportNames = o != null ? o.Reports.Select(r => r.FullName).ToList() : new List() }, elementSorter: e => e.Note, elementAsserter: (e, a) => { @@ -5187,11 +4657,7 @@ join g in ss.Set() on t.GearNickName equals g.Nickname into grouping from g in grouping.DefaultIfEmpty() orderby t.Note, g.Nickname descending select g.Squad.Members.Where(m => m.HasSoulPatch).Select( - m => new - { - m.Nickname, - AutomaticWeapons = m.Weapons.Where(w => w.IsAutomatic).ToList() - }).ToList(), + m => new { m.Nickname, AutomaticWeapons = m.Weapons.Where(w => w.IsAutomatic).ToList() }).ToList(), ss => from t in ss.Set() join g in ss.Set() on t.GearNickName equals g.Nickname into grouping @@ -5199,17 +4665,10 @@ from g in grouping.DefaultIfEmpty() orderby t.Note, Maybe(g, () => g.Nickname) descending select g != null - ? g.Squad.Members.Where(m => m.HasSoulPatch).OrderBy(m => m.Nickname) - .Select(m => new - { - m.Nickname, - AutomaticWeapons = m.Weapons.Where(w => w.IsAutomatic).ToList() - }).ToList() - : Enumerable.Empty().Select(x => new - { - Nickname = (string)null, - AutomaticWeapons = new List() - }).ToList(), + ? g.Squad.Members.Where(m => m.HasSoulPatch).OrderBy(m => m.Nickname) + .Select(m => new { m.Nickname, AutomaticWeapons = m.Weapons.Where(w => w.IsAutomatic).ToList() }).ToList() + : Enumerable.Empty().Select(x => new { Nickname = (string)null, AutomaticWeapons = new List() }) + .ToList(), assertOrder: true, elementAsserter: (e, a) => AssertCollection( e, @@ -5230,26 +4689,15 @@ public virtual Task Correlated_collections_from_left_join_with_additional_elemen isAsync, ss => ss.Set().OrderBy(w => w.Name).Select( w => w.Owner.Squad.Members.OrderByDescending(m => m.FullName).Select( - m => new - { - Weapons = m.Weapons.Where(ww => !ww.IsAutomatic).OrderBy(ww => ww.Id).ToList(), - m.Rank - }).ToList()), + m => new { Weapons = m.Weapons.Where(ww => !ww.IsAutomatic).OrderBy(ww => ww.Id).ToList(), m.Rank }).ToList()), ss => ss.Set().OrderBy(w => w.Name).Select( w => w.Owner != null ? w.Owner.Squad.Members.OrderByDescending(m => m.FullName).Select( - m => new - { - Weapons = m.Weapons.Where(ww => !ww.IsAutomatic).OrderBy(ww => ww.Id).ToList(), - m.Rank - }).ToList() - : Enumerable.Empty().Select(x => new - { - Weapons = new List(), - Rank = default(MilitaryRank) - })), + m => new { Weapons = m.Weapons.Where(ww => !ww.IsAutomatic).OrderBy(ww => ww.Id).ToList(), m.Rank }).ToList() + : Enumerable.Empty().Select(x => new { Weapons = new List(), Rank = default(MilitaryRank) })), assertOrder: true, - elementAsserter: (e, a) => AssertCollection(e, a, ordered: true, elementAsserter: (ee, aa) => + elementAsserter: (e, a) => AssertCollection( + e, a, ordered: true, elementAsserter: (ee, aa) => { Assert.Equal(ee.Rank, aa.Rank); AssertCollection(ee.Weapons, aa.Weapons, ordered: true); @@ -5272,11 +4720,7 @@ from r in ss.Set() { w.Id, InnerCollection = w.Owner.Squad.Members.OrderBy(mm => mm.Nickname).Select( - mm => new - { - mm.Nickname, - mm.HasSoulPatch - }).ToList() + mm => new { mm.Nickname, mm.HasSoulPatch }).ToList() }).ToList() }, elementSorter: e => e.FullName, @@ -5315,11 +4759,7 @@ from o in ss.Set().OfType() { w.Id, InnerSecond = w.Owner.Squad.Members.OrderBy(mm => mm.Nickname).Select( - mm => new - { - mm.Nickname, - mm.HasSoulPatch - }).ToList() + mm => new { mm.Nickname, mm.HasSoulPatch }).ToList() }).ToList() }).ToList() }, @@ -5364,11 +4804,7 @@ from r in ss.Set() { w.Id, InnerCollection = w.Owner.Squad.Members.OrderBy(mm => mm.Nickname).Select( - mm => new - { - mm.Nickname, - mm.HasSoulPatch - }).ToList() + mm => new { mm.Nickname, mm.HasSoulPatch }).ToList() }).ToList() }, assertOrder: true, @@ -5411,11 +4847,7 @@ from o in ss.Set().OfType() { w.Id, InnerSecond = w.Owner.Squad.Members.OrderBy(mm => mm.Nickname).Select( - mm => new - { - mm.Nickname, - mm.HasSoulPatch - }).ToList() + mm => new { mm.Nickname, mm.HasSoulPatch }).ToList() }).ToList() }).ToList() }, @@ -5488,18 +4920,10 @@ public virtual void Include_with_group_by_and_last() using (var ctx = CreateContext()) { var actual = ctx.Gears.OrderByDescending(g => g.HasSoulPatch).Include(g => g.Weapons).Select( - g => new - { - g.Rank, - g - }).GroupBy(g => g.Rank).ToList().OrderBy(g => g.Key).ToList(); + g => new { g.Rank, g }).GroupBy(g => g.Rank).ToList().OrderBy(g => g.Key).ToList(); var expected = Fixture.QueryAsserter.ExpectedData.Set().OrderByDescending(g => g.HasSoulPatch).Include(g => g.Weapons) .Select( - g => new - { - g.Rank, - g - }).GroupBy(g => g.Rank).ToList().OrderBy(g => g.Key).ToList(); + g => new { g.Rank, g }).GroupBy(g => g.Rank).ToList().OrderBy(g => g.Key).ToList(); Assert.Equal(expected.Count, actual.Count); @@ -5534,17 +4958,9 @@ public virtual void Include_with_group_by_with_composite_group_key() using (var ctx = CreateContext()) { var actual = ctx.Gears.OrderBy(g => g.Nickname).Include(g => g.Weapons).GroupBy( - g => new - { - g.Rank, - g.HasSoulPatch - }).ToList().OrderBy(g => g.Key.Rank).ThenBy(g => g.Key.HasSoulPatch).ToList(); + g => new { g.Rank, g.HasSoulPatch }).ToList().OrderBy(g => g.Key.Rank).ThenBy(g => g.Key.HasSoulPatch).ToList(); var expected = Fixture.QueryAsserter.ExpectedData.Set().OrderBy(g => g.Nickname).Include(g => g.Weapons).GroupBy( - g => new - { - g.Rank, - g.HasSoulPatch - }).ToList().OrderBy(g => g.Key.Rank).ThenBy(g => g.Key.HasSoulPatch).ToList(); + g => new { g.Rank, g.HasSoulPatch }).ToList().OrderBy(g => g.Key.Rank).ThenBy(g => g.Key.HasSoulPatch).ToList(); Assert.Equal(expected.Count, actual.Count); @@ -5631,13 +5047,15 @@ public virtual Task Null_semantics_on_nullable_bool_from_left_join_subquery_is_f isAsync, ss => from ll in ss.Set() - join h in ss.Set().OfType().Where(f => f.Name == "Swarm") on ll.Name equals h.CommanderName into grouping + join h in ss.Set().OfType().Where(f => f.Name == "Swarm") on ll.Name equals h.CommanderName into + grouping from h in grouping.DefaultIfEmpty() where h.Eradicated != true select h, ss => from ll in ss.Set() - join h in ss.Set().OfType().Where(f => f.Name == "Swarm") on ll.Name equals h.CommanderName into grouping + join h in ss.Set().OfType().Where(f => f.Name == "Swarm") on ll.Name equals h.CommanderName into + grouping from h in grouping.DefaultIfEmpty() where MaybeScalar(h, () => h.Eradicated) != true select h); @@ -5665,7 +5083,7 @@ public virtual Task Include_on_derived_type_with_order_by_and_paging(bool isAsyn new ExpectedInclude(e => e.Weapons, "Weapons", "DefeatedBy") }; - return AssertIncludeQuery( + return AssertIncludeQuery( isAsync, ss => ss.Set().Include(ll => ((LocustCommander)ll).DefeatedBy).ThenInclude(g => g.Weapons) .OrderBy(ll => ((LocustCommander)ll).DefeatedBy.Tag.Note).Take(10), @@ -5690,7 +5108,7 @@ public virtual Task Select_required_navigation_on_the_same_type_with_cast(bool i { return AssertQuery( isAsync, - ss => ss.Set().Select(g => ((Gear)g).CityOfBirth.Name), + ss => ss.Set().Select(g => g.CityOfBirth.Name), ss => ss.Set().Select(g => g.CityOfBirth.Name)); } @@ -5787,15 +5205,14 @@ public virtual async Task Include_with_concat(bool isAsync) { var expectedIncludes = new List { - new ExpectedInclude(g => g.Squad, "Squad"), - new ExpectedInclude(o => o.Squad, "Squad") + new ExpectedInclude(g => g.Squad, "Squad"), new ExpectedInclude(o => o.Squad, "Squad") }; var message = (await Assert.ThrowsAsync( () => AssertIncludeQuery( - isAsync, - ss => ss.Set().Include(g => g.Squad).Concat(ss.Set()), - expectedIncludes))).Message; + isAsync, + ss => ss.Set().Include(g => g.Squad).Concat(ss.Set()), + expectedIncludes))).Message; Assert.Equal( "When performing a set operation, both operands must have the same Include operations.", @@ -5809,10 +5226,7 @@ public virtual Task Negated_bool_ternary_inside_anonymous_type_in_projection(boo return AssertQuery( isAsync, ss => ss.Set().Select( - t => new - { - c = !(t.Gear.HasSoulPatch ? true : ((bool?)t.Gear.HasSoulPatch ?? true)) - }), + t => new { c = !(t.Gear.HasSoulPatch ? true : ((bool?)t.Gear.HasSoulPatch ?? true)) }), ss => ss.Set().Select( t => new { @@ -5841,7 +5255,8 @@ public virtual Task Order_by_entity_qsre_with_inheritance(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().OfType().OrderBy(lc => lc.HighCommand).ThenBy(lc => lc.Name).Select(lc => lc.Name), + ss => ss.Set().OfType().OrderBy(lc => lc.HighCommand).ThenBy(lc => lc.Name) + .Select(lc => lc.Name), assertOrder: true); } @@ -5852,7 +5267,8 @@ public virtual Task Order_by_entity_qsre_composite_key(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().OrderBy(w => w.Owner).ThenBy(w => w.Id).Select(w => w.Name), - ss => ss.Set().OrderBy(w => Maybe(w.Owner, () => w.Owner.Nickname)).ThenBy(w => MaybeScalar(w.Owner, () => w.Owner.SquadId)) + ss => ss.Set().OrderBy(w => Maybe(w.Owner, () => w.Owner.Nickname)) + .ThenBy(w => MaybeScalar(w.Owner, () => w.Owner.SquadId)) .ThenBy(w => w.Id).Select(w => w.Name), assertOrder: true); } @@ -5863,7 +5279,8 @@ public virtual Task Order_by_entity_qsre_with_other_orderbys(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().OrderBy(w => w.IsAutomatic).ThenByDescending(w => w.Owner).ThenBy(w => w.SynergyWith).ThenBy(w => w.Name), + ss => ss.Set().OrderBy(w => w.IsAutomatic).ThenByDescending(w => w.Owner).ThenBy(w => w.SynergyWith) + .ThenBy(w => w.Name), ss => ss.Set() .OrderBy(w => w.IsAutomatic) .ThenByDescending(w => Maybe(w.Owner, () => w.Owner.Nickname)) @@ -5881,11 +5298,7 @@ public virtual Task Join_on_entity_qsre_keys(bool isAsync) isAsync, ss => from w1 in ss.Set() join w2 in ss.Set() on w1 equals w2 - select new - { - Name1 = w1.Name, - Name2 = w2.Name - }, + select new { Name1 = w1.Name, Name2 = w2.Name }, elementSorter: e => e.Name1 + " " + e.Name2); } @@ -5897,11 +5310,7 @@ public virtual Task Join_on_entity_qsre_keys_composite_key(bool isAsync) isAsync, ss => from g1 in ss.Set() join g2 in ss.Set() on g1 equals g2 - select new - { - GearName1 = g1.FullName, - GearName2 = g2.FullName - }, + select new { GearName1 = g1.FullName, GearName2 = g2.FullName }, elementSorter: e => (e.GearName1, e.GearName2)); } @@ -5913,11 +5322,7 @@ public virtual Task Join_on_entity_qsre_keys_inheritance(bool isAsync) isAsync, ss => from g in ss.Set() join o in ss.Set().OfType() on g equals o - select new - { - GearName = g.FullName, - OfficerName = o.FullName - }, + select new { GearName = g.FullName, OfficerName = o.FullName }, elementSorter: e => (e.GearName, e.OfficerName)); } @@ -5929,11 +5334,7 @@ public virtual Task Join_on_entity_qsre_keys_outer_key_is_navigation(bool isAsyn isAsync, ss => from w1 in ss.Set() join w2 in ss.Set() on w1.SynergyWith equals w2 - select new - { - Name1 = w1.Name, - Name2 = w2.Name - }, + select new { Name1 = w1.Name, Name2 = w2.Name }, elementSorter: e => (e.Name1, e.Name2)); } @@ -5946,11 +5347,7 @@ public virtual Task Join_on_entity_qsre_keys_inner_key_is_navigation(bool isAsyn ss => from c in ss.Set() join g in ss.Set() on c equals g.AssignedCity - select new - { - CityName = c.Name, - GearNickname = g.Nickname - }, + select new { CityName = c.Name, GearNickname = g.Nickname }, elementSorter: e => (e.CityName, e.GearNickname)); } @@ -5963,11 +5360,7 @@ public virtual Task Join_on_entity_qsre_keys_inner_key_is_navigation_composite_k ss => from g in ss.Set() join t in ss.Set().Where(tt => tt.Note == "Cole's Tag" || tt.Note == "Dom's Tag") on g equals t.Gear - select new - { - g.Nickname, - t.Note - }, + select new { g.Nickname, t.Note }, elementSorter: e => (e.Nickname, e.Note)); } @@ -5980,11 +5373,7 @@ public virtual Task Join_on_entity_qsre_keys_inner_key_is_nested_navigation(bool ss => from s in ss.Set() join w in ss.Set().Where(ww => ww.IsAutomatic) on s equals w.Owner.Squad - select new - { - SquadName = s.Name, - WeaponName = w.Name - }, + select new { SquadName = s.Name, WeaponName = w.Name }, elementSorter: e => (e.SquadName, e.WeaponName)); } @@ -5998,20 +5387,12 @@ public virtual Task GroupJoin_on_entity_qsre_keys_inner_key_is_nested_navigation from s in ss.Set() join w in ss.Set() on s equals w.Owner.Squad into grouping from w in grouping.DefaultIfEmpty() - select new - { - SquadName = s.Name, - WeaponName = w.Name - }, + select new { SquadName = s.Name, WeaponName = w.Name }, ss => from s in ss.Set() join w in ss.Set() on s equals Maybe(w.Owner, () => w.Owner.Squad) into grouping from w in grouping.DefaultIfEmpty() - select new - { - SquadName = s.Name, - WeaponName = Maybe(w, () => w.Name) - }, + select new { SquadName = s.Name, WeaponName = Maybe(w, () => w.Name) }, elementSorter: e => (e.SquadName, e.WeaponName)); } @@ -6021,31 +5402,18 @@ public virtual async Task Join_with_complex_key_selector(bool isAsync) { var message = (await Assert.ThrowsAsync( () => AssertQuery( - isAsync, - ss => ss.Set() - .Join( - ss.Set().Where(t => t.Note == "Marcus' Tag"), o => true, i => true, (o, i) => new - { - o, - i - }) - .GroupJoin( - ss.Set(), - oo => oo.o.Members.FirstOrDefault(v => v.Tag == oo.i), - ii => ii, - (k, g) => new - { - k.o, - k.i, - value = g.OrderBy(gg => gg.FullName).FirstOrDefault() - }) - .Select( - r => new - { - r.o.Id, - TagId = r.i.Id - }), - elementSorter: e => (e.Id, e.TagId)))).Message; + isAsync, + ss => ss.Set() + .Join( + ss.Set().Where(t => t.Note == "Marcus' Tag"), o => true, i => true, (o, i) => new { o, i }) + .GroupJoin( + ss.Set(), + oo => oo.o.Members.FirstOrDefault(v => v.Tag == oo.i), + ii => ii, + (k, g) => new { k.o, k.i, value = g.OrderBy(gg => gg.FullName).FirstOrDefault() }) + .Select( + r => new { r.o.Id, TagId = r.i.Id }), + elementSorter: e => (e.Id, e.TagId)))).Message; Assert.Equal( "This query would cause multiple evaluation of a subquery because entity 'Gear' has a composite key. Rewrite your query avoiding the subquery.", @@ -6143,11 +5511,7 @@ public virtual Task Project_one_value_type_from_empty_collection(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Where(s => s.Name == "Kilo").Select( - s => new - { - s.Name, - SquadId = s.Members.Where(m => m.HasSoulPatch).Select(m => m.SquadId).FirstOrDefault() - })); + s => new { s.Name, SquadId = s.Members.Where(m => m.HasSoulPatch).Select(m => m.SquadId).FirstOrDefault() })); } [ConditionalTheory(Skip = "issue #15864")] @@ -6167,11 +5531,7 @@ public virtual Task Select_subquery_projecting_single_constant_int(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Select( - s => new - { - s.Name, - Gear = s.Members.Where(g => g.HasSoulPatch).Select(g => 42).FirstOrDefault() - })); + s => new { s.Name, Gear = s.Members.Where(g => g.HasSoulPatch).Select(g => 42).FirstOrDefault() })); } [ConditionalTheory] @@ -6181,11 +5541,7 @@ public virtual Task Select_subquery_projecting_single_constant_string(bool isAsy return AssertQuery( isAsync, ss => ss.Set().Select( - s => new - { - s.Name, - Gear = s.Members.Where(g => g.HasSoulPatch).Select(g => "Foo").FirstOrDefault() - })); + s => new { s.Name, Gear = s.Members.Where(g => g.HasSoulPatch).Select(g => "Foo").FirstOrDefault() })); } [ConditionalTheory] @@ -6195,11 +5551,7 @@ public virtual Task Select_subquery_projecting_single_constant_bool(bool isAsync return AssertQuery( isAsync, ss => ss.Set().Select( - s => new - { - s.Name, - Gear = s.Members.Where(g => g.HasSoulPatch).Select(g => true).FirstOrDefault() - })); + s => new { s.Name, Gear = s.Members.Where(g => g.HasSoulPatch).Select(g => true).FirstOrDefault() })); } [ConditionalTheory(Skip = "Issue#17287")] @@ -6213,10 +5565,7 @@ public virtual Task Select_subquery_projecting_single_constant_inside_anonymous( { s.Name, Gear = s.Members.Where(g => g.HasSoulPatch).Select( - g => new - { - One = 1 - }).FirstOrDefault() + g => new { One = 1 }).FirstOrDefault() })); } @@ -6231,11 +5580,7 @@ public virtual Task Select_subquery_projecting_multiple_constants_inside_anonymo { s.Name, Gear = s.Members.Where(g => g.HasSoulPatch).Select( - g => new - { - True = true, - False = false - }).FirstOrDefault() + g => new { True = true, False = false }).FirstOrDefault() })); } @@ -6247,10 +5592,7 @@ public virtual Task Include_with_order_by_constant(bool isAsync) isAsync, ss => ss.Set().Include(s => s.Members).OrderBy(s => 42).Select(s => s), expectedQuery: ss => ss.Set(), - new List - { - new ExpectedInclude(s => s.Members, "Members") - }); + new List { new ExpectedInclude(s => s.Members, "Members") }); } [ConditionalFact(Skip = "Issue #17068")] @@ -6276,11 +5618,7 @@ public virtual Task Correlated_collection_order_by_constant(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().OrderByDescending(s => 1).Select( - g => new - { - g.Nickname, - Weapons = g.Weapons.Select(w => w.Name).ToList() - }), + g => new { g.Nickname, Weapons = g.Weapons.Select(w => w.Name).ToList() }), elementSorter: e => e.Nickname, elementAsserter: (e, a) => { @@ -6300,11 +5638,7 @@ public virtual Task Select_subquery_projecting_single_constant_null_of_non_mappe return AssertQuery( isAsync, ss => ss.Set().Select( - s => new - { - s.Name, - Gear = s.Members.Where(g => g.HasSoulPatch).Select(g => (MyDTO)null).FirstOrDefault() - })); + s => new { s.Name, Gear = s.Members.Where(g => g.HasSoulPatch).Select(g => (MyDTO)null).FirstOrDefault() })); } [ConditionalTheory] @@ -6314,11 +5648,7 @@ public virtual Task Select_subquery_projecting_single_constant_of_non_mapped_typ return AssertQuery( isAsync, ss => ss.Set().Select( - s => new - { - s.Name, - Gear = s.Members.Where(g => g.HasSoulPatch).Select(g => new MyDTO()).FirstOrDefault() - }), + s => new { s.Name, Gear = s.Members.Where(g => g.HasSoulPatch).Select(g => new MyDTO()).FirstOrDefault() }), elementSorter: e => e.Name, elementAsserter: (e, a) => Assert.Equal(e.Name, a.Name)); } @@ -6331,10 +5661,7 @@ public virtual Task Include_with_order_by_constant_null_of_non_mapped_type(bool isAsync, ss => ss.Set().Include(s => s.Members).OrderBy(s => (MyDTO)null), expectedQuery: ss => ss.Set(), - new List - { - new ExpectedInclude(s => s.Members, "Members") - }); + new List { new ExpectedInclude(s => s.Members, "Members") }); } [ConditionalFact(Skip = "issue #11567")] @@ -6359,19 +5686,15 @@ public virtual Task Correlated_collection_order_by_constant_null_of_non_mapped_t { return AssertTranslationFailed( () => AssertQuery( - isAsync, - ss => ss.Set().OrderByDescending(s => (MyDTO)null).Select( - g => new + isAsync, + ss => ss.Set().OrderByDescending(s => (MyDTO)null).Select( + g => new { g.Nickname, Weapons = g.Weapons.Select(w => w.Name).ToList() }), + elementSorter: e => e.Nickname, + elementAsserter: (e, a) => { - g.Nickname, - Weapons = g.Weapons.Select(w => w.Name).ToList() - }), - elementSorter: e => e.Nickname, - elementAsserter: (e, a) => - { - Assert.Equal(e.Nickname, a.Nickname); - AssertCollection(e.Weapons, a.Weapons); - })); + Assert.Equal(e.Nickname, a.Nickname); + AssertCollection(e.Weapons, a.Weapons); + })); } [ConditionalFact(Skip = "Issue #17068")] @@ -6380,12 +5703,7 @@ public virtual void GroupBy_composite_key_with_Include() using (var ctx = CreateContext()) { var query = ctx.Gears.Include(o => o.Weapons).GroupBy( - o => new - { - o.Rank, - One = 1, - o.Nickname - }); + o => new { o.Rank, One = 1, o.Nickname }); var result = query.ToList(); Assert.Equal(5, result.Count); @@ -6408,10 +5726,7 @@ public virtual Task Include_collection_OrderBy_aggregate(bool isAsync) ss => ss.Set().OfType() .Include(o => o.Reports) .OrderBy(o => o.Weapons.Count).ThenBy(o => o.Nickname), - new List - { - new ExpectedInclude(o => o.Reports, "Reports") - }, + new List { new ExpectedInclude(o => o.Reports, "Reports") }, assertOrder: true); } @@ -6424,10 +5739,7 @@ public virtual Task Include_collection_with_complex_OrderBy2(bool isAsync) ss => ss.Set().OfType() .Include(o => o.Reports) .OrderBy(o => o.Weapons.OrderBy(w => w.Id).FirstOrDefault().IsAutomatic).ThenBy(o => o.Nickname), - new List - { - new ExpectedInclude(o => o.Reports, "Reports") - }, + new List { new ExpectedInclude(o => o.Reports, "Reports") }, assertOrder: true); } @@ -6440,10 +5752,7 @@ public virtual Task Include_collection_with_complex_OrderBy3(bool isAsync) ss => ss.Set().OfType() .Include(o => o.Reports) .OrderBy(o => o.Weapons.OrderBy(w => w.Id).Select(w => w.IsAutomatic).FirstOrDefault()).ThenBy(o => o.Nickname), - new List - { - new ExpectedInclude(o => o.Reports, "Reports") - }, + new List { new ExpectedInclude(o => o.Reports, "Reports") }, assertOrder: true); } @@ -6469,7 +5778,8 @@ public virtual Task Correlated_collection_with_very_complex_order_by(bool isAsyn ss => ss.Set().OfType() .OrderBy( o => o.Weapons.Where( - w => w.IsAutomatic == ss.Set().Where(g => g.Nickname == "Marcus").Select(g => g.HasSoulPatch).FirstOrDefault()) + w => w.IsAutomatic == ss.Set().Where(g => g.Nickname == "Marcus").Select(g => g.HasSoulPatch) + .FirstOrDefault()) .Count()).ThenBy(g => g.Nickname) .Select(o => o.Reports.Where(g => !g.HasSoulPatch).ToList()), assertOrder: true, @@ -6543,7 +5853,8 @@ public virtual Task Select_subquery_int_with_pushdown_and_coalesce2(bool isAsync { return AssertQueryScalar( isAsync, - ss => ss.Set().Select(g => (int?)g.Weapons.OrderBy(w => w.Id).FirstOrDefault().Id ?? g.Weapons.OrderBy(w => w.Id).FirstOrDefault().Id)); + ss => ss.Set().Select( + g => (int?)g.Weapons.OrderBy(w => w.Id).FirstOrDefault().Id ?? g.Weapons.OrderBy(w => w.Id).FirstOrDefault().Id)); } [ConditionalTheory] @@ -6552,7 +5863,8 @@ public virtual Task Select_subquery_boolean_empty(bool isAsync) { return AssertQueryScalar( isAsync, - ss => ss.Set().Select(g => g.Weapons.Where(w => w.Name == "BFG").OrderBy(w => w.Id).Select(w => w.IsAutomatic).FirstOrDefault())); + ss => ss.Set().Select( + g => g.Weapons.Where(w => w.Name == "BFG").OrderBy(w => w.Id).Select(w => w.IsAutomatic).FirstOrDefault())); } [ConditionalTheory] @@ -6561,7 +5873,8 @@ public virtual Task Select_subquery_boolean_empty_with_pushdown(bool isAsync) { return AssertQueryScalar( isAsync, - ss => ss.Set().Select(g => (bool?)g.Weapons.Where(w => w.Name == "BFG").OrderBy(w => w.Id).FirstOrDefault().IsAutomatic), + ss => ss.Set().Select( + g => (bool?)g.Weapons.Where(w => w.Name == "BFG").OrderBy(w => w.Id).FirstOrDefault().IsAutomatic), ss => ss.Set().Select(g => (bool?)null)); } @@ -6721,7 +6034,8 @@ public virtual Task Double_order_by_on_nullable_bool_coming_from_optional_naviga return AssertQuery( isAsync, ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => w.IsAutomatic).OrderBy(w => w.IsAutomatic).ThenBy(w => w.Id), - ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => w != null ? w.IsAutomatic : false).ThenBy(w => w != null ? (int?)w.Id : null), + ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => w != null ? w.IsAutomatic : false) + .ThenBy(w => w != null ? (int?)w.Id : null), assertOrder: true); } @@ -6733,7 +6047,8 @@ public virtual Task Double_order_by_on_Like(bool isAsync) isAsync, ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => EF.Functions.Like(w.Name, "%Lancer")) .OrderBy(w => EF.Functions.Like(w.Name, "%Lancer")).Select(w => w), - ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => w != null ? w.Name.EndsWith("Lancer") : false).Select(w => w)); + ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => w != null ? w.Name.EndsWith("Lancer") : false) + .Select(w => w)); } [ConditionalTheory] @@ -6752,7 +6067,8 @@ public virtual Task Double_order_by_on_string_compare(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().OrderBy(w => w.Name.CompareTo("Marcus' Lancer") == 0).OrderBy(w => w.Name.CompareTo("Marcus' Lancer") == 0).ThenBy(w => w.Id), + ss => ss.Set().OrderBy(w => w.Name.CompareTo("Marcus' Lancer") == 0) + .OrderBy(w => w.Name.CompareTo("Marcus' Lancer") == 0).ThenBy(w => w.Id), ss => ss.Set().OrderBy(w => w != null ? w.Name.CompareTo("Marcus' Lancer") == 0 : false).ThenBy(w => w.Id), assertOrder: true); } @@ -6773,7 +6089,8 @@ public virtual Task String_compare_with_null_conditional_argument(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => w.Name.CompareTo("Marcus' Lancer") == 0).Select(c => c), - ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => w != null ? w.Name.CompareTo("Marcus' Lancer") == 0 : false).Select(c => c)); + ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => w != null ? w.Name.CompareTo("Marcus' Lancer") == 0 : false) + .Select(c => c)); } [ConditionalTheory] @@ -6783,7 +6100,8 @@ public virtual Task String_compare_with_null_conditional_argument2(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => "Marcus' Lancer".CompareTo(w.Name) == 0).Select(w => w), - ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => w != null ? "Marcus' Lancer".CompareTo(w.Name) == 0 : false).Select(w => w)); + ss => ss.Set().Select(w => w.SynergyWith).OrderBy(w => w != null ? "Marcus' Lancer".CompareTo(w.Name) == 0 : false) + .Select(w => w)); } [ConditionalTheory] @@ -6901,11 +6219,7 @@ public virtual Task GroupBy_Property_Include_Aggregate_with_anonymous_selector(b ss => ss.Set().Include(g => g.CityOfBirth).GroupBy(g => g.Nickname).OrderBy(g => g.Key) .Select( - g => new - { - g.Key, - c = g.Count() - }), + g => new { g.Key, c = g.Count() }), assertOrder: true); } @@ -6960,12 +6274,7 @@ public virtual Task Group_by_with_include_with_entity_in_result_selector(bool is ss => ss.Set().Include(g => g.CityOfBirth).GroupBy(g => g.Rank).OrderBy(g => g.Key) .Select( - g => new - { - g.Key, - c = g.Count(), - element = g.OrderBy(gg => gg.Nickname).FirstOrDefault() - }), + g => new { g.Key, c = g.Count(), element = g.OrderBy(gg => gg.Nickname).FirstOrDefault() }), assertOrder: true, elementAsserter: (e, a) => { @@ -7098,8 +6407,8 @@ public virtual Task GetValueOrDefault_on_DateTimeOffset(bool isAsync) return AssertTranslationFailed( () => AssertQuery( - isAsync, - ss => ss.Set().Where(m => ((DateTimeOffset?)m.Timeline).GetValueOrDefault() == defaultValue))); + isAsync, + ss => ss.Set().Where(m => ((DateTimeOffset?)m.Timeline).GetValueOrDefault() == defaultValue))); } [ConditionalTheory] @@ -7154,11 +6463,7 @@ let automaticWeapons = g.Weapons .OrderByDescending(w => w.AmmunitionType) .Where(w => w.IsAutomatic) - select new - { - g.Nickname, - WeaponName = automaticWeapons.FirstOrDefault().Name - }, + select new { g.Nickname, WeaponName = automaticWeapons.FirstOrDefault().Name }, ss => from g in ss.Set() where g.Nickname != "Dom" let automaticWeapons @@ -7298,7 +6603,8 @@ public virtual Task Nav_rewrite_with_convert1(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Where(f => f.Capital.Name != "Foo").Select(f => ((LocustHorde)f).Commander), - ss => ss.Set().Where(f => Maybe(f.Capital, () => f.Capital.Name) != "Foo").Select(f => ((LocustHorde)f).Commander)); + ss => ss.Set().Where(f => Maybe(f.Capital, () => f.Capital.Name) != "Foo") + .Select(f => ((LocustHorde)f).Commander)); } [ConditionalTheory] @@ -7307,8 +6613,10 @@ public virtual Task Nav_rewrite_with_convert2(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(f => f.Capital.Name != "Foo").Select(f => (LocustHorde)f).Where(lh => lh.Commander.Name != "Bar"), - ss => ss.Set().Where(f => Maybe(f.Capital, () => f.Capital.Name) != "Foo").Select(f => (LocustHorde)f).Where(lh => lh.Commander.Name != "Bar")); + ss => ss.Set().Where(f => f.Capital.Name != "Foo").Select(f => (LocustHorde)f) + .Where(lh => lh.Commander.Name != "Bar"), + ss => ss.Set().Where(f => Maybe(f.Capital, () => f.Capital.Name) != "Foo").Select(f => (LocustHorde)f) + .Where(lh => lh.Commander.Name != "Bar")); } [ConditionalTheory] @@ -7317,8 +6625,10 @@ public virtual Task Nav_rewrite_with_convert3(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(f => f.Capital.Name != "Foo").Select(f => new { horde = (LocustHorde)f }).Where(x => x.horde.Commander.Name != "Bar"), - ss => ss.Set().Where(f => Maybe(f.Capital, () => f.Capital.Name) != "Foo").Select(f => new { horde = (LocustHorde)f }).Where(x => x.horde.Commander.Name != "Bar"), + ss => ss.Set().Where(f => f.Capital.Name != "Foo").Select(f => new { horde = (LocustHorde)f }) + .Where(x => x.horde.Commander.Name != "Bar"), + ss => ss.Set().Where(f => Maybe(f.Capital, () => f.Capital.Name) != "Foo") + .Select(f => new { horde = (LocustHorde)f }).Where(x => x.horde.Commander.Name != "Bar"), elementSorter: e => e.horde.Id, elementAsserter: (e, a) => AssertEqual(e.horde, a.horde)); } @@ -7353,9 +6663,10 @@ public virtual Task Include_with_complex_order_by(bool isAsync) .ThenBy(g => g.Nickname), ss => ss.Set() .Include(g => g.Weapons) - .OrderBy(g => Maybe( - g.Weapons.FirstOrDefault(w => w.Name.Contains("Gnasher")), - () => g.Weapons.FirstOrDefault(w => w.Name.Contains("Gnasher")).Name)) + .OrderBy( + g => Maybe( + g.Weapons.FirstOrDefault(w => w.Name.Contains("Gnasher")), + () => g.Weapons.FirstOrDefault(w => w.Name.Contains("Gnasher")).Name)) .ThenBy(g => g.Nickname), expectedIncludes: new List { new ExpectedInclude(e => e.Weapons, "Weapons") }, assertOrder: true); @@ -7367,7 +6678,8 @@ public virtual Task Anonymous_projection_take_followed_by_projecting_single_elem { return AssertQuery( isAsync, - ss => ss.Set().Select(g => new { Gear = g }).Take(25).Select(e => e.Gear.Weapons.OrderBy(w => w.Id).FirstOrDefault())); + ss => ss.Set().Select(g => new { Gear = g }).Take(25) + .Select(e => e.Gear.Weapons.OrderBy(w => w.Id).FirstOrDefault())); } [ConditionalTheory] @@ -7376,7 +6688,8 @@ public virtual Task Bool_projection_from_subquery_treated_appropriately_in_where { return AssertQuery( isAsync, - ss => ss.Set().Where(c => ss.Set().OrderBy(g => g.Nickname).ThenBy(g => g.SquadId).FirstOrDefault().HasSoulPatch)); + ss => ss.Set().Where( + c => ss.Set().OrderBy(g => g.Nickname).ThenBy(g => g.SquadId).FirstOrDefault().HasSoulPatch)); } [ConditionalTheory] @@ -7386,13 +6699,14 @@ public virtual Task DateTimeOffset_Contains_Less_than_Greater_than(bool isAsync) var dto = new DateTimeOffset(599898024001234567, new TimeSpan(1, 30, 0)); var start = dto.AddDays(-1); var end = dto.AddDays(1); - var dates = new DateTimeOffset[] { dto }; + var dates = new[] { dto }; return AssertQuery( isAsync, - ss => ss.Set().Where(m => start <= m.Timeline.Date && - m.Timeline < end && - dates.Contains(m.Timeline))); + ss => ss.Set().Where( + m => start <= m.Timeline.Date && + m.Timeline < end && + dates.Contains(m.Timeline))); } [ConditionalTheory] @@ -7401,7 +6715,8 @@ public virtual Task Navigation_inside_interpolated_string_expanded(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Select(w => w.SynergyWithId.HasValue ? $"SynergyWithOwner: {w.SynergyWith.OwnerFullName}" : string.Empty)); + ss => ss.Set().Select( + w => w.SynergyWithId.HasValue ? $"SynergyWithOwner: {w.SynergyWith.OwnerFullName}" : string.Empty)); } [ConditionalTheory] @@ -7412,7 +6727,7 @@ public virtual Task Left_join_projection_using_coalesce_tracking(bool isAsync) isAsync, ss => from g1 in ss.Set().AsTracking() join g2 in ss.Set() - on g1.LeaderNickname equals g2.Nickname into grouping + on g1.LeaderNickname equals g2.Nickname into grouping from g2 in grouping.DefaultIfEmpty() select g2 ?? g1, entryCount: 5); @@ -7426,7 +6741,7 @@ public virtual Task Left_join_projection_using_conditional_tracking(bool isAsync isAsync, ss => from g1 in ss.Set().AsTracking() join g2 in ss.Set() - on g1.LeaderNickname equals g2.Nickname into grouping + on g1.LeaderNickname equals g2.Nickname into grouping from g2 in grouping.DefaultIfEmpty() select g2 == null ? g1 : g2, entryCount: 5); @@ -7471,13 +6786,14 @@ public virtual Task Null_checks_in_correlated_predicate_are_correctly_translated return AssertQuery( isAsync, ss => from t in ss.Set() - select new - { - key = t.Id, - collection = (from g in ss.Set() - where t.GearNickName == g.Nickname && t.GearSquadId != null && t.GearSquadId == g.SquadId && t.GearNickName != null && t.Note != null && null != t.Note - select g).ToList() - }, + select new + { + key = t.Id, + collection = (from g in ss.Set() + where t.GearNickName == g.Nickname && t.GearSquadId != null && t.GearSquadId == g.SquadId + && t.GearNickName != null && t.Note != null && null != t.Note + select g).ToList() + }, elementSorter: e => e.key, elementAsserter: (e, a) => { @@ -7496,12 +6812,7 @@ public virtual Task SelectMany_Where_DefaultIfEmpty_with_navigation_in_the_colle isAsync, ss => from g in ss.Set() from w in g.Weapons.Where(ww => ww.IsAutomatic == isAutomatic).DefaultIfEmpty() - select new - { - g.Nickname, - g.FullName, - Collection = w != null - }); + select new { g.Nickname, g.FullName, Collection = w != null }); } [ConditionalTheory] @@ -7526,9 +6837,9 @@ public virtual Task Join_with_inner_being_a_subquery_projecting_anonymous_type_w isAsync, ss => from g in ss.Set() join inner in ( - from g2 in ss.Set() - select new { g2.Nickname } - ) on g.Nickname equals inner.Nickname + from g2 in ss.Set() + select new { g2.Nickname } + ) on g.Nickname equals inner.Nickname select g); } @@ -7634,24 +6945,14 @@ public virtual Task Acessing_reference_navigation_collection_composition_generat { return AssertQuery( isAsync, - ss => ss.Set().OrderBy(g => g.Nickname).Select(g => new - { - Weapons = g.Weapons.Select(w => new - { - w.Id, - w.IsAutomatic, - w.SynergyWith.Name - }) - }), - ss => ss.Set().OrderBy(g => g.Nickname).Select(g => new - { - Weapons = g.Weapons.Select(w => new + ss => ss.Set().OrderBy(g => g.Nickname).Select( + g => new { Weapons = g.Weapons.Select(w => new { w.Id, w.IsAutomatic, w.SynergyWith.Name }) }), + ss => ss.Set().OrderBy(g => g.Nickname).Select( + g => new { - w.Id, - w.IsAutomatic, - Name = Maybe(w.SynergyWith, () => w.SynergyWith.Name) - }) - }), + Weapons = g.Weapons.Select( + w => new { w.Id, w.IsAutomatic, Name = Maybe(w.SynergyWith, () => w.SynergyWith.Name) }) + }), assertOrder: true, elementAsserter: (e, a) => AssertCollection(e.Weapons, a.Weapons, elementSorter: ee => ee.Id)); } @@ -7665,8 +6966,7 @@ public virtual Task Reference_include_chain_loads_correctly_when_middle_is_null( ss => ss.Set().AsTracking().OrderBy(t => t.Note).Include(t => t.Gear).ThenInclude(g => g.Squad), new List { - new ExpectedInclude(t => t.Gear, "Gear"), - new ExpectedInclude(t => t.Squad, "Squad", "Gear") + new ExpectedInclude(t => t.Gear, "Gear"), new ExpectedInclude(t => t.Squad, "Squad", "Gear") }, entryCount: 13); } @@ -7704,9 +7004,10 @@ public virtual async Task Include_after_select_with_cast_throws(bool isAsync) Assert.Equal( "Include has been used on non entity queryable.", (await Assert.ThrowsAsync( - () => AssertQuery( - isAsync, - ss => ss.Set().Where(f => f is LocustHorde).Select(f => (LocustHorde)f).Include(h => h.Commander)))).Message); + () => AssertQuery( + isAsync, + ss => ss.Set().Where(f => f is LocustHorde).Select(f => (LocustHorde)f).Include(h => h.Commander)))) + .Message); } [ConditionalTheory] @@ -7716,9 +7017,9 @@ public virtual async Task Include_after_select_with_entity_projection_throws(boo Assert.Equal( "Include has been used on non entity queryable.", (await Assert.ThrowsAsync( - () => AssertQuery( - isAsync, - ss => ss.Set().Select(f => f.Capital).Include(c => c.BornGears)))).Message); + () => AssertQuery( + isAsync, + ss => ss.Set().Select(f => f.Capital).Include(c => c.BornGears)))).Message); } [ConditionalTheory] @@ -7728,9 +7029,9 @@ public virtual async Task Include_after_select_anonymous_projection_throws(bool Assert.Equal( "Include has been used on non entity queryable.", (await Assert.ThrowsAsync( - () => AssertQuery( - isAsync, - ss => ss.Set().Select(f => new { f }).Include(x => x.f.Capital)))).Message); + () => AssertQuery( + isAsync, + ss => ss.Set().Select(f => new { f }).Include(x => x.f.Capital)))).Message); } [ConditionalTheory(Skip = "issue #14671")] @@ -7740,9 +7041,9 @@ public virtual async Task Include_after_Select_throws(bool isAsync) Assert.Equal( "Include has been used on non entity queryable.", (await Assert.ThrowsAsync( - () => AssertQuery( - isAsync, - ss => ss.Set().Select(f => f).Include(h => h.Capital)))).Message); + () => AssertQuery( + isAsync, + ss => ss.Set().Select(f => f).Include(h => h.Capital)))).Message); } [ConditionalTheory(Skip = "issue #14671")] @@ -7752,23 +7053,18 @@ public virtual async Task Include_after_SelectMany_throws(bool isAsync) Assert.Equal( "Include has been used on non entity queryable.", (await Assert.ThrowsAsync( - () => AssertQuery( - isAsync, - ss => ss.Set().SelectMany(f => f.Capital.BornGears).Include(g => g.Squad), - ss => ss.Set().SelectMany(f => Maybe(f.Capital, () => f.Capital.BornGears) ?? new List())))).Message); + () => AssertQuery( + isAsync, + ss => ss.Set().SelectMany(f => f.Capital.BornGears).Include(g => g.Squad), + ss => ss.Set().SelectMany(f => Maybe(f.Capital, () => f.Capital.BornGears) ?? new List())))) + .Message); } [ConditionalTheory] [MemberData(nameof(IsAsyncData))] public virtual Task Query_reusing_parameter_doesnt_declare_duplicate_parameter(bool isAsync) { - var prm = new ComplexParameter - { - Inner = new ComplexParameterInner - { - Nickname = "Marcus", - } - }; + var prm = new ComplexParameter { Inner = new ComplexParameterInner { Nickname = "Marcus" } }; return AssertQuery( isAsync, @@ -7784,13 +7080,7 @@ public virtual Task Query_reusing_parameter_doesnt_declare_duplicate_parameter(b [MemberData(nameof(IsAsyncData))] public virtual Task Query_reusing_parameter_doesnt_declare_duplicate_parameter_complex(bool isAsync) { - var prm = new ComplexParameter - { - Inner = new ComplexParameterInner - { - Squad = new Squad { Id = 1 } - } - }; + var prm = new ComplexParameter { Inner = new ComplexParameterInner { Squad = new Squad { Id = 1 } } }; return AssertQuery( isAsync, @@ -7846,33 +7136,17 @@ public virtual Task Complex_GroupBy_after_set_operator(bool isAsync) return AssertQuery( isAsync, ss => (from g in ss.Set() - select new - { - g.AssignedCity.Name, - Count = g.Weapons.Count(), - }).Concat( + select new { g.AssignedCity.Name, Count = g.Weapons.Count() }).Concat( from g in ss.Set() - select new - { - g.CityOfBirth.Name, - Count = g.Weapons.Count(), - }) - .GroupBy(x => new { x.Name, x.Count }) - .Select(g => new { g.Key.Name, g.Key.Count, Sum = g.Sum(xx => xx.Count) }), + select new { g.CityOfBirth.Name, Count = g.Weapons.Count() }) + .GroupBy(x => new { x.Name, x.Count }) + .Select(g => new { g.Key.Name, g.Key.Count, Sum = g.Sum(xx => xx.Count) }), ss => (from g in ss.Set() - select new - { - Name = Maybe(g.AssignedCity, () => g.AssignedCity.Name), - Count = g.Weapons.Count(), - }).Concat( + select new { Name = Maybe(g.AssignedCity, () => g.AssignedCity.Name), Count = g.Weapons.Count() }).Concat( from g in ss.Set() - select new - { - g.CityOfBirth.Name, - Count = g.Weapons.Count(), - }) - .GroupBy(x => new { x.Name, x.Count }) - .Select(g => new { g.Key.Name, g.Key.Count, Sum = g.Sum(xx => xx.Count) }), + select new { g.CityOfBirth.Name, Count = g.Weapons.Count() }) + .GroupBy(x => new { x.Name, x.Count }) + .Select(g => new { g.Key.Name, g.Key.Count, Sum = g.Sum(xx => xx.Count) }), elementSorter: e => (e.Name, e.Count, e.Sum)); } @@ -7883,35 +7157,19 @@ public virtual Task Complex_GroupBy_after_set_operator_using_result_selector(boo return AssertQuery( isAsync, ss => (from g in ss.Set() - select new - { - g.AssignedCity.Name, - Count = g.Weapons.Count(), - }).Concat( + select new { g.AssignedCity.Name, Count = g.Weapons.Count() }).Concat( from g in ss.Set() - select new - { - g.CityOfBirth.Name, - Count = g.Weapons.Count(), - }) - .GroupBy( - x => new { x.Name, x.Count }, - (k, g) => new { k.Name, k.Count, Sum = g.Sum(xx => xx.Count) }), + select new { g.CityOfBirth.Name, Count = g.Weapons.Count() }) + .GroupBy( + x => new { x.Name, x.Count }, + (k, g) => new { k.Name, k.Count, Sum = g.Sum(xx => xx.Count) }), ss => (from g in ss.Set() - select new - { - Name = Maybe(g.AssignedCity, () => g.AssignedCity.Name), - Count = g.Weapons.Count(), - }).Concat( + select new { Name = Maybe(g.AssignedCity, () => g.AssignedCity.Name), Count = g.Weapons.Count() }).Concat( from g in ss.Set() - select new - { - g.CityOfBirth.Name, - Count = g.Weapons.Count(), - }) - .GroupBy( - x => new { x.Name, x.Count }, - (k, g) => new { k.Name, k.Count, Sum = g.Sum(xx => xx.Count) }), + select new { g.CityOfBirth.Name, Count = g.Weapons.Count() }) + .GroupBy( + x => new { x.Name, x.Count }, + (k, g) => new { k.Name, k.Count, Sum = g.Sum(xx => xx.Count) }), elementSorter: e => (e.Name, e.Count, e.Sum)); } @@ -7925,7 +7183,8 @@ public virtual Task Left_join_with_GroupBy_with_composite_group_key(bool isAsync join s in ss.Set() on g.SquadId equals s.Id join t in ss.Set() on g.Nickname equals t.GearNickName into grouping from t in grouping.DefaultIfEmpty() - group g by new { g.CityOfBirthName, g.HasSoulPatch } into groupby + group g by new { g.CityOfBirthName, g.HasSoulPatch } + into groupby select new { groupby.Key.CityOfBirthName, groupby.Key.HasSoulPatch }, elementSorter: e => (e.CityOfBirthName, e.HasSoulPatch)); } @@ -7953,11 +7212,12 @@ public virtual Task GroupBy_with_boolean_groupin_key_thru_navigation_access(bool .GroupBy(t => new { t.Gear.HasSoulPatch, t.Gear.Squad.Name }) .Select(g => new { g.Key.HasSoulPatch, Name = g.Key.Name.ToLower() }), ss => ss.Set() - .GroupBy(t => new - { - HasSoulPatch = MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch) ?? false, - Name = Maybe(t.Gear, () => t.Gear.Squad.Name) - }) + .GroupBy( + t => new + { + HasSoulPatch = MaybeScalar(t.Gear, () => t.Gear.HasSoulPatch) ?? false, + Name = Maybe(t.Gear, () => t.Gear.Squad.Name) + }) .Select(g => new { g.Key.HasSoulPatch, Name = Maybe(g.Key.Name, () => g.Key.Name.ToLower()) }), elementSorter: e => (e.HasSoulPatch, e.Name)); } @@ -7969,23 +7229,25 @@ public virtual Task Group_by_over_projection_with_multiple_properties_accessed_t return AssertQuery( isAsync, ss => ss.Set() - .Select(g => new - { - g.Nickname, - AssignedCityName = g.AssignedCity.Name, - CityOfBirthName = g.CityOfBirth.Name, - SquadName = g.Squad.Name - }) + .Select( + g => new + { + g.Nickname, + AssignedCityName = g.AssignedCity.Name, + CityOfBirthName = g.CityOfBirth.Name, + SquadName = g.Squad.Name + }) .GroupBy(x => x.CityOfBirthName) .Select(g => g.Key), ss => ss.Set() - .Select(g => new - { - g.Nickname, - AssignedCityName = Maybe(g.AssignedCity, () => g.AssignedCity.Name), - CityOfBirthName = Maybe(g.CityOfBirth, () => g.CityOfBirth.Name), - SquadName = g.Squad.Name - }) + .Select( + g => new + { + g.Nickname, + AssignedCityName = Maybe(g.AssignedCity, () => g.AssignedCity.Name), + CityOfBirthName = Maybe(g.CityOfBirth, () => g.CityOfBirth.Name), + SquadName = g.Squad.Name + }) .GroupBy(x => x.CityOfBirthName) .Select(g => g.Key)); } @@ -7996,14 +7258,10 @@ public virtual Task Group_by_with_aggregate_max_on_entity_type(bool isAsync) { return Assert.ThrowsAsync( () => AssertQuery( - isAsync, - ss => ss.Set() - .GroupBy(g => g.CityOfBirthName) - .Select(g => new - { - g.Key, - Aggregate = g.Max() - }))); + isAsync, + ss => ss.Set() + .GroupBy(g => g.CityOfBirthName) + .Select(g => new { g.Key, Aggregate = g.Max() }))); } [ConditionalTheory(Skip = "issue #18492")] diff --git a/test/EFCore.Specification.Tests/Query/GroupByQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/GroupByQueryTestBase.cs index 2a0a9e13b25..9994bb88e9f 100644 --- a/test/EFCore.Specification.Tests/Query/GroupByQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/GroupByQueryTestBase.cs @@ -252,11 +252,7 @@ public virtual Task GroupBy_aggregate_projecting_conditional_expression(bool isA isAsync, ss => ss.Set().GroupBy(o => o.OrderDate).Select( g => - new - { - Key = g.Key, - SomeValue = g.Count() == 0 ? 1 : g.Sum(o => o.OrderID % 2 == 0 ? 1 : 0) / g.Count() - }), + new { g.Key, SomeValue = g.Count() == 0 ? 1 : g.Sum(o => o.OrderID % 2 == 0 ? 1 : 0) / g.Count() }), e => e.SomeValue); } @@ -280,11 +276,7 @@ public virtual Task GroupBy_with_group_key_access_thru_navigation(bool isAsync) isAsync, ss => ss.Set() .GroupBy(od => od.Order.CustomerID) - .Select(g => new - { - g.Key, - Aggregate = g.Sum(od => od.OrderID), - }), + .Select(g => new { g.Key, Aggregate = g.Sum(od => od.OrderID) }), elementSorter: e => e.Key); } @@ -296,11 +288,7 @@ public virtual Task GroupBy_with_group_key_access_thru_nested_navigation(bool is isAsync, ss => ss.Set() .GroupBy(od => od.Order.Customer.Country) - .Select(g => new - { - g.Key, - Aggregate = g.Sum(od => od.OrderID), - }), + .Select(g => new { g.Key, Aggregate = g.Sum(od => od.OrderID) }), elementSorter: e => e.Key); } @@ -348,11 +336,7 @@ public virtual Task Group_by_with_arithmetic_operation_inside_aggregate(bool isA isAsync, ss => ss.Set() .GroupBy(o => o.CustomerID) - .Select(g => new - { - g.Key, - Sum = g.Sum(o => o.OrderID + o.CustomerID.Length) - }), + .Select(g => new { g.Key, Sum = g.Sum(o => o.OrderID + o.CustomerID.Length) }), elementSorter: e => e.Key, elementAsserter: (e, a) => { @@ -1455,7 +1439,7 @@ public virtual Task Self_join_GroupBy_Aggregate(bool isAsync) ss => (from o1 in ss.Set().Where(o => o.OrderID < 10400) join o2 in ss.Set() on o1.OrderID equals o2.OrderID group o2 by o1.CustomerID) - .Select(g => new { g.Key, Count = g.Average(o => o.OrderID) }), + .Select(g => new { g.Key, Count = g.Average(o => o.OrderID) }), e => e.Key); } @@ -1818,9 +1802,10 @@ public virtual Task Select_nested_collection_with_groupby(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Where(c => c.CustomerID.StartsWith("A")) - .Select(c => c.Orders.Any() - ? c.Orders.GroupBy(o => o.OrderID).Select(g => g.Key).ToArray() - : Array.Empty())); + .Select( + c => c.Orders.Any() + ? c.Orders.GroupBy(o => o.OrderID).Select(g => g.Key).ToArray() + : Array.Empty())); } [ConditionalTheory(Skip = "Issue #17068")] @@ -1901,7 +1886,7 @@ public virtual Task GroupBy_with_order_by_skip_and_another_order_by(bool isAsync .OrderBy(o => o.CustomerID) .GroupBy(o => o.CustomerID) .Select(g => g.Sum(o => o.OrderID)) - ); + ); } [ConditionalTheory] @@ -1987,8 +1972,7 @@ join orderDetail in ss.Set() on order.OrderID equals orderDetail.Or from orderDetail in orderJoin.DefaultIfEmpty() group new { orderDetail.ProductID, orderDetail.Quantity, orderDetail.UnitPrice } by new { - order.OrderID, - order.OrderDate + order.OrderID, order.OrderDate }).Where(x => x.Key.OrderID == 10248), elementAsserter: (e, a) => AssertGrouping(e, a)); } @@ -2234,7 +2218,8 @@ public virtual Task OrderBy_Skip_Take_GroupBy(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(o => o.CustomerID != "SAVEA").OrderBy(o => o.OrderDate).Skip(450).Take(50).GroupBy(o => o.CustomerID), + ss => ss.Set().Where(o => o.CustomerID != "SAVEA").OrderBy(o => o.OrderDate).Skip(450).Take(50) + .GroupBy(o => o.CustomerID), elementSorter: e => e.Key, elementAsserter: (e, a) => AssertGrouping(e, a), entryCount: 50); @@ -2376,11 +2361,11 @@ public virtual Task Join_GroupBy_entity_ToList(bool isAsync) return AssertQuery( isAsync, ss => from c in ss.Set().OrderBy(c => c.CustomerID).Take(5) - join o in ss.Set().OrderBy(o => o.OrderID).Take(50) - on c.CustomerID equals o.CustomerID - group o by c - into grp - select new { C = grp.Key, Os = grp.ToList() }); + join o in ss.Set().OrderBy(o => o.OrderID).Take(50) + on c.CustomerID equals o.CustomerID + group o by c + into grp + select new { C = grp.Key, Os = grp.ToList() }); } [ConditionalTheory(Skip = "issue #15938")] @@ -2391,11 +2376,7 @@ public virtual Task GroupBy_with_group_key_being_navigation(bool isAsync) isAsync, ss => ss.Set() .GroupBy(od => od.Order) - .Select(g => new - { - g.Key, - Aggregate = g.Sum(od => od.OrderID), - }), + .Select(g => new { g.Key, Aggregate = g.Sum(od => od.OrderID) }), elementSorter: e => e.Key); } @@ -2407,11 +2388,7 @@ public virtual Task GroupBy_with_group_key_being_nested_navigation(bool isAsync) isAsync, ss => ss.Set() .GroupBy(od => od.Order.Customer) - .Select(g => new - { - g.Key, - Aggregate = g.Sum(od => od.OrderID), - }), + .Select(g => new { g.Key, Aggregate = g.Sum(od => od.OrderID) }), elementSorter: e => e.Key); } @@ -2434,14 +2411,15 @@ public virtual Task GroupBy_with_group_key_being_navigation_with_complex_project isAsync, ss => ss.Set() .GroupBy(od => od.Order) - .Select(g => new - { - g.Key, - Id1 = g.Key.CustomerID, - Id2 = g.Key.Customer.CustomerID, - Id3 = g.Key.OrderID, - Aggregate = g.Sum(od => od.OrderID), - }), + .Select( + g => new + { + g.Key, + Id1 = g.Key.CustomerID, + Id2 = g.Key.Customer.CustomerID, + Id3 = g.Key.OrderID, + Aggregate = g.Sum(od => od.OrderID) + }), elementSorter: e => e.Id3, elementAsserter: (e, a) => { @@ -2571,21 +2549,15 @@ public virtual Task Complex_query_with_groupBy_in_subquery1(bool isAsync) return AssertQuery( isAsync, ss => ss.Set() - .Select(c => new - { - Key = c.CustomerID, - Subquery = c.Orders - .Select(o => new - { - First = o.CustomerID, - Second = o.OrderID - }) - .GroupBy(x => x.First) - .Select(g => new - { - Sum = g.Sum(x => x.Second), - }).ToList() - }), + .Select( + c => new + { + Key = c.CustomerID, + Subquery = c.Orders + .Select(o => new { First = o.CustomerID, Second = o.OrderID }) + .GroupBy(x => x.First) + .Select(g => new { Sum = g.Sum(x => x.Second) }).ToList() + }), elementSorter: e => e.Key, elementAsserter: (e, a) => { @@ -2601,22 +2573,15 @@ public virtual Task Complex_query_with_groupBy_in_subquery2(bool isAsync) return AssertQuery( isAsync, ss => ss.Set() - .Select(c => new - { - Key = c.CustomerID, - Subquery = c.Orders - .Select(o => new - { - First = o.CustomerID, - Second = o.OrderID - }) - .GroupBy(x => x.First) - .Select(g => new - { - Max = g.Max(x => x.First.Length), - Sum = g.Sum(x => x.Second), - }).ToList() - }), + .Select( + c => new + { + Key = c.CustomerID, + Subquery = c.Orders + .Select(o => new { First = o.CustomerID, Second = o.OrderID }) + .GroupBy(x => x.First) + .Select(g => new { Max = g.Max(x => x.First.Length), Sum = g.Sum(x => x.Second) }).ToList() + }), elementSorter: e => e.Key, elementAsserter: (e, a) => { @@ -2632,22 +2597,15 @@ public virtual Task Complex_query_with_groupBy_in_subquery3(bool isAsync) return AssertQuery( isAsync, ss => ss.Set() - .Select(c => new - { - Key = c.CustomerID, - Subquery = ss.Set() - .Select(o => new - { - First = o.CustomerID, - Second = o.OrderID - }) - .GroupBy(x => x.First) - .Select(g => new - { - Max = g.Max(x => x.First.Length), - Sum = g.Sum(x => x.Second), - }).ToList() - }), + .Select( + c => new + { + Key = c.CustomerID, + Subquery = ss.Set() + .Select(o => new { First = o.CustomerID, Second = o.OrderID }) + .GroupBy(x => x.First) + .Select(g => new { Max = g.Max(x => x.First.Length), Sum = g.Sum(x => x.Second) }).ToList() + }), elementSorter: e => e.Key, elementAsserter: (e, a) => { @@ -2664,22 +2622,15 @@ public virtual Task Complex_query_with_groupBy_in_subquery4(bool isAsync) return AssertQuery( isAsync, ss => ss.Set() - .Select(c => new - { - Key = c.CustomerID, - Subquery = c.Orders - .Select(o => new - { - First = o.OrderID, - Second = o.Customer.City + o.CustomerID - }) - .GroupBy(x => x.Second) - .Select(g => new - { - Sum = g.Sum(x => x.First), - Count = g.Count(x => x.Second.StartsWith("Lon")) - }).ToList() - }), + .Select( + c => new + { + Key = c.CustomerID, + Subquery = c.Orders + .Select(o => new { First = o.OrderID, Second = o.Customer.City + o.CustomerID }) + .GroupBy(x => x.Second) + .Select(g => new { Sum = g.Sum(x => x.First), Count = g.Count(x => x.Second.StartsWith("Lon")) }).ToList() + }), elementSorter: e => e.Key, elementAsserter: (e, a) => { diff --git a/test/EFCore.Specification.Tests/Query/IncludeTestBase.cs b/test/EFCore.Specification.Tests/Query/IncludeTestBase.cs index 23de2c4b40b..bdae7d0e5b0 100644 --- a/test/EFCore.Specification.Tests/Query/IncludeTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/IncludeTestBase.cs @@ -4026,7 +4026,8 @@ public virtual async Task Include_empty_reference_sets_IsLoaded(bool useString, [InlineData(true, false)] [InlineData(false, true)] [InlineData(true, true)] - public virtual async Task Include_is_not_ignored_when_projection_contains_client_method_and_complex_expression(bool useString, bool async) + public virtual async Task Include_is_not_ignored_when_projection_contains_client_method_and_complex_expression( + bool useString, bool async) { using (var context = CreateContext()) { @@ -4040,7 +4041,8 @@ public virtual async Task Include_is_not_ignored_when_projection_contains_client ? await query.ToListAsync() : query.ToList(); - Assert.Collection(result, + Assert.Collection( + result, e => Assert.Equal("Employee Nancy reports to Andrew", e), e2 => Assert.Equal("", e2)); } @@ -4049,7 +4051,6 @@ public virtual async Task Include_is_not_ignored_when_projection_contains_client private static string ClientMethod(Employee e) => e.FirstName + " reports to " + e.Manager.FirstName + e.Manager.LastName; - [ConditionalTheory(Skip = "Issue #17068")] [InlineData(false, false)] [InlineData(true, false)] diff --git a/test/EFCore.Specification.Tests/Query/OwnedQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/OwnedQueryTestBase.cs index 77eec8778d0..a4c1e6f356a 100644 --- a/test/EFCore.Specification.Tests/Query/OwnedQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/OwnedQueryTestBase.cs @@ -119,11 +119,11 @@ public virtual Task Query_when_subquery(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Distinct() - .OrderBy(p => p.Id) - .Take(5) - .Select(op => new { op }), + .OrderBy(p => p.Id) + .Take(5) + .Select(op => new { op }), assertOrder: true, - elementAsserter: (e, a) => AssertEqual(e.op, a.op)); + elementAsserter: (e, a) => AssertEqual(e.op, a.op)); } [ConditionalTheory] @@ -162,7 +162,8 @@ public virtual Task Navigation_rewrite_on_owned_collection_with_composition(bool { return AssertQueryScalar( isAsync, - ss => ss.Set().OrderBy(p => p.Id).Select(p => p.Orders.OrderBy(o => o.Id).Select(o => o.Id != 42).FirstOrDefault())); + ss => ss.Set().OrderBy(p => p.Id) + .Select(p => p.Orders.OrderBy(o => o.Id).Select(o => o.Id != 42).FirstOrDefault())); } [ConditionalTheory] @@ -171,7 +172,8 @@ public virtual Task Navigation_rewrite_on_owned_collection_with_composition_comp { return AssertQuery( isAsync, - ss => ss.Set().Select(p => p.Orders.OrderBy(o => o.Id).Select(o => o.Client.PersonAddress.Country.Name).FirstOrDefault())); + ss => ss.Set().Select( + p => p.Orders.OrderBy(o => o.Id).Select(o => o.Client.PersonAddress.Country.Name).FirstOrDefault())); } [ConditionalTheory] @@ -209,7 +211,8 @@ public virtual Task Filter_owned_entity_chained_with_regular_entity_followed_by_ { return AssertQuery( isAsync, - ss => ss.Set().Where(p => p.PersonAddress.Country.Planet.Id != 42).OrderBy(p => p.Id).Select(p => new { p.Orders }), + ss => ss.Set().Where(p => p.PersonAddress.Country.Planet.Id != 42).OrderBy(p => p.Id) + .Select(p => new { p.Orders }), assertOrder: true, elementAsserter: (e, a) => AssertCollection(e.Orders, a.Orders)); } @@ -220,7 +223,8 @@ public virtual Task Project_multiple_owned_navigations(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().OrderBy(p => p.Id).Select(p => new { p.Orders, p.PersonAddress, p.PersonAddress.Country.Planet }), + ss => ss.Set().OrderBy(p => p.Id) + .Select(p => new { p.Orders, p.PersonAddress, p.PersonAddress.Country.Planet }), assertOrder: true, elementAsserter: (e, a) => { @@ -246,7 +250,7 @@ public virtual Task Project_multiple_owned_navigations_with_expansion_on_owned_c elementAsserter: (e, a) => { Assert.Equal(e.Count, a.Count); - AssertEqual(e.Planet, a.Planet); + AssertEqual(e.Planet, a.Planet); }); } @@ -329,7 +333,8 @@ public virtual Task Navigation_rewrite_on_owned_reference_followed_by_regular_en [ConditionalTheory] [MemberData(nameof(IsAsyncData))] - public virtual Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(bool isAsync) + public virtual Task + Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(bool isAsync) { return AssertQuery( isAsync, @@ -392,18 +397,10 @@ public virtual async Task Preserve_includes_when_applying_skip_take_after_anonym using (var context = CreateContext()) { var expectedQuery = Fixture.QueryAsserter.ExpectedData.Set().OrderBy(p => p.Id); - var expectedResult = expectedQuery.Select(q => new - { - Query = q, - Count = expectedQuery.Count() - }).Skip(0).Take(100).ToList(); + var expectedResult = expectedQuery.Select(q => new { Query = q, Count = expectedQuery.Count() }).Skip(0).Take(100).ToList(); var baseQuery = context.Set().OrderBy(p => p.Id); - var query = baseQuery.Select(q => new - { - Query = q, - Count = baseQuery.Count() - }).Skip(0).Take(100); + var query = baseQuery.Select(q => new { Query = q, Count = baseQuery.Count() }).Skip(0).Take(100); var result = isAsync ? await query.ToListAsync() @@ -467,8 +464,9 @@ public OwnedQueryFixtureBase() { typeof(OwnedAddress), e => e?.Country.Name }, { typeof(OwnedCountry), e => e?.Name }, { typeof(Element), e => e?.Id }, - { typeof(Throned), e => e?.Property }, - }.ToDictionary(e => e.Key, e => (object)e.Value); ; + { typeof(Throned), e => e?.Property } + }.ToDictionary(e => e.Key, e => (object)e.Value); + ; var entityAsserters = new Dictionary> { @@ -657,8 +655,9 @@ public OwnedQueryFixtureBase() Assert.Equal(e.Property, a.Property); } } - }, - }.ToDictionary(e => e.Key, e => (object)e.Value); ; + } + }.ToDictionary(e => e.Key, e => (object)e.Value); + ; QueryAsserter = new QueryAsserter( CreateContext, @@ -897,15 +896,16 @@ private static IReadOnlyList CreatePlanets() => new List { new Planet { Id = 1, StarId = 1 } }; private static IReadOnlyList CreateStars() - => new List { + => new List + { new Star { Id = 1, Name = "Sol", Composition = new List { - new Element { Id = "H", Name = "Hydrogen", StarId = 1, }, - new Element { Id = "He", Name = "Helium", StarId = 1, }, + new Element { Id = "H", Name = "Hydrogen", StarId = 1 }, + new Element { Id = "He", Name = "Helium", StarId = 1 } } } }; @@ -917,15 +917,14 @@ private static IReadOnlyList CreateOwnedPeople() { var ownedPerson1 = new OwnedPerson { - Id = 1, - PersonAddress = new OwnedAddress { Country = new OwnedCountry { Name = "USA", PlanetId = 1 } }, + Id = 1, PersonAddress = new OwnedAddress { Country = new OwnedCountry { Name = "USA", PlanetId = 1 } } }; var ownedPerson2 = new Branch { Id = 2, PersonAddress = new OwnedAddress { Country = new OwnedCountry { Name = "USA", PlanetId = 1 } }, - BranchAddress = new OwnedAddress { Country = new OwnedCountry { Name = "Canada", PlanetId = 1 } }, + BranchAddress = new OwnedAddress { Country = new OwnedCountry { Name = "Canada", PlanetId = 1 } } }; var ownedPerson3 = new LeafA @@ -933,17 +932,20 @@ private static IReadOnlyList CreateOwnedPeople() Id = 3, PersonAddress = new OwnedAddress { Country = new OwnedCountry { Name = "USA", PlanetId = 1 } }, BranchAddress = new OwnedAddress { Country = new OwnedCountry { Name = "Canada", PlanetId = 1 } }, - LeafAAddress = new OwnedAddress { Country = new OwnedCountry { Name = "Mexico", PlanetId = 1 } }, + LeafAAddress = new OwnedAddress { Country = new OwnedCountry { Name = "Mexico", PlanetId = 1 } } }; var ownedPerson4 = new LeafB { Id = 4, PersonAddress = new OwnedAddress { Country = new OwnedCountry { Name = "USA", PlanetId = 1 } }, - LeafBAddress = new OwnedAddress { Country = new OwnedCountry { Name = "Panama", PlanetId = 1 } }, + LeafBAddress = new OwnedAddress { Country = new OwnedCountry { Name = "Panama", PlanetId = 1 } } }; - ownedPerson1.Orders = new List { new Order { Id = -11, Client = ownedPerson1 }, new Order { Id = -10, Client = ownedPerson1 } }; + ownedPerson1.Orders = new List + { + new Order { Id = -11, Client = ownedPerson1 }, new Order { Id = -10, Client = ownedPerson1 } + }; ownedPerson2.Orders = new List { new Order { Id = -20, Client = ownedPerson2 } }; ownedPerson3.Orders = new List { new Order { Id = -30, Client = ownedPerson3 } }; ownedPerson4.Orders = new List { new Order { Id = -40, Client = ownedPerson4 } }; diff --git a/test/EFCore.Specification.Tests/Query/QueryNavigationsTestBase.cs b/test/EFCore.Specification.Tests/Query/QueryNavigationsTestBase.cs index bf2c842bafa..4cda2a9c454 100644 --- a/test/EFCore.Specification.Tests/Query/QueryNavigationsTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/QueryNavigationsTestBase.cs @@ -49,9 +49,11 @@ public virtual Task GroupJoin_with_nav_projected_in_subquery_when_client_eval(bo return AssertQuery( isAsync, ss => from c in ss.Set() - join o in ss.Set().Select(o => ClientProjection(o, o.Customer)) on c.CustomerID equals o.CustomerID into grouping + join o in ss.Set().Select(o => ClientProjection(o, o.Customer)) on c.CustomerID equals o.CustomerID into + grouping from o in grouping - join od in ss.Set().Select(od => ClientProjection(od, od.Product)) on o.OrderID equals od.OrderID into grouping2 + join od in ss.Set().Select(od => ClientProjection(od, od.Product)) on o.OrderID equals od.OrderID into + grouping2 from od in grouping2 select c, entryCount: 89); @@ -80,7 +82,8 @@ public virtual Task GroupJoin_with_nav_in_predicate_in_subquery_when_client_eval ss => from c in ss.Set() join o in ss.Set().Where(o => ClientPredicate(o, o.Customer)) on c.CustomerID equals o.CustomerID into grouping from o in grouping - join od in ss.Set().Where(od => ClientPredicate(od, od.Product)) on o.OrderID equals od.OrderID into grouping2 + join od in ss.Set().Where(od => ClientPredicate(od, od.Product)) on o.OrderID equals od.OrderID into + grouping2 from od in grouping2 select c, entryCount: 89); @@ -109,7 +112,8 @@ public virtual Task GroupJoin_with_nav_in_orderby_in_subquery_when_client_eval(b ss => from c in ss.Set() join o in ss.Set().OrderBy(o => ClientOrderBy(o, o.Customer)) on c.CustomerID equals o.CustomerID into grouping from o in grouping - join od in ss.Set().OrderBy(od => ClientOrderBy(od, od.Product)) on o.OrderID equals od.OrderID into grouping2 + join od in ss.Set().OrderBy(od => ClientOrderBy(od, od.Product)) on o.OrderID equals od.OrderID into + grouping2 from od in grouping2 select c, entryCount: 89); @@ -210,9 +214,9 @@ public virtual Task Select_Where_Navigation_Deep(bool isAsync) return AssertQuery( isAsync, ss => (from od in ss.Set() - where od.Order.Customer.City == "Seattle" - orderby od.OrderID, od.ProductID - select od).Take(1), + where od.Order.Customer.City == "Seattle" + orderby od.OrderID, od.ProductID + select od).Take(1), entryCount: 1); } @@ -233,7 +237,8 @@ public virtual Task Select_collection_FirstOrDefault_project_single_column1(bool { return AssertQuery( isAsync, - ss => ss.Set().OrderBy(c => c.CustomerID).Take(2).Select(c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault().CustomerID)); + ss => ss.Set().OrderBy(c => c.CustomerID).Take(2) + .Select(c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault().CustomerID)); } [ConditionalTheory] @@ -646,16 +651,10 @@ public virtual Task Collection_select_nav_prop_all_client(bool isAsync) isAsync, ss => from c in ss.Set() orderby c.CustomerID - select new - { - All = c.Orders.All(o => o.ShipCity == "London") - }, + select new { All = c.Orders.All(o => o.ShipCity == "London") }, ss => from c in ss.Set() orderby c.CustomerID - select new - { - All = (c.Orders ?? new List()).All(o => false) - }, + select new { All = (c.Orders ?? new List()).All(o => false) }, assertOrder: true)); } @@ -971,9 +970,9 @@ public virtual Task Navigation_from_join_clause_inside_contains(bool isAsync) return AssertQuery( isAsync, ss => from od in ss.Set() - join o in ss.Set() on od.OrderID equals o.OrderID - where new[] { "USA", "Redania" }.Contains(o.Customer.Country) - select od, + join o in ss.Set() on od.OrderID equals o.OrderID + where new[] { "USA", "Redania" }.Contains(o.Customer.Country) + select od, entryCount: 352); } @@ -985,8 +984,8 @@ public virtual Task Where_subquery_on_navigation(bool isAsync) isAsync, ss => from p in ss.Set() where p.OrderDetails.Contains( - ss.Set().OrderByDescending(o => o.OrderID).ThenBy(o => o.ProductID) - .FirstOrDefault(orderDetail => orderDetail.Quantity == 1)) + ss.Set().OrderByDescending(o => o.OrderID).ThenBy(o => o.ProductID) + .FirstOrDefault(orderDetail => orderDetail.Quantity == 1)) select p, entryCount: 1); } @@ -998,7 +997,8 @@ public virtual Task Where_subquery_on_navigation2(bool isAsync) return AssertQuery( isAsync, ss => from p in ss.Set() - where p.OrderDetails.Contains(ss.Set().OrderByDescending(o => o.OrderID).ThenBy(o => o.ProductID).FirstOrDefault()) + where p.OrderDetails.Contains( + ss.Set().OrderByDescending(o => o.OrderID).ThenBy(o => o.ProductID).FirstOrDefault()) select p, entryCount: 1); } @@ -1155,7 +1155,8 @@ orderby o.OrderID select new { o.OrderID, - OrderDetail = o.OrderDetails.OrderBy(od => od.OrderID).ThenBy(od => od.ProductID).Select(od => od.OrderID).FirstOrDefault(), + OrderDetail = o.OrderDetails.OrderBy(od => od.OrderID).ThenBy(od => od.ProductID).Select(od => od.OrderID) + .FirstOrDefault(), o.Customer.City }).Take(3), assertOrder: true); @@ -1173,7 +1174,7 @@ from od in ss.Set() join o in ss.Set() on od.OrderID equals 10260 join c2 in ss.Set() on o.CustomerID equals c2.CustomerID select c2 - on c.CustomerID equals subquery.CustomerID into result + on c.CustomerID equals subquery.CustomerID into result from subquery in result.DefaultIfEmpty() select c, entryCount: 91); @@ -1191,7 +1192,7 @@ from od in ss.Set() join o in ss.Set() on od.OrderID equals 10260 join c2 in ss.Set() on o.CustomerID equals c2.CustomerID select c2 - on c.CustomerID equals subquery.CustomerID into result + on c.CustomerID equals subquery.CustomerID into result from subquery in result.DefaultIfEmpty() select c.CustomerID); } @@ -1267,7 +1268,8 @@ public virtual Task Navigation_projection_on_groupjoin_qsre_with_empty_grouping( return AssertQuery( isAsync, ss => from c in ss.Set() - join o in ss.Set().Where(oo => !anatrsOrders.Contains(oo.OrderID)) on c.CustomerID equals o.CustomerID into grouping + join o in ss.Set().Where(oo => !anatrsOrders.Contains(oo.OrderID)) on c.CustomerID equals o.CustomerID into + grouping where c.CustomerID.StartsWith("A") select new { c, G = grouping.Select(o => o.OrderDetails).ToList() }, elementSorter: e => e.c.CustomerID, diff --git a/test/EFCore.Specification.Tests/Query/QueryTestBase.cs b/test/EFCore.Specification.Tests/Query/QueryTestBase.cs index 320bb07400e..2bc3761114d 100644 --- a/test/EFCore.Specification.Tests/Query/QueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/QueryTestBase.cs @@ -137,7 +137,8 @@ protected Task AssertSingleResult( Action asserter = null, int entryCount = 0, [CallerMemberName] string testMethodName = null) - => Fixture.QueryAsserter.AssertSingleResultTyped(actualSyncQuery, actualAsyncQuery, expectedQuery, asserter, entryCount, isAsync, testMethodName); + => Fixture.QueryAsserter.AssertSingleResultTyped( + actualSyncQuery, actualAsyncQuery, expectedQuery, asserter, entryCount, isAsync, testMethodName); #region Assert termination operation methods diff --git a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Functions.cs b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Functions.cs index 5c27dc00ef1..181ce29d9f3 100644 --- a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Functions.cs +++ b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Functions.cs @@ -310,12 +310,14 @@ public virtual async Task String_Compare_multi_predicate(bool isAsync) { await AssertQuery( isAsync, - ss => ss.Set().Where(c => string.Compare(c.CustomerID, "ALFKI") > -1).Where(c => string.Compare(c.CustomerID, "CACTU") == -1), + ss => ss.Set().Where(c => string.Compare(c.CustomerID, "ALFKI") > -1) + .Where(c => string.Compare(c.CustomerID, "CACTU") == -1), entryCount: 11); await AssertQuery( isAsync, - ss => ss.Set().Where(c => string.Compare(c.ContactTitle, "Owner") == 0).Where(c => string.Compare(c.Country, "USA") != 0), + ss => ss.Set().Where(c => string.Compare(c.ContactTitle, "Owner") == 0) + .Where(c => string.Compare(c.Country, "USA") != 0), entryCount: 15); } @@ -964,7 +966,8 @@ public virtual Task Where_math_min(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(od => od.OrderID == 11077).Where(od => Math.Min(od.OrderID, od.ProductID) == od.ProductID), + ss => ss.Set().Where(od => od.OrderID == 11077) + .Where(od => Math.Min(od.OrderID, od.ProductID) == od.ProductID), entryCount: 25); } @@ -1253,7 +1256,8 @@ public virtual Task Substring_with_Index_of(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(c => c.CustomerID == "ALFKI").Select(c => c.ContactName.Substring(c.ContactName.IndexOf("a"), 3))); + ss => ss.Set().Where(c => c.CustomerID == "ALFKI") + .Select(c => c.ContactName.Substring(c.ContactName.IndexOf("a"), 3))); } [ConditionalTheory] @@ -1411,7 +1415,8 @@ public virtual Task Order_by_length_twice_followed_by_projection_of_naked_collec { return AssertQuery( isAsync, - ss => ss.Set().OrderBy(c => c.CustomerID.Length).ThenBy(c => c.CustomerID.Length).ThenBy(c => c.CustomerID).Select(c => c.Orders), + ss => ss.Set().OrderBy(c => c.CustomerID.Length).ThenBy(c => c.CustomerID.Length).ThenBy(c => c.CustomerID) + .Select(c => c.Orders), assertOrder: true, elementAsserter: (e, a) => AssertCollection(e, a), entryCount: 830); @@ -1456,7 +1461,8 @@ public virtual Task Projecting_Math_Truncate_and_ordering_by_it_twice(bool isAsy { return AssertQuery( isAsync, - ss => ss.Set().Where(o => o.OrderID < 10250).Select(o => new { A = Math.Truncate((double)o.OrderID) }).OrderBy(r => r.A) + ss => ss.Set().Where(o => o.OrderID < 10250).Select(o => new { A = Math.Truncate((double)o.OrderID) }) + .OrderBy(r => r.A) .OrderBy(r => r.A), assertOrder: true); } @@ -1467,7 +1473,8 @@ public virtual Task Projecting_Math_Truncate_and_ordering_by_it_twice2(bool isAs { return AssertQuery( isAsync, - ss => ss.Set().Where(o => o.OrderID < 10250).Select(o => new { A = Math.Truncate((double)o.OrderID) }).OrderBy(r => r.A) + ss => ss.Set().Where(o => o.OrderID < 10250).Select(o => new { A = Math.Truncate((double)o.OrderID) }) + .OrderBy(r => r.A) .OrderByDescending(r => r.A), assertOrder: true); } @@ -1478,7 +1485,8 @@ public virtual Task Projecting_Math_Truncate_and_ordering_by_it_twice3(bool isAs { return AssertQuery( isAsync, - ss => ss.Set().Where(o => o.OrderID < 10250).Select(o => new { A = Math.Truncate((double)o.OrderID) }).OrderByDescending(r => r.A) + ss => ss.Set().Where(o => o.OrderID < 10250).Select(o => new { A = Math.Truncate((double)o.OrderID) }) + .OrderByDescending(r => r.A) .ThenBy(r => r.A), assertOrder: true); } diff --git a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.JoinGroupJoin.cs b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.JoinGroupJoin.cs index bb6430569d6..23c21065206 100644 --- a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.JoinGroupJoin.cs +++ b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.JoinGroupJoin.cs @@ -187,7 +187,8 @@ public virtual Task Join_customers_orders_with_subquery_predicate_with_take(bool ss => from c in ss.Set() join o1 in - (from o2 in ss.Set() where o2.OrderID > 0 orderby o2.OrderID select o2).Take(5) on c.CustomerID equals o1.CustomerID + (from o2 in ss.Set() where o2.OrderID > 0 orderby o2.OrderID select o2).Take(5) on c.CustomerID equals o1 + .CustomerID where o1.CustomerID == "ALFKI" select new { c.ContactName, o1.OrderID }, e => e.OrderID); @@ -300,7 +301,7 @@ public virtual Task Join_same_collection_multiple(bool isAsync) isAsync, ss => ss.Set().Join( ss.Set(), o => o.CustomerID, i => i.CustomerID, (c1, c2) => new { c1, c2 }).Join( - ss.Set(), o => o.c1.CustomerID, i => i.CustomerID, (c12, c3) => c3), + ss.Set(), o => o.c1.CustomerID, i => i.CustomerID, (c12, c3) => c3), entryCount: 91); } @@ -585,7 +586,8 @@ public virtual Task GroupJoin_outer_projection4(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().GroupJoin(ss.Set(), c => c.CustomerID, o => o.CustomerID, (c, g) => g.Select(o => o.CustomerID)), + ss => ss.Set().GroupJoin( + ss.Set(), c => c.CustomerID, o => o.CustomerID, (c, g) => g.Select(o => o.CustomerID)), elementSorter: e => e.Count(), elementAsserter: (e, a) => AssertCollection(e, a)); } diff --git a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.KeylessEntities.cs b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.KeylessEntities.cs index 38fe975a824..c21b4221bc2 100644 --- a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.KeylessEntities.cs +++ b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.KeylessEntities.cs @@ -156,8 +156,8 @@ public virtual Task KeylessEntity_select_where_navigation(bool isAsync) return AssertQuery( isAsync, ss => from ov in ss.Set() - where ov.Customer.City == "Seattle" - select ov); + where ov.Customer.City == "Seattle" + select ov); } [ConditionalTheory] @@ -167,8 +167,8 @@ public virtual Task KeylessEntity_select_where_navigation_multi_level(bool isAsy return AssertQuery( isAsync, ss => from ov in ss.Set() - where ov.Customer.Orders.Any() - select ov); + where ov.Customer.Orders.Any() + select ov); } } } diff --git a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.ResultOperators.cs b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.ResultOperators.cs index 90c86bbab78..c8921192b12 100644 --- a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.ResultOperators.cs +++ b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.ResultOperators.cs @@ -160,7 +160,7 @@ public virtual Task Sum_with_division_on_decimal(bool isAsync) isAsync, ss => ss.Set(), selector: od => od.Quantity / 2.09m, - asserter: (e, a) => Assert.InRange((decimal)e - (decimal)a, -0.1m, 0.1m)); + asserter: (e, a) => Assert.InRange(e - a, -0.1m, 0.1m)); } [ConditionalTheory] @@ -171,7 +171,7 @@ public virtual Task Sum_with_division_on_decimal_no_significant_digits(bool isAs isAsync, ss => ss.Set(), selector: od => od.Quantity / 2m, - asserter: (e, a) => Assert.InRange((decimal)e - (decimal)a, -0.1m, 0.1m)); + asserter: (e, a) => Assert.InRange(e - a, -0.1m, 0.1m)); } [ConditionalTheory] @@ -281,7 +281,7 @@ public virtual Task Average_with_division_on_decimal(bool isAsync) isAsync, ss => ss.Set(), selector: od => od.Quantity / 2.09m, - asserter: (e, a) => Assert.InRange((decimal)e - (decimal)a, -0.1m, 0.1m)); + asserter: (e, a) => Assert.InRange(e - a, -0.1m, 0.1m)); } [ConditionalTheory] @@ -292,7 +292,7 @@ public virtual Task Average_with_division_on_decimal_no_significant_digits(bool isAsync, ss => ss.Set(), selector: od => od.Quantity / 2m, - asserter: (e, a) => Assert.InRange((decimal)e - (decimal)a, -0.1m, 0.1m)); + asserter: (e, a) => Assert.InRange(e - a, -0.1m, 0.1m)); } [ConditionalTheory] @@ -303,7 +303,7 @@ public virtual Task Average_with_coalesce(bool isAsync) isAsync, ss => ss.Set().Where(p => p.ProductID < 40), selector: p => p.UnitPrice ?? 0, - asserter: (e, a) => Assert.InRange((decimal)e - (decimal)a, -0.1m, 0.1m)); + asserter: (e, a) => Assert.InRange(e - a, -0.1m, 0.1m)); } [ConditionalTheory(Skip = "Issue #15937")] @@ -1008,7 +1008,8 @@ public virtual Task First_inside_subquery_gets_client_evaluated(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(c => c.CustomerID == "ALFKI" && c.Orders.Where(o => o.CustomerID == "ALFKI").First().CustomerID == "ALFKI"), + ss => ss.Set().Where( + c => c.CustomerID == "ALFKI" && c.Orders.Where(o => o.CustomerID == "ALFKI").First().CustomerID == "ALFKI"), entryCount: 1); } @@ -1285,7 +1286,8 @@ public virtual Task Contains_with_local_collection_complex_predicate_and(bool is return AssertQuery( isAsync, - ss => ss.Set().Where(c => (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE") && ids.Contains(c.CustomerID)), entryCount: 1); + ss => ss.Set().Where(c => (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE") && ids.Contains(c.CustomerID)), + entryCount: 1); } [ConditionalTheory] @@ -1296,7 +1298,8 @@ public virtual Task Contains_with_local_collection_complex_predicate_or(bool isA return AssertQuery( isAsync, - ss => ss.Set().Where(c => ids.Contains(c.CustomerID) || (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE")), entryCount: 1); + ss => ss.Set().Where(c => ids.Contains(c.CustomerID) || (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE")), + entryCount: 1); } [ConditionalTheory] @@ -1307,7 +1310,8 @@ public virtual Task Contains_with_local_collection_complex_predicate_not_matchin return AssertQuery( isAsync, - ss => ss.Set().Where(c => (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE") || !ids.Contains(c.CustomerID)), entryCount: 91); + ss => ss.Set().Where(c => (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE") || !ids.Contains(c.CustomerID)), + entryCount: 91); } [ConditionalTheory] @@ -1329,7 +1333,8 @@ public virtual Task Contains_with_local_collection_sql_injection(bool isAsync) return AssertQuery( isAsync, - ss => ss.Set().Where(c => ids.Contains(c.CustomerID) || (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE")), entryCount: 1); + ss => ss.Set().Where(c => ids.Contains(c.CustomerID) || (c.CustomerID == "ALFKI" || c.CustomerID == "ABCDE")), + entryCount: 1); } [ConditionalTheory] @@ -1510,7 +1515,7 @@ public virtual Task List_Contains_with_constant_list(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Where( - c => new List { new Customer { CustomerID = "ALFKI" }, new Customer { CustomerID = "ANATR" } }.Contains(c)), + c => new List { new Customer { CustomerID = "ALFKI" }, new Customer { CustomerID = "ANATR" } }.Contains(c)), entryCount: 2); } @@ -1544,7 +1549,8 @@ public virtual Task Contains_with_constant_list_value_type_id(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(o => new List { new Order { OrderID = 10248 }, new Order { OrderID = 10249 } }.Contains(o)), + ss => ss.Set().Where( + o => new List { new Order { OrderID = 10248 }, new Order { OrderID = 10249 } }.Contains(o)), entryCount: 2); } @@ -1588,7 +1594,8 @@ public virtual void Paging_operation_on_string_doesnt_issue_warning() { using (var context = CreateContext()) { - var message = Assert.Throws(() => context.Customers.Select(c => c.CustomerID.FirstOrDefault()).ToList()).Message; + var message = Assert + .Throws(() => context.Customers.Select(c => c.CustomerID.FirstOrDefault()).ToList()).Message; Assert.Equal( CoreStrings.QueryFailed( @@ -1597,7 +1604,7 @@ public virtual void Paging_operation_on_string_doesnt_issue_warning() Expression: c).CustomerID .AsQueryable()", "NavigationExpandingExpressionVisitor"), - message); + message); } } @@ -1767,9 +1774,10 @@ public virtual Task Collection_Last_member_access_in_projection_translated(bool ss => ss.Set().Where(c => c.CustomerID.StartsWith("F")) .Where(c => c.Orders.OrderByDescending(o => o.OrderID).Last().CustomerID == c.CustomerID), ss => ss.Set().Where(c => c.CustomerID.StartsWith("F")) - .Where(c => Maybe( - c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault(), - () => c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault().CustomerID) == c.CustomerID), + .Where( + c => Maybe( + c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault(), + () => c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault().CustomerID) == c.CustomerID), entryCount: 7); } @@ -1782,9 +1790,10 @@ public virtual Task Collection_LastOrDefault_member_access_in_projection_transla ss => ss.Set().Where(c => c.CustomerID.StartsWith("F")) .Where(c => c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault().CustomerID == c.CustomerID), ss => ss.Set().Where(c => c.CustomerID.StartsWith("F")) - .Where(c => Maybe( - c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault(), - () => c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault().CustomerID) == c.CustomerID), + .Where( + c => Maybe( + c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault(), + () => c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault().CustomerID) == c.CustomerID), entryCount: 7); } diff --git a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Select.cs b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Select.cs index e60be56eb90..07138a18eea 100644 --- a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Select.cs +++ b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Select.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.TestModels.Northwind; using Xunit; @@ -780,7 +779,8 @@ public virtual Task Project_single_element_from_collection_with_OrderBy_Distinct { return AssertQuery( isAsync, - ss => ss.Set().Select(c => c.Orders.OrderBy(o => o.OrderID).Select(o => o.CustomerID).Distinct().FirstOrDefault())); + ss => ss.Set() + .Select(c => c.Orders.OrderBy(o => o.OrderID).Select(o => o.CustomerID).Distinct().FirstOrDefault())); } [ConditionalTheory] @@ -1238,7 +1238,8 @@ public virtual Task Project_non_nullable_value_after_FirstOrDefault_on_empty_col { return AssertQueryScalar( isAsync, - ss => ss.Set().Select(c => ss.Set().Where(o => o.CustomerID == "John Doe").Select(o => o.CustomerID).FirstOrDefault().Length), + ss => ss.Set().Select( + c => ss.Set().Where(o => o.CustomerID == "John Doe").Select(o => o.CustomerID).FirstOrDefault().Length), ss => ss.Set().Select(c => 0)); } @@ -1265,10 +1266,10 @@ public CustomerListItem(string id, string city) public override bool Equals(object obj) => obj != null - && (ReferenceEquals(this, obj) - || obj is CustomerListItem customerListItem - && Id == customerListItem.Id - && City == customerListItem.City); + && (ReferenceEquals(this, obj) + || obj is CustomerListItem customerListItem + && Id == customerListItem.Id + && City == customerListItem.City); public override int GetHashCode() => HashCode.Combine(Id, City); } @@ -1281,12 +1282,9 @@ public virtual async Task Filtered_collection_projection_is_tracked(bool isAsync { var query = context.Customers .Where(c => c.CustomerID.StartsWith("A")) - .Select(c => - new - { - Customer = c, - FilteredOrders = c.Orders.Where(o => o.OrderID > 11000) - }); + .Select( + c => + new { Customer = c, FilteredOrders = c.Orders.Where(o => o.OrderID > 11000) }); var result = isAsync ? (await query.ToListAsync()) @@ -1306,12 +1304,9 @@ public virtual async Task Filtered_collection_projection_with_to_list_is_tracked { var query = context.Customers .Where(c => c.CustomerID.StartsWith("A")) - .Select(c => - new - { - Customer = c, - FilteredOrders = c.Orders.Where(o => o.OrderID > 11000).ToList() - }); + .Select( + c => + new { Customer = c, FilteredOrders = c.Orders.Where(o => o.OrderID > 11000).ToList() }); var result = isAsync ? (await query.ToListAsync()) @@ -1329,16 +1324,20 @@ public virtual Task SelectMany_with_collection_being_correlated_subquery_which_r { return AssertQuery( isAsync, - ss => ss.Set().SelectMany(c => c.Orders.Select(o => new { OrderProperty = o.CustomerID, CustomerProperty = c.CustomerID }))); + ss => ss.Set().SelectMany( + c => c.Orders.Select(o => new { OrderProperty = o.CustomerID, CustomerProperty = c.CustomerID }))); } [ConditionalTheory(Skip = "issue #17763")] [MemberData(nameof(IsAsyncData))] - public virtual Task SelectMany_with_collection_being_correlated_subquery_which_references_non_mapped_properties_from_inner_and_outer_entity(bool isAsync) + public virtual Task + SelectMany_with_collection_being_correlated_subquery_which_references_non_mapped_properties_from_inner_and_outer_entity( + bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().SelectMany(c => c.Orders.Select(o => new { OrderProperty = o.ShipName, CustomerProperty = c.ContactName }))); + ss => ss.Set().SelectMany( + c => c.Orders.Select(o => new { OrderProperty = o.ShipName, CustomerProperty = c.ContactName }))); } [ConditionalTheory] @@ -1405,10 +1404,8 @@ public virtual Task Collection_FirstOrDefault_with_entity_equality_check_in_proj { return AssertQuery( isAsync, - ss => ss.Set().Select(c => new - { - Order = (c.Orders.Any() ? c.Orders.FirstOrDefault() : null) == null ? null : new Order { } - })); + ss => ss.Set().Select( + c => new { Order = (c.Orders.Any() ? c.Orders.FirstOrDefault() : null) == null ? null : new Order() })); } [ConditionalTheory] @@ -1427,11 +1424,7 @@ public virtual Task ToList_Count_in_projection_works(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Where(c => c.CustomerID.StartsWith("A")) - .Select(c => new - { - c, - Count = c.Orders.ToList().Count() - }), + .Select(c => new { c, Count = c.Orders.ToList().Count() }), entryCount: 4, elementSorter: r => r.c.CustomerID, elementAsserter: (e, a) => @@ -1448,11 +1441,7 @@ public virtual Task LastOrDefault_member_access_in_projection_translates_to_serv return AssertQuery( isAsync, ss => ss.Set().Where(c => c.CustomerID.StartsWith("A")) - .Select(c => new - { - c, - c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault().OrderDate - }), + .Select(c => new { c, c.Orders.OrderByDescending(o => o.OrderID).LastOrDefault().OrderDate }), entryCount: 4); } } diff --git a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.SetOperations.cs b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.SetOperations.cs index 1e5b9f88af2..c874ec14f1f 100644 --- a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.SetOperations.cs +++ b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.SetOperations.cs @@ -43,9 +43,10 @@ public virtual Task Concat_non_entity(bool isAsync) isAsync, ss => ss.Set() .Where(c => c.City == "México D.F.") .Select(c => c.CustomerID) - .Concat(ss.Set() - .Where(s => s.ContactTitle == "Owner") - .Select(c => c.CustomerID))); + .Concat( + ss.Set() + .Where(s => s.ContactTitle == "Owner") + .Select(c => c.CustomerID))); } [ConditionalTheory] @@ -89,9 +90,10 @@ public virtual Task Except_non_entity(bool isAsync) isAsync, ss => ss.Set() .Where(s => s.ContactTitle == "Owner") .Select(c => c.CustomerID) - .Except(ss.Set() - .Where(c => c.City == "México D.F.") - .Select(c => c.CustomerID))); + .Except( + ss.Set() + .Where(c => c.City == "México D.F.") + .Select(c => c.CustomerID))); } [ConditionalTheory] @@ -125,9 +127,10 @@ public virtual Task Intersect_non_entity(bool isAsync) isAsync, ss => ss.Set() .Where(c => c.City == "México D.F.") .Select(c => c.CustomerID) - .Intersect(ss.Set() - .Where(s => s.ContactTitle == "Owner") - .Select(c => c.CustomerID))); + .Intersect( + ss.Set() + .Where(s => s.ContactTitle == "Owner") + .Select(c => c.CustomerID))); } [ConditionalTheory] @@ -161,9 +164,10 @@ public virtual Task Union_non_entity(bool isAsync) isAsync, ss => ss.Set() .Where(s => s.ContactTitle == "Owner") .Select(c => c.CustomerID) - .Union(ss.Set() - .Where(c => c.City == "México D.F.") - .Select(c => c.CustomerID))); + .Union( + ss.Set() + .Where(c => c.City == "México D.F.") + .Select(c => c.CustomerID))); } // OrderBy, Skip and Take are typically supported on the set operation itself (no need for query pushdown) @@ -262,9 +266,10 @@ public virtual Task Select_Union(bool isAsync) isAsync, ss => ss.Set() .Where(c => c.City == "Berlin") .Select(c => c.Address) - .Union(ss.Set() - .Where(c => c.City == "London") - .Select(c => c.Address))); + .Union( + ss.Set() + .Where(c => c.City == "London") + .Select(c => c.Address))); } [ConditionalTheory] @@ -322,9 +327,10 @@ public virtual Task Select_Union_different_fields_in_anonymous_with_subquery(boo isAsync, ss => ss.Set() .Where(c => c.City == "Berlin") .Select(c => new { Foo = c.City, Customer = c }) // Foo is City - .Union(ss.Set() - .Where(c => c.City == "London") - .Select(c => new { Foo = c.Region, Customer = c })) // Foo is Region + .Union( + ss.Set() + .Where(c => c.City == "London") + .Select(c => new { Foo = c.Region, Customer = c })) // Foo is Region .OrderBy(x => x.Foo) .Skip(1) .Take(10) @@ -352,9 +358,10 @@ public virtual Task Include_Union(bool isAsync) isAsync, ss => ss.Set() .Where(c => c.City == "Berlin") .Include(c => c.Orders) - .Union(ss.Set() - .Where(c => c.City == "London") - .Include(c => c.Orders)), + .Union( + ss.Set() + .Where(c => c.City == "London") + .Include(c => c.Orders)), entryCount: 59); } @@ -365,9 +372,10 @@ public virtual Task Select_Except_reference_projection(bool isAsync) return AssertQuery( isAsync, ss => ss.Set() .Select(o => o.Customer) - .Except(ss.Set() - .Where(o => o.CustomerID == "ALFKI") - .Select(o => o.Customer)), + .Except( + ss.Set() + .Where(o => o.CustomerID == "ALFKI") + .Select(o => o.Customer)), entryCount: 88); } @@ -423,8 +431,9 @@ public virtual Task SubSelect_Union(bool isAsync) isAsync, ss => ss.Set() .Select(c => new { Customer = c, Orders = c.Orders.Count }) - .Union(ss.Set() - .Select(c => new { Customer = c, Orders = c.Orders.Count })), + .Union( + ss.Set() + .Select(c => new { Customer = c, Orders = c.Orders.Count })), entryCount: 91); } @@ -448,10 +457,11 @@ public virtual Task GroupBy_Select_Union(bool isAsync) .Where(c => c.City == "Berlin") .GroupBy(c => c.CustomerID) .Select(g => new { CustomerID = g.Key, Count = g.Count() }) - .Union(ss.Set() - .Where(c => c.City == "London") - .GroupBy(c => c.CustomerID) - .Select(g => new { CustomerID = g.Key, Count = g.Count() }))); + .Union( + ss.Set() + .Where(c => c.City == "London") + .GroupBy(c => c.CustomerID) + .Select(g => new { CustomerID = g.Key, Count = g.Count() }))); } [ConditionalTheory] @@ -461,8 +471,9 @@ public virtual Task Union_over_columns_with_different_nullability(bool isAsync) return AssertQuery( isAsync, ss => ss.Set() .Select(c => "NonNullableConstant") - .Concat(ss.Set() - .Select(c => (string)null))); + .Concat( + ss.Set() + .Select(c => (string)null))); } [ConditionalTheory] @@ -518,9 +529,10 @@ public virtual Task OrderBy_Take_Union(bool isAsync) isAsync, ss => ss.Set() .OrderBy(c => c.ContactName) .Take(1) - .Union(ss.Set() - .OrderBy(c => c.ContactName) - .Take(1)), + .Union( + ss.Set() + .OrderBy(c => c.ContactName) + .Take(1)), entryCount: 1, assertOrder: true); } diff --git a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Where.cs b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Where.cs index a3e665316e6..b9fe00d19ac 100644 --- a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Where.cs +++ b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.Where.cs @@ -6,9 +6,9 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.TestModels.Northwind; using Xunit; +// ReSharper disable RedundantBoolCompare namespace Microsoft.EntityFrameworkCore.Query { @@ -574,7 +574,8 @@ public virtual Task Where_shadow_subquery_FirstOrDefault(bool isAsync) isAsync, ss => from e in ss.Set() where EF.Property(e, "Title") - == EF.Property(ss.Set().OrderBy(e2 => EF.Property(e2, "Title")).FirstOrDefault(), "Title") + == EF.Property( + ss.Set().OrderBy(e2 => EF.Property(e2, "Title")).FirstOrDefault(), "Title") select e, entryCount: 1); } @@ -1175,7 +1176,7 @@ public virtual Task Where_select_many_and(bool isAsync) ss => from c in ss.Set() from e in ss.Set() - // ReSharper disable ArrangeRedundantParentheses + // ReSharper disable ArrangeRedundantParentheses #pragma warning disable RCS1032 // Remove redundant parentheses. where (c.City == "London" && c.Country == "UK") && (e.City == "London" && e.Country == "UK") @@ -1652,7 +1653,9 @@ public virtual Task Where_compare_constructed_equal(bool isAsync) c => new { x = c.City } == new { x = "London" })); } - [ConditionalTheory(Skip = "Issue #14672. Cannot eval 'where (new <>f__AnonymousType410`2(x = [c].City, y = [c].Country) == { x = London, y = UK })'")] + [ConditionalTheory( + Skip = + "Issue #14672. Cannot eval 'where (new <>f__AnonymousType410`2(x = [c].City, y = [c].Country) == { x = London, y = UK })'")] [MemberData(nameof(IsAsyncData))] public virtual Task Where_compare_constructed_multi_value_equal(bool isAsync) { @@ -1662,7 +1665,9 @@ public virtual Task Where_compare_constructed_multi_value_equal(bool isAsync) c => new { x = c.City, y = c.Country } == new { x = "London", y = "UK" })); } - [ConditionalTheory(Skip = "Issue #14672. Cannot eval 'where (new <>f__AnonymousType410`2(x = [c].City, y = [c].Country) != { x = London, y = UK })'")] + [ConditionalTheory( + Skip = + "Issue #14672. Cannot eval 'where (new <>f__AnonymousType410`2(x = [c].City, y = [c].Country) != { x = London, y = UK })'")] [MemberData(nameof(IsAsyncData))] public virtual Task Where_compare_constructed_multi_value_not_equal(bool isAsync) { @@ -1688,7 +1693,8 @@ public virtual Task Where_compare_tuple_constructed_multi_value_equal(bool isAsy { return AssertQuery( isAsync, - ss => ss.Set().Where(c => new Tuple(c.City, c.Country) == new Tuple("London", "UK"))); + ss => ss.Set().Where( + c => new Tuple(c.City, c.Country) == new Tuple("London", "UK"))); } [ConditionalTheory(Skip = "Issue #14672. Cannot eval 'where (new Tuple`2(Item1 = [c].City, Item2 = [c].Country) != (London, UK))'")] @@ -1697,7 +1703,8 @@ public virtual Task Where_compare_tuple_constructed_multi_value_not_equal(bool i { return AssertQuery( isAsync, - ss => ss.Set().Where(c => new Tuple(c.City, c.Country) != new Tuple("London", "UK")), + ss => ss.Set().Where( + c => new Tuple(c.City, c.Country) != new Tuple("London", "UK")), entryCount: 91); } @@ -1801,7 +1808,7 @@ public virtual Task Where_multiple_contains_in_subquery_with_or(bool isAsync) isAsync, ss => ss.Set().Where( od => ss.Set().OrderBy(p => p.ProductID).Take(1).Select(p => p.ProductID).Contains(od.ProductID) - || ss.Set().OrderBy(o => o.OrderID).Take(1).Select(o => o.OrderID).Contains(od.OrderID)), + || ss.Set().OrderBy(o => o.OrderID).Take(1).Select(o => o.OrderID).Contains(od.OrderID)), entryCount: 41); } @@ -1813,7 +1820,7 @@ public virtual Task Where_multiple_contains_in_subquery_with_and(bool isAsync) isAsync, ss => ss.Set().Where( od => ss.Set().OrderBy(p => p.ProductID).Take(20).Select(p => p.ProductID).Contains(od.ProductID) - && ss.Set().OrderBy(o => o.OrderID).Take(10).Select(o => o.OrderID).Contains(od.OrderID)), + && ss.Set().OrderBy(o => o.OrderID).Take(10).Select(o => o.OrderID).Contains(od.OrderID)), entryCount: 5); } @@ -1931,10 +1938,7 @@ public virtual Task Enclosing_class_const_member_does_not_generate_parameter(boo [MemberData(nameof(IsAsyncData))] public virtual Task Generic_Ilist_contains_translates_to_server(bool isAsync) { - var cities = new List - { - "Seattle" - } as IList; + var cities = new List { "Seattle" } as IList; return AssertQuery( isAsync, @@ -1952,7 +1956,8 @@ public virtual Task Filter_non_nullable_value_after_FirstOrDefault_on_empty_coll { return AssertQuery( isAsync, - ss => ss.Set().Where(c => ss.Set().Where(o => o.CustomerID == "John Doe").Select(o => o.CustomerID).FirstOrDefault().Length == 0), + ss => ss.Set().Where( + c => ss.Set().Where(o => o.CustomerID == "John Doe").Select(o => o.CustomerID).FirstOrDefault().Length == 0), ss => ss.Set().Where(c => false)); } diff --git a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.cs index 94c571c43b7..52671198d32 100644 --- a/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/SimpleQueryTestBase.cs @@ -1127,8 +1127,10 @@ public virtual Task All_top_level_subquery(bool isAsync) { return AssertSingleResult( isAsync, - syncQuery: ss => ss.Set().All(c1 => ss.Set().Any(c2 => ss.Set().Any(c3 => c1.CustomerID == c3.CustomerID))), - asyncQuery: ss => ss.Set().AllAsync(c1 => ss.Set().Any(c2 => ss.Set().Any(c3 => c1.CustomerID == c3.CustomerID)))); + syncQuery: ss => ss.Set().All( + c1 => ss.Set().Any(c2 => ss.Set().Any(c3 => c1.CustomerID == c3.CustomerID))), + asyncQuery: ss => ss.Set().AllAsync( + c1 => ss.Set().Any(c2 => ss.Set().Any(c3 => c1.CustomerID == c3.CustomerID)))); } [ConditionalTheory] @@ -1137,8 +1139,12 @@ public virtual Task All_top_level_subquery_ef_property(bool isAsync) { return AssertSingleResult( isAsync, - syncQuery: ss => ss.Set().All(c1 => ss.Set().Any(c2 => ss.Set().Any(c3 => EF.Property(c1, "CustomerID") == c3.CustomerID))), - asyncQuery: ss => ss.Set().AllAsync(c1 => ss.Set().Any(c2 => ss.Set().Any(c3 => EF.Property(c1, "CustomerID") == c3.CustomerID)))); + syncQuery: ss => ss.Set().All( + c1 => ss.Set().Any( + c2 => ss.Set().Any(c3 => EF.Property(c1, "CustomerID") == c3.CustomerID))), + asyncQuery: ss => ss.Set().AllAsync( + c1 => ss.Set().Any( + c2 => ss.Set().Any(c3 => EF.Property(c1, "CustomerID") == c3.CustomerID)))); } [ConditionalTheory] @@ -1264,8 +1270,8 @@ public virtual Task Take_with_single_select_many(bool isAsync) from o in ss.Set() orderby c.CustomerID, o.OrderID select new { c, o }) - .Take(1) - .Cast(), + .Take(1) + .Cast(), entryCount: 2); } @@ -1302,7 +1308,7 @@ from e in ss.Set() where c.City == "London" || e.City == "London" select new { c, e }, - e => (e.c.CustomerID, + e.e.EmployeeID), + e => (e.c.CustomerID, +e.e.EmployeeID), entryCount: 100); } @@ -2179,7 +2185,7 @@ public virtual Task SelectMany_projection1(bool isAsync) ss => from e1 in ss.Set() from e2 in ss.Set() select new { e1.City, e2.Country }, - e => (e.City,e.Country)); + e => (e.City, e.Country)); } [ConditionalTheory] @@ -2321,7 +2327,8 @@ public virtual Task Where_Join_Any(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(c => c.CustomerID == "ALFKI" && c.Orders.Any(o => o.OrderDate == new DateTime(2008, 10, 24)))); + ss => ss.Set().Where( + c => c.CustomerID == "ALFKI" && c.Orders.Any(o => o.OrderDate == new DateTime(2008, 10, 24)))); } [ConditionalTheory(Skip = "Issue#17762")] @@ -2330,7 +2337,8 @@ public virtual Task Where_Join_Exists(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(c => c.CustomerID == "ALFKI" && c.Orders.Exists(o => o.OrderDate == new DateTime(2008, 10, 24)))); + ss => ss.Set().Where( + c => c.CustomerID == "ALFKI" && c.Orders.Exists(o => o.OrderDate == new DateTime(2008, 10, 24)))); } [ConditionalTheory(Skip = "Issue#17762")] @@ -2339,7 +2347,8 @@ public virtual Task Where_Join_Exists_Inequality(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Where(c => c.CustomerID == "ALFKI" && c.Orders.Exists(o => o.OrderDate != new DateTime(2008, 10, 24))), + ss => ss.Set().Where( + c => c.CustomerID == "ALFKI" && c.Orders.Exists(o => o.OrderDate != new DateTime(2008, 10, 24))), entryCount: 1); } @@ -2483,8 +2492,8 @@ public virtual Task Join_with_default_if_empty_on_both_sources(bool isAsync) isAsync, ss => (from e in ss.Set().Where(c => c.EmployeeID == NonExistentID).DefaultIfEmpty() select e).Join( - from e in ss.Set().Where(c => c.EmployeeID == NonExistentID).DefaultIfEmpty() - select e, o => o, i => i, (o, i) => o)); + from e in ss.Set().Where(c => c.EmployeeID == NonExistentID).DefaultIfEmpty() + select e, o => o, i => i, (o, i) => o)); } [ConditionalTheory] @@ -2514,7 +2523,7 @@ public virtual async Task Default_if_empty_top_level_arg(bool isAsync) .Where(c => c.EmployeeID == 4294967295) .DefaultIfEmpty(__p_0)", "NavigationExpandingExpressionVisitor"), - message); + message); } [ConditionalTheory] @@ -2533,7 +2542,7 @@ public virtual async Task Default_if_empty_top_level_arg_followed_by_projecting_ .Where(c => c.EmployeeID == 4294967295) .DefaultIfEmpty(__p_0)", "NavigationExpandingExpressionVisitor"), - message); + message); } [ConditionalTheory] @@ -2704,7 +2713,7 @@ public virtual Task OrderBy_multiple_queries(bool isAsync) [MemberData(nameof(IsAsyncData))] public virtual Task OrderBy_shadow(bool isAsync) { - return AssertQuery( + return AssertQuery( isAsync, ss => ss.Set().OrderBy(e => EF.Property(e, "Title")).ThenBy(e => e.EmployeeID), assertOrder: true, @@ -2747,9 +2756,9 @@ public virtual Task OrderBy_correlated_subquery2(bool isAsync) ss => ss.Set().Where( o => o.OrderID <= 10250 && ss.Set().OrderBy( - c => ss.Set().Any( - c2 => c2.CustomerID == "ALFKI")) - .FirstOrDefault().City != "Nowhere"), + c => ss.Set().Any( + c2 => c2.CustomerID == "ALFKI")) + .FirstOrDefault().City != "Nowhere"), entryCount: 3); } @@ -2773,10 +2782,10 @@ public virtual Task OrderBy_multiple(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().Where(c => c.CustomerID.StartsWith("A")) - .OrderBy(c => c.CustomerID) - .OrderBy(c => c.Country) - .ThenBy(c => c.City) - .Select(c => c.City), + .OrderBy(c => c.CustomerID) + .OrderBy(c => c.Country) + .ThenBy(c => c.City) + .Select(c => c.City), assertOrder: true); } @@ -3343,7 +3352,7 @@ public virtual void Select_Where_Subquery_Equality() { var orders = (from o in context.Orders.OrderBy(o => o.OrderID).Take(1) - // ReSharper disable once UseMethodAny.0 + // ReSharper disable once UseMethodAny.0 where (from od in context.OrderDetails.OrderBy(od => od.OrderID).Take(2) where (from c in context.Set() where c.CustomerID == o.CustomerID @@ -3804,10 +3813,10 @@ await AssertQuery( isAsync, ss => ss.Set().Where( o => (o.OrderID < 10400) - || (dateFilter == null) - || (o.OrderDate.HasValue - && o.OrderDate.Value.Month == dateFilter.Value.Month - && o.OrderDate.Value.Year == dateFilter.Value.Year)), + || (dateFilter == null) + || (o.OrderDate.HasValue + && o.OrderDate.Value.Month == dateFilter.Value.Month + && o.OrderDate.Value.Year == dateFilter.Value.Year)), entryCount: 152); dateFilter = null; @@ -3816,10 +3825,10 @@ await AssertQuery( isAsync, ss => ss.Set().Where( o => (o.OrderID < 10400) - || (dateFilter == null) - || (o.OrderDate.HasValue - && o.OrderDate.Value.Month == dateFilter.Value.Month - && o.OrderDate.Value.Year == dateFilter.Value.Year)), + || (dateFilter == null) + || (o.OrderDate.HasValue + && o.OrderDate.Value.Month == dateFilter.Value.Month + && o.OrderDate.Value.Year == dateFilter.Value.Year)), entryCount: 830); } @@ -3881,7 +3890,8 @@ public virtual Task Subquery_member_pushdown_does_not_change_original_subquery_m o => new { OrderId = o.OrderID, - City = EF.Property(ss.Set().SingleOrDefault(c => c.CustomerID == o.CustomerID), "City") + City = EF.Property( + ss.Set().SingleOrDefault(c => c.CustomerID == o.CustomerID), "City") }) .OrderBy(o => o.City), assertOrder: true); @@ -4321,7 +4331,8 @@ public virtual Task No_orderby_added_for_client_side_GroupJoin_dependent_to_prin isAsync, ss => from o in ss.Set() - join c in ss.Set() on new { o.CustomerID, o.OrderID } equals new { c.CustomerID, OrderID = 10000 } into grouping + join c in ss.Set() on new { o.CustomerID, o.OrderID } equals new { c.CustomerID, OrderID = 10000 } into + grouping from c in ClientDefaultIfEmpty(grouping) #pragma warning disable IDE0031 // Use null propagation select new { Id1 = o.CustomerID, Id2 = c != null ? c.CustomerID : null }, @@ -4338,7 +4349,8 @@ public virtual Task No_orderby_added_for_client_side_GroupJoin_dependent_to_prin isAsync, ss => from o in ss.Set() - join c in ss.Set() on new { o.OrderID, o.CustomerID } equals new { OrderID = 10000, c.CustomerID } into grouping + join c in ss.Set() on new { o.OrderID, o.CustomerID } equals new { OrderID = 10000, c.CustomerID } into + grouping from c in ClientDefaultIfEmpty(grouping) #pragma warning disable IDE0031 // Use null propagation select new { Id1 = o.CustomerID, Id2 = c != null ? c.CustomerID : null }, @@ -4451,8 +4463,10 @@ public virtual Task Anonymous_complex_distinct_result(bool isAsync) { return AssertSingleResult( isAsync, - syncQuery: ss => ss.Set().Select(c => new { A = c.CustomerID + c.City }).Distinct().Count(n => n.A.StartsWith("A")), - asyncQuery: ss => ss.Set().Select(c => new { A = c.CustomerID + c.City }).Distinct().CountAsync(n => n.A.StartsWith("A"))); + syncQuery: ss => ss.Set().Select(c => new { A = c.CustomerID + c.City }).Distinct() + .Count(n => n.A.StartsWith("A")), + asyncQuery: ss + => ss.Set().Select(c => new { A = c.CustomerID + c.City }).Distinct().CountAsync(n => n.A.StartsWith("A"))); } [ConditionalTheory] @@ -4509,7 +4523,8 @@ public virtual Task DTO_member_distinct_where(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Select(c => new DTO { Property = c.CustomerID }).Distinct().Where(n => n.Property == "ALFKI"), + ss => ss.Set().Select(c => new DTO { Property = c.CustomerID }).Distinct() + .Where(n => n.Property == "ALFKI"), elementSorter: e => e.Property, elementAsserter: (e, a) => Assert.Equal(e.Property, a.Property)); } @@ -4543,7 +4558,8 @@ public virtual Task DTO_complex_distinct_where(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Select(c => new DTO { Property = c.CustomerID + c.City }).Distinct().Where(n => n.Property == "ALFKIBerlin"), + ss => ss.Set().Select(c => new DTO { Property = c.CustomerID + c.City }).Distinct() + .Where(n => n.Property == "ALFKIBerlin"), elementSorter: e => e.Property, elementAsserter: (e, a) => Assert.Equal(e.Property, a.Property)); } @@ -4554,7 +4570,8 @@ public virtual Task DTO_complex_distinct_orderby(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Select(c => new DTO { Property = c.CustomerID + c.City }).Distinct().OrderBy(n => n.Property), + ss => ss.Set().Select(c => new DTO { Property = c.CustomerID + c.City }).Distinct() + .OrderBy(n => n.Property), assertOrder: true, elementAsserter: (e, a) => Assert.Equal(e.Property, a.Property)); } @@ -4645,7 +4662,8 @@ public virtual Task Complex_query_with_repeated_nested_query_model_compiles_corr .Where( outer => (from c in ss.Set() - let customers = ss.Set().Where(cc => ss.Set().OrderBy(inner => inner.CustomerID).Take(10).Distinct().Any()) + let customers = ss.Set().Where( + cc => ss.Set().OrderBy(inner => inner.CustomerID).Take(10).Distinct().Any()) .Select(cc => cc.CustomerID) where customers.Any() select customers).Any()), @@ -5195,9 +5213,9 @@ public virtual Task Join_take_count_works(bool isAsync) isAsync, ss => (from o in ss.Set().Where(o => o.OrderID > 690 && o.OrderID < 710) join c in ss.Set().Where(c => c.CustomerID == "ALFKI") - on o.CustomerID equals c.CustomerID + on o.CustomerID equals c.CustomerID select o) - .Take(5)); + .Take(5)); } [ConditionalTheory(Skip = "Issue#15713")] @@ -5362,7 +5380,8 @@ public virtual Task Client_OrderBy_GroupBy_Group_ordering_works(bool isAsync) isAsync, ss => from o in ss.Set() orderby ClientEvalSelector(o) - group o by o.CustomerID into g + group o by o.CustomerID + into g orderby g.Key select g.OrderByDescending(x => x.OrderID), assertOrder: true, @@ -5511,11 +5530,9 @@ public virtual async Task Context_based_client_method(bool isAsync) [MemberData(nameof(IsAsyncData))] public virtual Task OrderBy_object_type_server_evals(bool isAsync) { - Expression>[] orderingExpressions = { - o => o.OrderID, - o => o.OrderDate, - o => o.Customer.CustomerID, - o => o.Customer.City + Expression>[] orderingExpressions = + { + o => o.OrderID, o => o.OrderDate, o => o.Customer.CustomerID, o => o.Customer.City }; return AssertQuery( @@ -5537,11 +5554,12 @@ public virtual Task AsQueryable_in_query_server_evals(bool isAsync) return AssertQuery( isAsync, ss => ss.Set().OrderBy(c => c.CustomerID) - .Select(c => c.Orders.AsQueryable() - .Where(ValidYear) - .OrderBy(o => o.OrderID) - .Take(1) - .Select(o => new { o.OrderDate }).ToList()), + .Select( + c => c.Orders.AsQueryable() + .Where(ValidYear) + .OrderBy(o => o.OrderID) + .Take(1) + .Select(o => new { o.OrderDate }).ToList()), assertOrder: true, elementAsserter: (e, a) => AssertCollection(e, a, ordered: true)); } diff --git a/test/EFCore.Specification.Tests/Query/SpatialQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/SpatialQueryTestBase.cs index 15f1393a040..fd7cf25a413 100644 --- a/test/EFCore.Specification.Tests/Query/SpatialQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/SpatialQueryTestBase.cs @@ -604,7 +604,8 @@ public virtual Task GetPointN(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Select(e => new { e.Id, Point0 = e.LineString == null ? null : e.LineString.GetPointN(0) }), + ss => ss.Set() + .Select(e => new { e.Id, Point0 = e.LineString == null ? null : e.LineString.GetPointN(0) }), elementSorter: x => x.Id); } @@ -704,7 +705,8 @@ public virtual Task IsRing(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Select(e => new { e.Id, IsRing = e.LineString == null ? (bool?)null : e.LineString.IsRing }), + ss => ss.Set() + .Select(e => new { e.Id, IsRing = e.LineString == null ? (bool?)null : e.LineString.IsRing }), elementSorter: x => x.Id); } @@ -774,7 +776,8 @@ public virtual Task Length(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Select(e => new { e.Id, Length = e.LineString == null ? (double?)null : e.LineString.Length }), + ss => ss.Set() + .Select(e => new { e.Id, Length = e.LineString == null ? (double?)null : e.LineString.Length }), elementSorter: x => x.Id, elementAsserter: (e, a) => { @@ -948,7 +951,8 @@ public virtual Task StartPoint(bool isAsync) { return AssertQuery( isAsync, - ss => ss.Set().Select(e => new { e.Id, StartPoint = e.LineString == null ? null : e.LineString.StartPoint }), + ss => ss.Set() + .Select(e => new { e.Id, StartPoint = e.LineString == null ? null : e.LineString.StartPoint }), elementSorter: x => x.Id); } diff --git a/test/EFCore.Specification.Tests/TestModels/FunkyDataModel/FunkyDataData.cs b/test/EFCore.Specification.Tests/TestModels/FunkyDataModel/FunkyDataData.cs index bd09c1d43be..f03b99b056f 100644 --- a/test/EFCore.Specification.Tests/TestModels/FunkyDataModel/FunkyDataData.cs +++ b/test/EFCore.Specification.Tests/TestModels/FunkyDataModel/FunkyDataData.cs @@ -39,7 +39,6 @@ public static IReadOnlyList CreateFunkyCustomers() new FunkyCustomer { Id = 6, FirstName = null, LastName = "%B%a%r" }, new FunkyCustomer { Id = 7, FirstName = "%B%a%r", LastName = "" }, new FunkyCustomer { Id = 8, FirstName = "", LastName = "%%r%" }, - new FunkyCustomer { Id = 9, FirstName = "_Bar", LastName = "_B", NullableBool = false }, new FunkyCustomer { Id = 10, FirstName = "Ba_r", LastName = "a_", NullableBool = false }, new FunkyCustomer { Id = 11, FirstName = "Bar_", LastName = "_B_", NullableBool = false }, @@ -48,10 +47,9 @@ public static IReadOnlyList CreateFunkyCustomers() new FunkyCustomer { Id = 14, FirstName = null, LastName = "_B_a_r" }, new FunkyCustomer { Id = 15, FirstName = "_B_a_r", LastName = "" }, new FunkyCustomer { Id = 16, FirstName = "", LastName = "__r_" }, - - new FunkyCustomer { Id = 17, FirstName = "[]Bar", LastName = "[]", NullableBool = true}, - new FunkyCustomer { Id = 18, FirstName = "B[a]r", LastName = "B[", NullableBool = true}, - new FunkyCustomer { Id = 19, FirstName = "B[[a^r", LastName = "B[[", NullableBool = true}, + new FunkyCustomer { Id = 17, FirstName = "[]Bar", LastName = "[]", NullableBool = true }, + new FunkyCustomer { Id = 18, FirstName = "B[a]r", LastName = "B[", NullableBool = true }, + new FunkyCustomer { Id = 19, FirstName = "B[[a^r", LastName = "B[[", NullableBool = true } }; } } diff --git a/test/EFCore.Specification.Tests/TestModels/MonsterContext`.cs b/test/EFCore.Specification.Tests/TestModels/MonsterContext`.cs index 330bed3ba13..4f83a3d6420 100644 --- a/test/EFCore.Specification.Tests/TestModels/MonsterContext`.cs +++ b/test/EFCore.Specification.Tests/TestModels/MonsterContext`.cs @@ -496,15 +496,15 @@ public override void SeedUsingFKs() var rsaToken1 = Add( new TRsaToken - { - Issued = DateTime.Now, Serial = "1234", Username = Entry(login1).Property(e => e.Username).CurrentValue - }) + { + Issued = DateTime.Now, Serial = "1234", Username = Entry(login1).Property(e => e.Username).CurrentValue + }) .Entity; var rsaToken2 = Add( new TRsaToken - { - Issued = DateTime.Now, Serial = "2234", Username = Entry(login2).Property(e => e.Username).CurrentValue - }) + { + Issued = DateTime.Now, Serial = "2234", Username = Entry(login2).Property(e => e.Username).CurrentValue + }) .Entity; var smartCard1 = Add( @@ -702,9 +702,9 @@ public override void SeedUsingFKs() var productReview1 = Add( new TProductReview - { - ProductId = Entry(product1).Property(e => e.ProductId).CurrentValue, Review = "Better than Tarqies!" - }) + { + ProductId = Entry(product1).Property(e => e.ProductId).CurrentValue, Review = "Better than Tarqies!" + }) .Entity; var productReview2 = Add( new TProductReview @@ -717,21 +717,21 @@ public override void SeedUsingFKs() var productPhoto1 = Add( new TProductPhoto - { - ProductId = Entry(product1).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 101, 102 } - }) + { + ProductId = Entry(product1).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 101, 102 } + }) .Entity; var productPhoto2 = Add( new TProductPhoto - { - ProductId = Entry(product1).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 103, 104 } - }) + { + ProductId = Entry(product1).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 103, 104 } + }) .Entity; var productPhoto3 = Add( new TProductPhoto - { - ProductId = Entry(product3).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 105, 106 } - }) + { + ProductId = Entry(product3).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 105, 106 } + }) .Entity; var productWebFeature1 = Add( @@ -769,9 +769,9 @@ public override void SeedUsingFKs() }).Entity; var supplierInfo2 = Add( new TSupplierInfo - { - SupplierId = Entry(supplier1).Property(e => e.SupplierId).CurrentValue, Information = "Orange fur?" - }) + { + SupplierId = Entry(supplier1).Property(e => e.SupplierId).CurrentValue, Information = "Orange fur?" + }) .Entity; var supplierInfo3 = Add( new TSupplierInfo @@ -963,9 +963,9 @@ public override void SeedUsingNavigations(bool dependentNavs, bool principalNavs new TLogin { Customer = dependentNavs ? customer2 : null, Username = "MrsBossyPants", AlternateUsername = "Sue" }).Entity; var login3 = Add( new TLogin - { - Customer = dependentNavs ? customer3 : null, Username = "TheStripedMenace", AlternateUsername = "Tarquin" - }) + { + Customer = dependentNavs ? customer3 : null, Username = "TheStripedMenace", AlternateUsername = "Tarquin" + }) .Entity; if (principalNavs) { @@ -1191,21 +1191,21 @@ public override void SeedUsingNavigations(bool dependentNavs, bool principalNavs var productPhoto1 = Add( new TProductPhoto - { - ProductId = Entry(product1).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 101, 102 } - }) + { + ProductId = Entry(product1).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 101, 102 } + }) .Entity; var productPhoto2 = Add( new TProductPhoto - { - ProductId = Entry(product1).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 103, 104 } - }) + { + ProductId = Entry(product1).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 103, 104 } + }) .Entity; var productPhoto3 = Add( new TProductPhoto - { - ProductId = Entry(product3).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 105, 106 } - }) + { + ProductId = Entry(product3).Property(e => e.ProductId).CurrentValue, Photo = new byte[] { 105, 106 } + }) .Entity; if (principalNavs) { diff --git a/test/EFCore.Specification.Tests/TestUtilities/ISetSource.cs b/test/EFCore.Specification.Tests/TestUtilities/ISetSource.cs index 76c914a08f7..5cd5fc971e2 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/ISetSource.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/ISetSource.cs @@ -7,7 +7,7 @@ namespace Microsoft.EntityFrameworkCore.TestUtilities { public interface ISetSource { - public IQueryable Set() + IQueryable Set() where TEntity : class; } } diff --git a/test/EFCore.Specification.Tests/TestUtilities/QueryAsserter.cs b/test/EFCore.Specification.Tests/TestUtilities/QueryAsserter.cs index 9bdece9fc9f..81331f35911 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/QueryAsserter.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/QueryAsserter.cs @@ -6,7 +6,6 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.TestUtilities.QueryTestGeneration; using Xunit; @@ -94,7 +93,8 @@ public override async Task AssertQuery( var expected = expectedQuery(ExpectedData).ToArray(); - if (!assertOrder && elementSorter == null) + if (!assertOrder + && elementSorter == null) { _entitySorters.TryGetValue(typeof(TResult), out var sorter); elementSorter = (Func)sorter; @@ -236,8 +236,8 @@ public override async Task> AssertIncludeQuery( var expected = expectedQuery(ExpectedData).ToList(); - - if (!assertOrder && elementSorter == null) + if (!assertOrder + && elementSorter == null) { _entitySorters.TryGetValue(typeof(TResult), out var sorter); elementSorter = (Func)sorter; @@ -301,7 +301,6 @@ public override async Task AssertAny( Assert.Equal(expected, actual); } - using (var context = _contextCreator()) { var actual = isAsync @@ -586,7 +585,7 @@ public override async Task AssertLastOrDefault( } public override async Task AssertCount( - Func> actualQuery, + Func> actualQuery, Func> expectedQuery, bool isAsync = false) { @@ -1551,7 +1550,8 @@ public override async Task AssertAverage( public override void AssertEqual(T expected, T actual, Action asserter = null) { - if (asserter == null && expected != null) + if (asserter == null + && expected != null) { _entityAsserters.TryGetValue(typeof(T), out var entityAsserter); asserter ??= (Action)entityAsserter; @@ -1576,7 +1576,8 @@ public override void AssertCollection( Func elementSorter = null, Action elementAsserter = null) { - if (expected == null && actual == null) + if (expected == null + && actual == null) { return; } @@ -1636,6 +1637,7 @@ public override void AssertCollection( private class DefaultSetSource : ISetSource { private readonly DbContext _context; + public DefaultSetSource(DbContext context) { _context = context; diff --git a/test/EFCore.Specification.Tests/TestUtilities/QueryAsserterBase.cs b/test/EFCore.Specification.Tests/TestUtilities/QueryAsserterBase.cs index 4944214785e..1b91af560d4 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/QueryAsserterBase.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/QueryAsserterBase.cs @@ -11,7 +11,7 @@ namespace Microsoft.EntityFrameworkCore.TestUtilities { public abstract class QueryAsserterBase { - public virtual Func SetSourceCreator { get; set; } + public virtual Func SetSourceCreator { get; set; } public virtual ISetSource ExpectedData { get; set; } diff --git a/test/EFCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerTest.cs index bdb59031429..fc7f2da6406 100644 --- a/test/EFCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerTest.cs @@ -6,7 +6,6 @@ using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; -using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; diff --git a/test/EFCore.SqlServer.FunctionalTests/DbContextPoolingTest.cs b/test/EFCore.SqlServer.FunctionalTests/DbContextPoolingTest.cs index 6f45dfd2eea..482c64b4f84 100644 --- a/test/EFCore.SqlServer.FunctionalTests/DbContextPoolingTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/DbContextPoolingTest.cs @@ -28,18 +28,18 @@ public class DbContextPoolingTest : IClassFixture(int poolSize = 32) where TContextService : class where TContext : DbContext, TContextService - => new ServiceCollection() - .AddDbContextPool( - ob => - ob.UseSqlServer(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString) - .EnableServiceProviderCaching(false), - poolSize) - .AddDbContextPool( - ob => - ob.UseSqlServer(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString) - .EnableServiceProviderCaching(false), - poolSize) - .BuildServiceProvider(); + => ServiceCollectionContainerBuilderExtensions.BuildServiceProvider( + new ServiceCollection() + .AddDbContextPool( + ob => + ob.UseSqlServer(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString) + .EnableServiceProviderCaching(false), + poolSize) + .AddDbContextPool( + ob => + ob.UseSqlServer(SqlServerNorthwindTestStoreFactory.NorthwindConnectionString) + .EnableServiceProviderCaching(false), + poolSize)); private static IServiceProvider BuildServiceProvider(int poolSize = 32) where TContext : DbContext diff --git a/test/EFCore.SqlServer.FunctionalTests/LoadSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/LoadSqlServerTest.cs index 8fcefbdc1c8..bfb8956801c 100644 --- a/test/EFCore.SqlServer.FunctionalTests/LoadSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/LoadSqlServerTest.cs @@ -173,7 +173,8 @@ public override void Lazy_load_one_to_one_reference_to_principal_already_loaded( AssertSql(""); } - public override void Lazy_load_one_to_one_reference_to_dependent_already_loaded(EntityState state, CascadeTiming cascadeDeleteTiming) + public override void Lazy_load_one_to_one_reference_to_dependent_already_loaded( + EntityState state, CascadeTiming cascadeDeleteTiming) { base.Lazy_load_one_to_one_reference_to_dependent_already_loaded(state, cascadeDeleteTiming); @@ -660,14 +661,16 @@ public override async Task Load_many_to_one_reference_to_principal_already_loade AssertSql(""); } - public override async Task Load_one_to_one_reference_to_principal_already_loaded(EntityState state, bool async, CascadeTiming cascadeDeleteTiming) + public override async Task Load_one_to_one_reference_to_principal_already_loaded( + EntityState state, bool async, CascadeTiming cascadeDeleteTiming) { await base.Load_one_to_one_reference_to_principal_already_loaded(state, async, cascadeDeleteTiming); AssertSql(""); } - public override async Task Load_one_to_one_reference_to_dependent_already_loaded(EntityState state, bool async, CascadeTiming cascadeDeleteTiming) + public override async Task Load_one_to_one_reference_to_dependent_already_loaded( + EntityState state, bool async, CascadeTiming cascadeDeleteTiming) { await base.Load_one_to_one_reference_to_dependent_already_loaded(state, async, cascadeDeleteTiming); @@ -688,7 +691,8 @@ public override async Task Load_one_to_one_PK_to_PK_reference_to_dependent_alrea AssertSql(""); } - public override async Task Load_collection_using_Query_already_loaded(EntityState state, bool async, CascadeTiming cascadeDeleteTiming) + public override async Task Load_collection_using_Query_already_loaded( + EntityState state, bool async, CascadeTiming cascadeDeleteTiming) { await base.Load_collection_using_Query_already_loaded(state, async, cascadeDeleteTiming); @@ -724,7 +728,8 @@ FROM [Parent] AS [p] WHERE [p].[Id] = @__p_0"); } - public override async Task Load_one_to_one_reference_to_dependent_using_Query_already_loaded(EntityState state, bool async, CascadeTiming cascadeDeleteTiming) + public override async Task Load_one_to_one_reference_to_dependent_using_Query_already_loaded( + EntityState state, bool async, CascadeTiming cascadeDeleteTiming) { await base.Load_one_to_one_reference_to_dependent_using_Query_already_loaded(state, async, cascadeDeleteTiming); @@ -921,7 +926,7 @@ public override async Task Load_many_to_one_reference_to_principal_using_Query_n await base.Load_many_to_one_reference_to_principal_using_Query_not_found_untyped(state, async); AssertSql( - @"@__p_0='787' + @"@__p_0='787' SELECT [p].[Id], [p].[AlternateId] FROM [Parent] AS [p] @@ -973,14 +978,16 @@ public override async Task Load_one_to_one_reference_to_principal_already_loaded AssertSql(""); } - public override async Task Load_one_to_one_reference_to_dependent_already_loaded_untyped(EntityState state, bool async, CascadeTiming cascadeDeleteTiming) + public override async Task Load_one_to_one_reference_to_dependent_already_loaded_untyped( + EntityState state, bool async, CascadeTiming cascadeDeleteTiming) { await base.Load_one_to_one_reference_to_dependent_already_loaded_untyped(state, async, cascadeDeleteTiming); AssertSql(""); } - public override async Task Load_collection_using_Query_already_loaded_untyped(EntityState state, bool async, CascadeTiming cascadeDeleteTiming) + public override async Task Load_collection_using_Query_already_loaded_untyped( + EntityState state, bool async, CascadeTiming cascadeDeleteTiming) { await base.Load_collection_using_Query_already_loaded_untyped(state, async, cascadeDeleteTiming); @@ -1016,7 +1023,8 @@ FROM [Parent] AS [p] WHERE [p].[Id] = @__p_0"); } - public override async Task Load_one_to_one_reference_to_dependent_using_Query_already_loaded_untyped(EntityState state, bool async, CascadeTiming cascadeDeleteTiming) + public override async Task Load_one_to_one_reference_to_dependent_using_Query_already_loaded_untyped( + EntityState state, bool async, CascadeTiming cascadeDeleteTiming) { await base.Load_one_to_one_reference_to_dependent_using_Query_already_loaded_untyped(state, async, cascadeDeleteTiming); @@ -1283,7 +1291,7 @@ public override async Task Load_one_to_one_reference_to_principal_using_Query_nu await base.Load_one_to_one_reference_to_principal_using_Query_null_FK_shadow_fk(state, async); AssertSql( - @"SELECT TOP(2) [p].[Id], [p].[AlternateId] + @"SELECT TOP(2) [p].[Id], [p].[AlternateId] FROM [Parent] AS [p] WHERE CAST(0 AS bit) = CAST(1 AS bit)"); } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/CompiledQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/CompiledQuerySqlServerTest.cs index 6874967a540..954573abbdd 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/CompiledQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/CompiledQuerySqlServerTest.cs @@ -3,7 +3,6 @@ using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.TestUtilities; -using Xunit; using Xunit.Abstractions; namespace Microsoft.EntityFrameworkCore.Query diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsQuerySqlServerTest.cs index 632f24495f5..4de6de5ecb3 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/ComplexNavigationsQuerySqlServerTest.cs @@ -169,9 +169,11 @@ FROM [LevelTwo] AS [l0] ORDER BY [l].[Id], [t].[Id], [t].[Id0]"); } - public override async Task Multi_level_include_correct_PK_is_chosen_as_the_join_predicate_for_queries_that_join_same_table_multiple_times(bool isAsync) + public override async Task + Multi_level_include_correct_PK_is_chosen_as_the_join_predicate_for_queries_that_join_same_table_multiple_times(bool isAsync) { - await base.Multi_level_include_correct_PK_is_chosen_as_the_join_predicate_for_queries_that_join_same_table_multiple_times(isAsync); + await base.Multi_level_include_correct_PK_is_chosen_as_the_join_predicate_for_queries_that_join_same_table_multiple_times( + isAsync); AssertSql( @"SELECT [l].[Id], [l].[Date], [l].[Name], [l].[OneToMany_Optional_Self_Inverse1Id], [l].[OneToMany_Required_Self_Inverse1Id], [l].[OneToOne_Optional_Self1Id], [t0].[Id], [t0].[Date], [t0].[Level1_Optional_Id], [t0].[Level1_Required_Id], [t0].[Name], [t0].[OneToMany_Optional_Inverse2Id], [t0].[OneToMany_Optional_Self_Inverse2Id], [t0].[OneToMany_Required_Inverse2Id], [t0].[OneToMany_Required_Self_Inverse2Id], [t0].[OneToOne_Optional_PK_Inverse2Id], [t0].[OneToOne_Optional_Self2Id], [t0].[Id0], [t0].[Level2_Optional_Id], [t0].[Level2_Required_Id], [t0].[Name0], [t0].[OneToMany_Optional_Inverse3Id], [t0].[OneToMany_Optional_Self_Inverse3Id], [t0].[OneToMany_Required_Inverse3Id], [t0].[OneToMany_Required_Self_Inverse3Id], [t0].[OneToOne_Optional_PK_Inverse3Id], [t0].[OneToOne_Optional_Self3Id], [t0].[Id00], [t0].[Date0], [t0].[Level1_Optional_Id0], [t0].[Level1_Required_Id0], [t0].[Name00], [t0].[OneToMany_Optional_Inverse2Id0], [t0].[OneToMany_Optional_Self_Inverse2Id0], [t0].[OneToMany_Required_Inverse2Id0], [t0].[OneToMany_Required_Self_Inverse2Id0], [t0].[OneToOne_Optional_PK_Inverse2Id0], [t0].[OneToOne_Optional_Self2Id0], [t0].[Id1], [t0].[Level2_Optional_Id0], [t0].[Level2_Required_Id0], [t0].[Name1], [t0].[OneToMany_Optional_Inverse3Id0], [t0].[OneToMany_Optional_Self_Inverse3Id0], [t0].[OneToMany_Required_Inverse3Id0], [t0].[OneToMany_Required_Self_Inverse3Id0], [t0].[OneToOne_Optional_PK_Inverse3Id0], [t0].[OneToOne_Optional_Self3Id0] @@ -1586,7 +1588,8 @@ ORDER BY [l0].[Id] ORDER BY [t].[Id]"); } - public override async Task Order_by_key_of_anonymous_type_projected_navigation_doesnt_get_optimized_into_FK_access_subquery(bool isAsync) + public override async Task Order_by_key_of_anonymous_type_projected_navigation_doesnt_get_optimized_into_FK_access_subquery( + bool isAsync) { await base.Order_by_key_of_anonymous_type_projected_navigation_doesnt_get_optimized_into_FK_access_subquery(isAsync); @@ -1646,7 +1649,8 @@ FROM [LevelTwo] AS [l] ORDER BY [l0].[Id]"); } - public override async Task Projection_select_correct_table_in_subquery_when_materialization_is_not_required_in_multiple_joins(bool isAsync) + public override async Task Projection_select_correct_table_in_subquery_when_materialization_is_not_required_in_multiple_joins( + bool isAsync) { await base.Projection_select_correct_table_in_subquery_when_materialization_is_not_required_in_multiple_joins(isAsync); @@ -2077,7 +2081,8 @@ FROM [LevelFour] AS [l0] ) AS [t] ON [l].[Id] = [t].[Level1_Optional_Id0]"); } - public override async Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany(bool isAsync) + public override async Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany( + bool isAsync) { await base.SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany(isAsync); @@ -2093,7 +2098,8 @@ FROM [LevelFour] AS [l0] ) AS [t] ON [l].[Id] = [t].[Level1_Optional_Id0]"); } - public override async Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany2(bool isAsync) + public override async Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany2( + bool isAsync) { await base.SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany2(isAsync); @@ -2106,7 +2112,8 @@ FROM [LevelFour] AS [l] INNER JOIN [LevelOne] AS [l3] ON [l2].[Level1_Optional_Id] = [l3].[Id]"); } - public override async Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany3(bool isAsync) + public override async Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany3( + bool isAsync) { await base.SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany3(isAsync); @@ -2119,7 +2126,8 @@ FROM [LevelOne] AS [l] INNER JOIN [LevelTwo] AS [l3] ON [l2].[Id] = [l3].[Id]"); } - public override async Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany4(bool isAsync) + public override async Task SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany4( + bool isAsync) { await base.SelectMany_with_nested_navigations_explicit_DefaultIfEmpty_and_additional_joins_outside_of_SelectMany4(isAsync); @@ -2152,9 +2160,12 @@ FROM [LevelFour] AS [l3] } public override async Task - SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_same_navs(bool isAsync) + SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_same_navs( + bool isAsync) { - await base.SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_same_navs(isAsync); + await base + .SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_same_navs( + isAsync); AssertSql( @"SELECT [l4].[Id], [l4].[Date], [l4].[Name], [l4].[OneToMany_Optional_Self_Inverse1Id], [l4].[OneToMany_Required_Self_Inverse1Id], [l4].[OneToOne_Optional_Self1Id] @@ -2166,9 +2177,13 @@ FROM [LevelFour] AS [l] LEFT JOIN [LevelOne] AS [l4] ON [l3].[Id] = [l4].[Id]"); } - public override async Task SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_different_navs(bool isAsync) + public override async Task + SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_different_navs( + bool isAsync) { - await base.SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_different_navs(isAsync); + await base + .SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_followed_by_Select_required_navigation_using_different_navs( + isAsync); AssertSql( @"SELECT [l3].[Id], [l3].[Date], [l3].[Name], [l3].[OneToMany_Optional_Self_Inverse1Id], [l3].[OneToMany_Required_Self_Inverse1Id], [l3].[OneToOne_Optional_Self1Id] @@ -2179,9 +2194,11 @@ FROM [LevelOne] AS [l] LEFT JOIN [LevelOne] AS [l3] ON [l2].[Id] = [l3].[Id]"); } - public override async Task Complex_SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_with_other_query_operators_composed_on_top(bool isAsync) + public override async Task + Complex_SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_with_other_query_operators_composed_on_top(bool isAsync) { - await base.Complex_SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_with_other_query_operators_composed_on_top(isAsync); + await base.Complex_SelectMany_with_nested_navigations_and_explicit_DefaultIfEmpty_with_other_query_operators_composed_on_top( + isAsync); AssertSql( @"SELECT [l2].[Id], [l2].[Level3_Optional_Id], [l2].[Level3_Required_Id], [l2].[Name], [l2].[OneToMany_Optional_Inverse4Id], [l2].[OneToMany_Optional_Self_Inverse4Id], [l2].[OneToMany_Required_Inverse4Id], [l2].[OneToMany_Required_Self_Inverse4Id], [l2].[OneToOne_Optional_PK_Inverse4Id], [l2].[OneToOne_Optional_Self4Id], [l14].[Name], [l].[Id], [t].[Id], [t].[Id0], [t1].[Id], [t1].[Date], [t1].[Level1_Optional_Id], [t1].[Level1_Required_Id], [t1].[Name], [t1].[OneToMany_Optional_Inverse2Id], [t1].[OneToMany_Optional_Self_Inverse2Id], [t1].[OneToMany_Required_Inverse2Id], [t1].[OneToMany_Required_Self_Inverse2Id], [t1].[OneToOne_Optional_PK_Inverse2Id], [t1].[OneToOne_Optional_Self2Id] @@ -2540,7 +2557,8 @@ ORDER BY [l].[Id] ORDER BY [t].[Id0]"); } - public override async Task GroupJoin_on_a_subquery_containing_another_GroupJoin_with_orderby_on_inner_sequence_projecting_inner(bool isAsync) + public override async Task GroupJoin_on_a_subquery_containing_another_GroupJoin_with_orderby_on_inner_sequence_projecting_inner( + bool isAsync) { await base.GroupJoin_on_a_subquery_containing_another_GroupJoin_with_orderby_on_inner_sequence_projecting_inner(isAsync); @@ -3330,9 +3348,13 @@ FROM [InheritanceOne] AS [i] WHERE [i].[Discriminator] IN (N'InheritanceBase1', N'InheritanceDerived1', N'InheritanceDerived2')"); } - public override async Task String_include_multiple_derived_navigation_with_same_name_and_different_type_nested_also_includes_partially_matching_navigation_chains(bool isAsync) + public override async Task + String_include_multiple_derived_navigation_with_same_name_and_different_type_nested_also_includes_partially_matching_navigation_chains( + bool isAsync) { - await base.String_include_multiple_derived_navigation_with_same_name_and_different_type_nested_also_includes_partially_matching_navigation_chains(isAsync); + await base + .String_include_multiple_derived_navigation_with_same_name_and_different_type_nested_also_includes_partially_matching_navigation_chains( + isAsync); AssertSql( @"SELECT [i].[Id], [i].[Discriminator], [i].[InheritanceBase2Id], [i].[InheritanceBase2Id1], [i].[Name], [i0].[Id], [i0].[DifferentTypeReference_InheritanceDerived1Id], [i0].[InheritanceDerived1Id], [i0].[InheritanceDerived1Id1], [i0].[InheritanceDerived2Id], [i0].[Name], [i0].[SameTypeReference_InheritanceDerived1Id], [i0].[SameTypeReference_InheritanceDerived2Id], [i1].[Id], [i1].[DifferentTypeReference_InheritanceDerived2Id], [i1].[InheritanceDerived2Id], [i1].[Name], [i2].[Id], [i2].[InheritanceLeaf2Id], [i2].[Name] @@ -3370,9 +3392,13 @@ WHERE [i].[Discriminator] IN (N'InheritanceBase1', N'InheritanceDerived1', N'Inh ORDER BY [i].[Id], [i0].[Id], [i1].[Id]"); } - public override async Task String_include_multiple_derived_collection_navigation_with_same_name_and_different_type_nested_also_includes_partially_matching_navigation_chains(bool isAsync) + public override async Task + String_include_multiple_derived_collection_navigation_with_same_name_and_different_type_nested_also_includes_partially_matching_navigation_chains( + bool isAsync) { - await base.String_include_multiple_derived_collection_navigation_with_same_name_and_different_type_nested_also_includes_partially_matching_navigation_chains(isAsync); + await base + .String_include_multiple_derived_collection_navigation_with_same_name_and_different_type_nested_also_includes_partially_matching_navigation_chains( + isAsync); AssertSql( @"SELECT [i].[Id], [i].[Discriminator], [i].[InheritanceBase2Id], [i].[InheritanceBase2Id1], [i].[Name], [i0].[Id], [i0].[DifferentTypeReference_InheritanceDerived1Id], [i0].[InheritanceDerived1Id], [i0].[InheritanceDerived1Id1], [i0].[InheritanceDerived2Id], [i0].[Name], [i0].[SameTypeReference_InheritanceDerived1Id], [i0].[SameTypeReference_InheritanceDerived2Id], [t].[Id], [t].[DifferentTypeReference_InheritanceDerived2Id], [t].[InheritanceDerived2Id], [t].[Name], [t].[Id0], [t].[InheritanceLeaf2Id], [t].[Name0] diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/IncludeSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/IncludeSqlServerTest.cs index 82a4b5b310b..31bf82b5722 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/IncludeSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/IncludeSqlServerTest.cs @@ -1228,7 +1228,8 @@ OFFSET @__p_1 ROWS ORDER BY [t].[c], [t].[CustomerID], [o].[OrderID]"); } - public override async Task Include_is_not_ignored_when_projection_contains_client_method_and_complex_expression(bool useString, bool async) + public override async Task Include_is_not_ignored_when_projection_contains_client_method_and_complex_expression( + bool useString, bool async) { await base.Include_is_not_ignored_when_projection_contains_client_method_and_complex_expression(useString, async); diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/OwnedQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/OwnedQuerySqlServerTest.cs index 98709dbcb25..9fe2d24a306 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/OwnedQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/OwnedQuerySqlServerTest.cs @@ -302,7 +302,7 @@ public override async Task Query_for_branch_type_loads_all_owned_navs_tracking(b await base.Query_for_branch_type_loads_all_owned_navs_tracking(isAsync); AssertSql( - @"SELECT [o].[Id], [o].[Discriminator], [t0].[Id], [t3].[Id], [t3].[PersonAddress_Country_Name], [t3].[PersonAddress_Country_PlanetId], [t5].[Id], [t8].[Id], [t8].[BranchAddress_Country_Name], [t8].[BranchAddress_Country_PlanetId], [t10].[Id], [t13].[Id], [t13].[LeafAAddress_Country_Name], [t13].[LeafAAddress_Country_PlanetId], [o15].[ClientId], [o15].[Id] + @"SELECT [o].[Id], [o].[Discriminator], [t0].[Id], [t3].[Id], [t3].[PersonAddress_Country_Name], [t3].[PersonAddress_Country_PlanetId], [t5].[Id], [t8].[Id], [t8].[BranchAddress_Country_Name], [t8].[BranchAddress_Country_PlanetId], [t10].[Id], [t13].[Id], [t13].[LeafAAddress_Country_Name], [t13].[LeafAAddress_Country_PlanetId], [o15].[ClientId], [o15].[Id] FROM [OwnedPerson] AS [o] LEFT JOIN ( SELECT [o0].[Id], [t].[Id] AS [Id0] @@ -1361,7 +1361,8 @@ WHERE [o].[Discriminator] IN (N'OwnedPerson', N'Branch', N'LeafB', N'LeafA') ORDER BY [o].[Id], [e].[Id]"); } - public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_and_scalar(bool isAsync) + public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_and_scalar( + bool isAsync) { await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_and_scalar(isAsync); @@ -1396,9 +1397,11 @@ WHERE [o2].[PersonAddress_Country_PlanetId] IS NOT NULL WHERE [o].[Discriminator] IN (N'OwnedPerson', N'Branch', N'LeafB', N'LeafA')"); } - public override async Task Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(bool isAsync) + public override async Task + Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(bool isAsync) { - await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection(isAsync); + await base.Navigation_rewrite_on_owned_reference_followed_by_regular_entity_and_another_reference_in_predicate_and_projection( + isAsync); AssertSql( @"SELECT [s].[Id], [s].[Name], [o].[Id], [e].[Id], [e].[Name], [e].[StarId] @@ -1523,7 +1526,7 @@ public override async Task Preserve_includes_when_applying_skip_take_after_anony FROM [OwnedPerson] AS [o] WHERE [o].[Discriminator] IN (N'OwnedPerson', N'Branch', N'LeafB', N'LeafA')", // - @"@__Count_0='4' + @"@__Count_0='4' @__p_1='0' @__p_2='100' @@ -1744,7 +1747,6 @@ WHERE [o].[Discriminator] IN (N'OwnedPerson', N'Branch', N'LeafB', N'LeafA') AND ORDER BY [o].[Id], [o20].[ClientId], [o20].[Id]"); } - private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/QueryBugsTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/QueryBugsTest.cs index 41827833651..099e9880d20 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/QueryBugsTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/QueryBugsTest.cs @@ -634,15 +634,11 @@ private SqlServerTestStore CreateDatabase925() var customer1 = new Customer { - FirstName = "Customer", - LastName = "One", - Orders = new List { order11, order12 } + FirstName = "Customer", LastName = "One", Orders = new List { order11, order12 } }; var customer2 = new Customer { - FirstName = "Customer", - LastName = "Two", - Orders = new List { order21, order22, order23 } + FirstName = "Customer", LastName = "Two", Orders = new List { order21, order22, order23 } }; context.Customers.AddRange(customer1, customer2); @@ -888,9 +884,7 @@ private SqlServerTestStore CreateDatabase963() var daenerys = new Targaryen { - Name = "Daenerys", - Details = details, - Dragons = new List { drogon, rhaegal, viserion } + Name = "Daenerys", Details = details, Dragons = new List { drogon, rhaegal, viserion } }; context.Targaryens.AddRange(daenerys, aerys); context.Dragons.AddRange(drogon, rhaegal, viserion, balerion); @@ -1423,7 +1417,7 @@ join eRoot in ctx.Entities.Include(e => e.Children) on eVersion.RootEntityId equals eRoot.Id into RootEntities from eRootJoined in RootEntities.DefaultIfEmpty() - // ReSharper disable once ConstantNullCoalescingCondition + // ReSharper disable once ConstantNullCoalescingCondition select new { One = 1, Coalesce = eRootJoined ?? (eVersion ?? eRootJoined) }; var result = query.ToList(); @@ -1444,7 +1438,7 @@ join eRoot in ctx.Entities on eVersion.RootEntityId equals eRoot.Id into RootEntities from eRootJoined in RootEntities.DefaultIfEmpty() - // ReSharper disable once ConstantNullCoalescingCondition + // ReSharper disable once ConstantNullCoalescingCondition select new { One = eRootJoined, Two = 2, Coalesce = eRootJoined ?? (eVersion ?? eRootJoined) }; var result = query.ToList(); @@ -1465,7 +1459,7 @@ join eRoot in ctx.Entities on eVersion.RootEntityId equals eRoot.Id into RootEntities from eRootJoined in RootEntities.DefaultIfEmpty() - // ReSharper disable once MergeConditionalExpression + // ReSharper disable once MergeConditionalExpression #pragma warning disable IDE0029 // Use coalesce expression select eRootJoined != null ? eRootJoined : eVersion; #pragma warning restore IDE0029 // Use coalesce expression @@ -2042,7 +2036,7 @@ public EntityDto8282(Entity8282 entity) Id = entity.Id; } - public int Id { get; set; } + public int Id { get; } } private class MyContext8282 : DbContext @@ -2205,9 +2199,7 @@ private SqlServerTestStore CreateDatabase8538() context.AddRange( new Entity8538 { - Permission = Permission.NONE, - PermissionByte = PermissionByte.NONE, - PermissionShort = PermissionShort.NONE + Permission = Permission.NONE, PermissionByte = PermissionByte.NONE, PermissionShort = PermissionShort.NONE }, new Entity8538 { @@ -2719,10 +2711,7 @@ public virtual void From_sql_gets_value_of_out_parameter_in_stored_procedure() { var valueParam = new SqlParameter { - ParameterName = "Value", - Value = 0, - Direction = ParameterDirection.Output, - SqlDbType = SqlDbType.Int + ParameterName = "Value", Value = 0, Direction = ParameterDirection.Output, SqlDbType = SqlDbType.Int }; Assert.Equal(0, valueParam.Value); @@ -3210,7 +3199,7 @@ public void Include_with_order_by_on_interface_key() { using (var context = new MyContext10635(_options)) { - var query = context.Parents.Include(p => p.Children).OrderBy(p => ((IEntity10635)p).Id).ToList(); + var query = context.Parents.Include(p => p.Children).OrderBy(p => p.Id).ToList(); AssertSql( @"SELECT [p].[Id], [p].[Name], [c].[Id], [c].[Name], [c].[Parent10635Id], [c].[ParentId] @@ -3228,7 +3217,7 @@ public void Correlated_collection_with_order_by_on_interface_key() { using (var context = new MyContext10635(_options)) { - var query = context.Parents.OrderBy(p => ((IEntity10635)p).Id).Select(p => p.Children.ToList()).ToList(); + var query = context.Parents.OrderBy(p => p.Id).Select(p => p.Children.ToList()).ToList(); AssertSql( @"SELECT [p].[Id], [c].[Id], [c].[Name], [c].[Parent10635Id], [c].[ParentId] @@ -5259,8 +5248,7 @@ private SqlServerTestStore CreateDatabase15684() context.Products.Add( new Product15684 { - Name = "Apple", - Category = new Category15684 { Name = "Fruit", Status = CategoryStatus15684.Active } + Name = "Apple", Category = new Category15684 { Name = "Fruit", Status = CategoryStatus15684.Active } }); context.Products.Add(new Product15684 { Name = "Bike" }); @@ -5893,7 +5881,9 @@ private class MyContext17276 : DbContext { public DbSet RemovableEntities { get; set; } public DbSet Parents { get; set; } - public MyContext17276(DbContextOptions options) : base(options) + + public MyContext17276(DbContextOptions options) + : base(options) { } @@ -5912,7 +5902,8 @@ private SqlServerTestStore CreateDatabase17276() ClearLog(); }); - private static List List17276(IQueryable query) where T : IRemovable17276 + private static List List17276(IQueryable query) + where T : IRemovable17276 { return query.Where(x => !x.IsRemoved).ToList(); } @@ -6062,7 +6053,9 @@ FROM [Foos] AS [f] private class MyContext6864 : DbContext { public DbSet Foos { get; set; } - public MyContext6864(DbContextOptions options) : base(options) + + public MyContext6864(DbContextOptions options) + : base(options) { } } @@ -6096,7 +6089,6 @@ public Bar6864(int value) public override string ToString() => Value; public static implicit operator string(Bar6864 bar) => bar.Value; public Bar6864 Clone() => new Bar6864(_value); - } #endregion @@ -6123,7 +6115,8 @@ FROM [TipoServicio9582] AS [t] private class MyContext9582 : DbContext { - public MyContext9582(DbContextOptions options) : base(options) + public MyContext9582(DbContextOptions options) + : base(options) { } @@ -6158,7 +6151,6 @@ private SqlServerTestStore CreateDatabase9582() private class TipoServicio9582 { - public int Id { get; set; } public string Nombre { get; set; } } @@ -6198,11 +6190,13 @@ public virtual void Implicit_DbContext_throws_memory_leak() private class MyContext7222 : DbContext { public DbSet Blogs { get; set; } + public MyContext7222() { } - public MyContext7222(DbContextOptions options) : base(options) + public MyContext7222(DbContextOptions options) + : base(options) { } @@ -6211,7 +6205,6 @@ public void RunQuery() Blogs.Select(b => ClientMethod(b)).ToList(); } - public int ClientMethod(Blog7222 blog) => blog.Id; } @@ -6242,7 +6235,7 @@ public virtual async Task Return_type_of_First_is_preserved() using (var context = new MyContext17644(_options)) { var personsToFind = await context.Persons.Where(p => p.Age >= 21) - .Select(p => new PersonDetailView17644() { Name = p.Name, Age = p.Age }) + .Select(p => new PersonDetailView17644 { Name = p.Name, Age = p.Age }) .FirstAsync(); AssertSql( @@ -6261,7 +6254,7 @@ public virtual async Task Return_type_of_FirstOrDefault_is_preserved() using (var context = new MyContext17644(_options)) { var personsToFind = await context.Persons.Where(p => p.Age >= 21) - .Select(p => new PersonDetailView17644() { Name = p.Name, Age = p.Age }) + .Select(p => new PersonDetailView17644 { Name = p.Name, Age = p.Age }) .FirstOrDefaultAsync(); AssertSql( @@ -6280,7 +6273,7 @@ public virtual async Task Return_type_of_Single_is_preserved() using (var context = new MyContext17644(_options)) { var personsToFind = await context.Persons.Where(p => p.Age >= 21) - .Select(p => new PersonDetailView17644() { Name = p.Name, Age = p.Age }) + .Select(p => new PersonDetailView17644 { Name = p.Name, Age = p.Age }) .SingleAsync(); AssertSql( @@ -6299,7 +6292,7 @@ public virtual async Task Return_type_of_SingleOrDefault_is_preserved() using (var context = new MyContext17644(_options)) { var personsToFind = await context.Persons.Where(p => p.Age >= 21) - .Select(p => new PersonDetailView17644() { Name = p.Name, Age = p.Age }) + .Select(p => new PersonDetailView17644 { Name = p.Name, Age = p.Age }) .SingleOrDefaultAsync(); AssertSql( @@ -6310,7 +6303,6 @@ FROM [Persons] AS [p] } } - [ConditionalFact] public virtual async Task Return_type_of_Last_is_preserved() { @@ -6320,7 +6312,7 @@ public virtual async Task Return_type_of_Last_is_preserved() { var personsToFind = await context.Persons.Where(p => p.Age >= 21) .OrderBy(p => p.Id) - .Select(p => new PersonDetailView17644() { Name = p.Name, Age = p.Age }) + .Select(p => new PersonDetailView17644 { Name = p.Name, Age = p.Age }) .LastAsync(); AssertSql( @@ -6341,7 +6333,7 @@ public virtual async Task Return_type_of_LastOrDefault_is_preserved() { var personsToFind = await context.Persons.Where(p => p.Age >= 21) .OrderBy(p => p.Id) - .Select(p => new PersonDetailView17644() { Name = p.Name, Age = p.Age }) + .Select(p => new PersonDetailView17644 { Name = p.Name, Age = p.Age }) .LastOrDefaultAsync(); AssertSql( @@ -6356,11 +6348,13 @@ FROM [Persons] AS [p] private class MyContext17644 : DbContext { public DbSet Persons { get; set; } + public MyContext17644() { } - public MyContext17644(DbContextOptions options) : base(options) + public MyContext17644(DbContextOptions options) + : base(options) { } } @@ -6406,10 +6400,7 @@ public virtual async Task Async_correlated_projection_with_first() using (var context = new MyContext11023(_options)) { var query = await context.Entities - .Select(e => new - { - ThingIds = e.Values.First().Things.Select(t => t.Subthing.ThingId).ToList() - }) + .Select(e => new { ThingIds = e.Values.First().Things.Select(t => t.Subthing.ThingId).ToList() }) .ToListAsync(); var result = Assert.Single(query); @@ -6448,7 +6439,8 @@ private class MyContext11023 : DbContext public DbSet Things { get; set; } public DbSet Subthings { get; set; } - public MyContext11023(DbContextOptions options) : base(options) + public MyContext11023(DbContextOptions options) + : base(options) { } } @@ -6458,26 +6450,21 @@ private SqlServerTestStore CreateDatabase11023() () => new MyContext11023(_options), context => { - context.Add(new Entity11023 - { - Values = new List + context.Add( + new Entity11023 { - new Value11023 + Values = new List { - Things = new List + new Value11023 { - new Thing11023 - { - Subthing = new Subthing11023() - }, - new Thing11023 + Things = new List { - Subthing = new Subthing11023() + new Thing11023 { Subthing = new Subthing11023() }, + new Thing11023 { Subthing = new Subthing11023() } } } } - } - }); + }); context.SaveChanges(); @@ -6552,15 +6539,18 @@ private class MyContext7973 : DbContext public DbSet Users { get; set; } public DbSet Organisations { get; set; } - public MyContext7973(DbContextOptions options) : base(options) + public MyContext7973(DbContextOptions options) + : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().HasKey(ou => new { ou.OrganisationId, ou.UserId }); - modelBuilder.Entity().HasOne(ou => ou.Organisation).WithMany(o => o.OrganisationUsers).HasForeignKey(ou => ou.OrganisationId); - modelBuilder.Entity().HasOne(ou => ou.User).WithMany(u => u.OrganisationUsers).HasForeignKey(ou => ou.UserId); + modelBuilder.Entity().HasOne(ou => ou.Organisation).WithMany(o => o.OrganisationUsers) + .HasForeignKey(ou => ou.OrganisationId); + modelBuilder.Entity().HasOne(ou => ou.User).WithMany(u => u.OrganisationUsers) + .HasForeignKey(ou => ou.UserId); } } @@ -6570,11 +6560,7 @@ private SqlServerTestStore CreateDatabase7973() context => { context.AddRange( - new OrganisationUser7973 - { - Organisation = new Organisation7973(), - User = new User7973() - }, + new OrganisationUser7973 { Organisation = new Organisation7973(), User = new User7973() }, new Organisation7973(), new User7973()); @@ -6621,7 +6607,8 @@ public virtual void Nested_include_queries_do_not_populate_navigation_twice() query.ToList(); } - Assert.Collection(query, + Assert.Collection( + query, b => Assert.Equal(3, b.Posts.Count), b => Assert.Equal(2, b.Posts.Count), b => Assert.Single(b.Posts)); @@ -6633,7 +6620,8 @@ private class MyContext10447 : DbContext { public DbSet Blogs { get; set; } - public MyContext10447(DbContextOptions options) : base(options) + public MyContext10447(DbContextOptions options) + : base(options) { } @@ -6648,30 +6636,9 @@ private SqlServerTestStore CreateDatabase10447() context => { context.AddRange( - new Blog10447 - { - Posts = new List - { - new Post10447(), - new Post10447(), - new Post10447(), - } - }, - new Blog10447 - { - Posts = new List - { - new Post10447(), - new Post10447(), - } - }, - new Blog10447 - { - Posts = new List - { - new Post10447(), - } - }); + new Blog10447 { Posts = new List { new Post10447(), new Post10447(), new Post10447() } }, + new Blog10447 { Posts = new List { new Post10447(), new Post10447() } }, + new Blog10447 { Posts = new List { new Post10447() } }); context.SaveChanges(); ClearLog(); @@ -6703,12 +6670,8 @@ public virtual void Let_multiple_references_with_reference_to_outer() { var users = (from a in context.Activities let cs = context.CompetitionSeasons - .First(s => s.StartDate <= a.DateTime && a.DateTime < s.EndDate) - select new - { - cs.Id, - Points = a.ActivityType.Points.Where(p => p.CompetitionSeason == cs) - }).ToList(); + .First(s => s.StartDate <= a.DateTime && a.DateTime < s.EndDate) + select new { cs.Id, Points = a.ActivityType.Points.Where(p => p.CompetitionSeason == cs) }).ToList(); AssertSql( @"SELECT ( @@ -6742,20 +6705,22 @@ public virtual void Let_multiple_references_with_reference_to_outer_2() using (var context = new MyContext12456(_options)) { var users = context.Activities - .Select(a => new - { - Activity = a, - CompetitionSeason = context.CompetitionSeasons - .First(s => s.StartDate <= a.DateTime && a.DateTime < s.EndDate) - }) - .Select(a => new - { - a.Activity, - CompetitionSeasonId = a.CompetitionSeason.Id, - Points = a.Activity.Points ?? a.Activity.ActivityType.Points - .Where(p => p.CompetitionSeason == a.CompetitionSeason) - .Select(p => p.Points).SingleOrDefault() - }).ToList(); + .Select( + a => new + { + Activity = a, + CompetitionSeason = context.CompetitionSeasons + .First(s => s.StartDate <= a.DateTime && a.DateTime < s.EndDate) + }) + .Select( + a => new + { + a.Activity, + CompetitionSeasonId = a.CompetitionSeason.Id, + Points = a.Activity.Points ?? a.Activity.ActivityType.Points + .Where(p => p.CompetitionSeason == a.CompetitionSeason) + .Select(p => p.Points).SingleOrDefault() + }).ToList(); AssertSql( @"SELECT [a0].[Id], [a0].[ActivityTypeId], [a0].[DateTime], [a0].[Points], ( @@ -6783,7 +6748,8 @@ private class MyContext12456 : DbContext public DbSet Activities { get; set; } public DbSet CompetitionSeasons { get; set; } - public MyContext12456(DbContextOptions options) : base(options) + public MyContext12456(DbContextOptions options) + : base(options) { } } @@ -6849,26 +6815,29 @@ public virtual async Task Run_something() using (var context = new MyContext15137(_options)) { var container = await context.Trades - .Select(x => new + .Select( + x => new { - Id = x.Id, + x.Id, Assets = x.Assets.AsQueryable() - .Select(y => new - { - Id = y.Id, - Contract = new + .Select( + y => new { - Id = y.Contract.Id, - Season = new + y.Id, + Contract = new { - Id = y.Contract.Season.Id, - IsPastTradeDeadline = (y.Contract.Season.Games.Max(z => (int?)z.GameNumber) ?? 0) > 10 + y.Contract.Id, + Season = new + { + y.Contract.Season.Id, + IsPastTradeDeadline = + (y.Contract.Season.Games.Max(z => (int?)z.GameNumber) ?? 0) > 10 + } } - } - }) + }) .ToList() }) - .SingleAsync(); + .SingleAsync(); AssertSql( @"SELECT [t0].[Id], [t1].[Id], [t1].[Id0], [t1].[Id1], [t1].[c] @@ -6897,7 +6866,8 @@ private class MyContext15137 : DbContext { public DbSet Trades { get; set; } - public MyContext15137(DbContextOptions options) : base(options) + public MyContext15137(DbContextOptions options) + : base(options) { } } @@ -6915,16 +6885,7 @@ private SqlServerTestStore CreateDatabase15137() { Contract = new DbContract { - Season = new DbSeason - { - Games = new List - { - new DbGame - { - GameNumber = 1 - } - } - } + Season = new DbSeason { Games = new List { new DbGame { GameNumber = 1 } } } } } } @@ -6982,15 +6943,16 @@ public void Query_filter_with_pk_fk_optimization_bug_13517() using var _ = CreateDatabase13517(); using var context = new BugContext13517(_options); - context.Entities.Select(s => - new BugEntityDto13517 - { - Id = s.Id, - RefEntity = s.RefEntity == null - ? null - : new BugRefEntityDto13517 { Id = s.RefEntity.Id, Public = s.RefEntity.Public }, - RefEntityId = s.RefEntityId - }).Single(p => p.Id == 1); + context.Entities.Select( + s => + new BugEntityDto13517 + { + Id = s.Id, + RefEntity = s.RefEntity == null + ? null + : new BugRefEntityDto13517 { Id = s.RefEntity.Id, Public = s.RefEntity.Public }, + RefEntityId = s.RefEntityId + }).Single(p => p.Id == 1); AssertSql( @"SELECT TOP(2) [e].[Id], CASE diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/QueryLoggingSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/QueryLoggingSqlServerTest.cs index 18041faed6b..1c5cb8b08b2 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/QueryLoggingSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/QueryLoggingSqlServerTest.cs @@ -79,7 +79,8 @@ var customers Assert.NotNull(customers); Assert.Contains( #pragma warning disable CS0612 // Type or member is obsolete - CoreResources.LogIgnoredInclude(new TestLogger()).GenerateMessage("[c].Orders"), Fixture.TestSqlLoggerFactory.Log.Select(l => l.Message)); + CoreResources.LogIgnoredInclude(new TestLogger()).GenerateMessage("[c].Orders"), + Fixture.TestSqlLoggerFactory.Log.Select(l => l.Message)); #pragma warning restore CS0612 // Type or member is obsolete } } diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/SimpleQuerySqlServerTest.Select.cs b/test/EFCore.SqlServer.FunctionalTests/Query/SimpleQuerySqlServerTest.Select.cs index ee4783187f0..0cfb54d3137 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/SimpleQuerySqlServerTest.Select.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/SimpleQuerySqlServerTest.Select.cs @@ -1,10 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore.Diagnostics; -using Xunit; namespace Microsoft.EntityFrameworkCore.Query { @@ -1094,7 +1091,8 @@ WHERE [c].[CustomerID] LIKE N'A%' ORDER BY [c].[CustomerID], [t].[OrderID]"); } - public override async Task SelectMany_with_collection_being_correlated_subquery_which_references_inner_and_outer_entity(bool isAsync) + public override async Task SelectMany_with_collection_being_correlated_subquery_which_references_inner_and_outer_entity( + bool isAsync) { await base.SelectMany_with_collection_being_correlated_subquery_which_references_inner_and_outer_entity(isAsync); @@ -1108,9 +1106,13 @@ FROM [Orders] AS [o] ) AS [t]"); } - public override async Task SelectMany_with_collection_being_correlated_subquery_which_references_non_mapped_properties_from_inner_and_outer_entity(bool isAsync) + public override async Task + SelectMany_with_collection_being_correlated_subquery_which_references_non_mapped_properties_from_inner_and_outer_entity( + bool isAsync) { - await base.SelectMany_with_collection_being_correlated_subquery_which_references_non_mapped_properties_from_inner_and_outer_entity(isAsync); + await base + .SelectMany_with_collection_being_correlated_subquery_which_references_non_mapped_properties_from_inner_and_outer_entity( + isAsync); AssertSql( @""); diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/SpatialQuerySqlServerGeographyTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/SpatialQuerySqlServerGeographyTest.cs index a252b5cd101..31469c60041 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/SpatialQuerySqlServerGeographyTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/SpatialQuerySqlServerGeographyTest.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; -using Xunit; using Xunit.Abstractions; namespace Microsoft.EntityFrameworkCore.Query diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureDatabaseCreationTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureDatabaseCreationTest.cs index 2131a1fbb9d..c85499b6855 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureDatabaseCreationTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureDatabaseCreationTest.cs @@ -38,7 +38,6 @@ private class ElasticPoolContext : DbContext public DbSet BigUns { get; set; } public ElasticPoolContext(SqlServerTestStore testStore) - : base() { _connectionString = testStore.ConnectionString; } @@ -75,7 +74,6 @@ private class BasicContext : DbContext public DbSet BigUns { get; set; } public BasicContext(SqlServerTestStore testStore) - : base() { _connectionString = testStore.ConnectionString; } @@ -113,7 +111,6 @@ private class BusinessCriticalContext : DbContext public DbSet BigUns { get; set; } public BusinessCriticalContext(SqlServerTestStore testStore) - : base() { _connectionString = testStore.ConnectionString; } @@ -138,7 +135,7 @@ private async Task AssertOptionsAsync(DbConnection connection, long? maxSize, st await connection.OpenAsync(); using var command = connection.CreateCommand(); - command.CommandText = @$" + command.CommandText = $@" SELECT DATABASEPROPERTYEX('{storeName}', 'EDITION'), DATABASEPROPERTYEX('{storeName}', 'ServiceObjective'), DATABASEPROPERTYEX('{storeName}', 'MaxSizeInBytes');"; diff --git a/test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs b/test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs index dfa0ebdd0ca..65252c6ed6a 100644 --- a/test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs @@ -54,20 +54,21 @@ private static async Task Returns_false_when_database_does_not_exist_test( { var creator = GetDatabaseCreator(context); - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (CreateTransactionScope(ambientTransaction)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - if (useCanConnect) + using (CreateTransactionScope(ambientTransaction)) { - Assert.False(async ? await creator.CanConnectAsync() : creator.CanConnect()); + if (useCanConnect) + { + Assert.False(async ? await creator.CanConnectAsync() : creator.CanConnect()); + } + else + { + Assert.False(async ? await creator.ExistsAsync() : creator.Exists()); + } } - else - { - Assert.False(async ? await creator.ExistsAsync() : creator.Exists()); - } - } - }); + }); Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State); } @@ -105,20 +106,21 @@ private static async Task Returns_true_when_database_exists_test(bool async, boo { var creator = GetDatabaseCreator(context); - await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => - { - using (CreateTransactionScope(ambientTransaction)) + await context.Database.CreateExecutionStrategy().ExecuteAsync( + async () => { - if (useCanConnect) - { - Assert.True(async ? await creator.CanConnectAsync() : creator.CanConnect()); - } - else + using (CreateTransactionScope(ambientTransaction)) { - Assert.True(async ? await creator.ExistsAsync() : creator.Exists()); + if (useCanConnect) + { + Assert.True(async ? await creator.CanConnectAsync() : creator.CanConnect()); + } + else + { + Assert.True(async ? await creator.ExistsAsync() : creator.Exists()); + } } - } - }); + }); Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State); } @@ -165,20 +167,21 @@ private static async Task Delete_database_test(bool async, bool open, bool ambie Assert.True(async ? await creator.ExistsAsync() : creator.Exists()); - await GetExecutionStrategy(testDatabase).ExecuteAsync(async () => - { - using (CreateTransactionScope(ambientTransaction)) + await GetExecutionStrategy(testDatabase).ExecuteAsync( + async () => { - if (async) - { - Assert.True(await context.Database.EnsureDeletedAsync()); - } - else + using (CreateTransactionScope(ambientTransaction)) { - Assert.True(context.Database.EnsureDeleted()); + if (async) + { + Assert.True(await context.Database.EnsureDeletedAsync()); + } + else + { + Assert.True(context.Database.EnsureDeleted()); + } } - } - }); + }); Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State); @@ -440,13 +443,14 @@ public async Task Returns_false_when_database_exists_but_has_no_tables(bool asyn { var creator = GetDatabaseCreator(testDatabase); - await GetExecutionStrategy(testDatabase).ExecuteAsync(async () => - { - using (CreateTransactionScope(ambientTransaction)) + await GetExecutionStrategy(testDatabase).ExecuteAsync( + async () => { - Assert.False(async ? await creator.HasTablesAsyncBase() : creator.HasTablesBase()); - } - }); + using (CreateTransactionScope(ambientTransaction)) + { + Assert.False(async ? await creator.HasTablesAsyncBase() : creator.HasTablesBase()); + } + }); } } @@ -460,13 +464,14 @@ public async Task Returns_true_when_database_exists_and_has_any_tables(bool asyn { var creator = GetDatabaseCreator(testDatabase); - await GetExecutionStrategy(testDatabase).ExecuteAsync(async () => - { - using (CreateTransactionScope(ambientTransaction)) + await GetExecutionStrategy(testDatabase).ExecuteAsync( + async () => { - Assert.True(async ? await creator.HasTablesAsyncBase() : creator.HasTablesBase()); - } - }); + using (CreateTransactionScope(ambientTransaction)) + { + Assert.True(async ? await creator.HasTablesAsyncBase() : creator.HasTablesBase()); + } + }); } } } @@ -663,20 +668,21 @@ public async Task Creates_physical_database_but_not_tables(bool async, bool ambi creator.EnsureDeleted(); - await GetExecutionStrategy(testDatabase).ExecuteAsync(async () => - { - using (CreateTransactionScope(ambientTransaction)) + await GetExecutionStrategy(testDatabase).ExecuteAsync( + async () => { - if (async) - { - await creator.CreateAsync(); - } - else + using (CreateTransactionScope(ambientTransaction)) { - creator.Create(); + if (async) + { + await creator.CreateAsync(); + } + else + { + creator.Create(); + } } - } - }); + }); Assert.True(creator.Exists()); @@ -686,7 +692,7 @@ await GetExecutionStrategy(testDatabase).ExecuteAsync(async () => } Assert.Empty( -(await testDatabase.QueryAsync( + (await testDatabase.QueryAsync( "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'"))); Assert.True( diff --git a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs index b2a9f932770..fded1a2ffb9 100644 --- a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs +++ b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerTestStore.cs @@ -352,15 +352,15 @@ private static Task ExecuteAsync( DbConnection connection, Func> executeAsync, string sql, bool useTransaction = false, IReadOnlyList parameters = null) => new TestSqlServerRetryingExecutionStrategy().ExecuteAsync( - new - { - connection, - executeAsync, - sql, - useTransaction, - parameters - }, - state => ExecuteCommandAsync(state.connection, state.executeAsync, state.sql, state.useTransaction, state.parameters)); + new + { + connection, + executeAsync, + sql, + useTransaction, + parameters + }, + state => ExecuteCommandAsync(state.connection, state.executeAsync, state.sql, state.useTransaction, state.parameters)); private static async Task ExecuteCommandAsync( DbConnection connection, Func> executeAsync, string sql, bool useTransaction, diff --git a/test/EFCore.SqlServer.Tests/Metadata/SqlServerMetadataBuilderExtensionsTest.cs b/test/EFCore.SqlServer.Tests/Metadata/SqlServerMetadataBuilderExtensionsTest.cs index 3e2ba4f28dc..8eabac9a752 100644 --- a/test/EFCore.SqlServer.Tests/Metadata/SqlServerMetadataBuilderExtensionsTest.cs +++ b/test/EFCore.SqlServer.Tests/Metadata/SqlServerMetadataBuilderExtensionsTest.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.SqlServer.Internal; diff --git a/test/EFCore.SqlServer.Tests/Migrations/SqlServerModelDifferTest.cs b/test/EFCore.SqlServer.Tests/Migrations/SqlServerModelDifferTest.cs index 469bd760643..e5b9e134672 100644 --- a/test/EFCore.SqlServer.Tests/Migrations/SqlServerModelDifferTest.cs +++ b/test/EFCore.SqlServer.Tests/Migrations/SqlServerModelDifferTest.cs @@ -5,7 +5,6 @@ using System.Reflection; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations.Internal; using Microsoft.EntityFrameworkCore.Migrations.Operations; using Microsoft.EntityFrameworkCore.SqlServer.Metadata.Internal; diff --git a/test/EFCore.SqlServer.Tests/ModelBuilding/SqlServerModelBuilderGenericTest.cs b/test/EFCore.SqlServer.Tests/ModelBuilding/SqlServerModelBuilderGenericTest.cs index 1920151a33c..421cc574b61 100644 --- a/test/EFCore.SqlServer.Tests/ModelBuilding/SqlServerModelBuilderGenericTest.cs +++ b/test/EFCore.SqlServer.Tests/ModelBuilding/SqlServerModelBuilderGenericTest.cs @@ -422,15 +422,23 @@ public virtual void Owned_types_can_be_mapped_to_different_tables() Assert.Equal(ValueGenerated.Never, bookOwnership1.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); Assert.Equal(ValueGenerated.Never, bookOwnership2.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); - Assert.Equal(ValueGenerated.Never, bookLabel1Ownership1.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); - Assert.Equal(ValueGenerated.Never, bookLabel1Ownership2.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); - Assert.Equal(ValueGenerated.Never, bookLabel2Ownership1.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); - Assert.Equal(ValueGenerated.Never, bookLabel2Ownership2.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); - - Assert.Equal(ValueGenerated.Never, bookLabel1Ownership11.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); - Assert.Equal(ValueGenerated.Never, bookLabel1Ownership21.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); - Assert.Equal(ValueGenerated.Never, bookLabel2Ownership11.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); - Assert.Equal(ValueGenerated.Never, bookLabel2Ownership21.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); + Assert.Equal( + ValueGenerated.Never, bookLabel1Ownership1.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); + Assert.Equal( + ValueGenerated.Never, bookLabel1Ownership2.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); + Assert.Equal( + ValueGenerated.Never, bookLabel2Ownership1.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); + Assert.Equal( + ValueGenerated.Never, bookLabel2Ownership2.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); + + Assert.Equal( + ValueGenerated.Never, bookLabel1Ownership11.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); + Assert.Equal( + ValueGenerated.Never, bookLabel1Ownership21.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); + Assert.Equal( + ValueGenerated.Never, bookLabel2Ownership11.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); + Assert.Equal( + ValueGenerated.Never, bookLabel2Ownership21.DeclaringEntityType.FindPrimaryKey().Properties.Single().ValueGenerated); } [ConditionalFact] diff --git a/test/EFCore.SqlServer.Tests/SqlServerOptionsExtensionTest.cs b/test/EFCore.SqlServer.Tests/SqlServerOptionsExtensionTest.cs index 694c2c6aaed..8e1c91c0efe 100644 --- a/test/EFCore.SqlServer.Tests/SqlServerOptionsExtensionTest.cs +++ b/test/EFCore.SqlServer.Tests/SqlServerOptionsExtensionTest.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal; diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/GearsOfWarQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/GearsOfWarQuerySqliteTest.cs index e7946d0ebcb..8c2e74a7032 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/GearsOfWarQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/GearsOfWarQuerySqliteTest.cs @@ -1,9 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore.Diagnostics; using Xunit; namespace Microsoft.EntityFrameworkCore.Query diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/SimpleQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/SimpleQuerySqliteTest.cs index a90444f93db..3f3411cf3bc 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/SimpleQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/SimpleQuerySqliteTest.cs @@ -4,7 +4,6 @@ using System; using System.Linq; using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.TestModels.Northwind; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; @@ -1312,7 +1311,8 @@ public override void Select_nested_collection_multi_level() public override Task SelectMany_correlated_with_outer_4(bool isAsync) => null; - public override Task Complex_nested_query_doesnt_try_binding_to_grandparent_when_parent_returns_complex_result(bool isAsync) => null; + public override Task Complex_nested_query_doesnt_try_binding_to_grandparent_when_parent_returns_complex_result(bool isAsync) + => null; public override Task SelectMany_correlated_subquery_hard(bool isAsync) => null; diff --git a/test/EFCore.Tests/Metadata/Conventions/EntityTypeAttributeConventionTest.cs b/test/EFCore.Tests/Metadata/Conventions/EntityTypeAttributeConventionTest.cs index 4435871c1de..ef453a8df7b 100644 --- a/test/EFCore.Tests/Metadata/Conventions/EntityTypeAttributeConventionTest.cs +++ b/test/EFCore.Tests/Metadata/Conventions/EntityTypeAttributeConventionTest.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.ComponentModel.DataAnnotations.Schema; -using System.Linq; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal; diff --git a/test/EFCore.Tests/Metadata/Internal/ClrCollectionAccessorFactoryTest.cs b/test/EFCore.Tests/Metadata/Internal/ClrCollectionAccessorFactoryTest.cs index 53c0820e4a4..6fccdb0b852 100644 --- a/test/EFCore.Tests/Metadata/Internal/ClrCollectionAccessorFactoryTest.cs +++ b/test/EFCore.Tests/Metadata/Internal/ClrCollectionAccessorFactoryTest.cs @@ -4,7 +4,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Linq; using System.Reflection; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/test/EFCore.Tests/ModelBuilding/InheritanceTestBase.cs b/test/EFCore.Tests/ModelBuilding/InheritanceTestBase.cs index d0efc8c8697..7b4e2669a04 100644 --- a/test/EFCore.Tests/ModelBuilding/InheritanceTestBase.cs +++ b/test/EFCore.Tests/ModelBuilding/InheritanceTestBase.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; using System.Linq; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Diagnostics.Internal; diff --git a/test/EFCore.Tests/ModelBuilding/ModelBuilderNonGenericTest.cs b/test/EFCore.Tests/ModelBuilding/ModelBuilderNonGenericTest.cs index 2acb4d7e18c..1fb00b83c24 100644 --- a/test/EFCore.Tests/ModelBuilding/ModelBuilderNonGenericTest.cs +++ b/test/EFCore.Tests/ModelBuilding/ModelBuilderNonGenericTest.cs @@ -225,7 +225,8 @@ public override DataBuilder HasData(IEnumerable data) public override TestDiscriminatorBuilder HasDiscriminator( Expression> propertyExpression) => new NonGenericTestDiscriminatorBuilder( - EntityTypeBuilder.HasDiscriminator(propertyExpression?.GetPropertyAccess().GetSimpleMemberName(), typeof(TDiscriminator))); + EntityTypeBuilder.HasDiscriminator( + propertyExpression?.GetPropertyAccess().GetSimpleMemberName(), typeof(TDiscriminator))); public override TestDiscriminatorBuilder HasDiscriminator(string propertyName) => new NonGenericTestDiscriminatorBuilder( diff --git a/test/EFCore.Tests/ModelBuilding/OwnedTypesTestBase.cs b/test/EFCore.Tests/ModelBuilding/OwnedTypesTestBase.cs index c6a219c865b..2cd2303ae56 100644 --- a/test/EFCore.Tests/ModelBuilding/OwnedTypesTestBase.cs +++ b/test/EFCore.Tests/ModelBuilding/OwnedTypesTestBase.cs @@ -6,7 +6,6 @@ using System.Linq; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Metadata.Internal; using Xunit; // ReSharper disable InconsistentNaming @@ -164,7 +163,7 @@ public virtual void Can_configure_another_relationship_to_owner() { r.WithOwner(); r.HasOne(d => d.Customer) - .WithMany(); + .WithMany(); }); var model = modelBuilder.FinalizeModel(); @@ -196,12 +195,12 @@ public virtual void Changing_ownership_uniqueness_throws() r => { r.HasOne(d => d.Customer) - .WithMany(); + .WithMany(); }); - - Assert.Equal(CoreStrings.NavigationNotAdded(nameof(Customer), nameof(Customer.Details), nameof(CustomerDetails)), - Assert.Throws(() => modelBuilder.FinalizeModel()).Message); + Assert.Equal( + CoreStrings.NavigationNotAdded(nameof(Customer), nameof(Customer.Details), nameof(CustomerDetails)), + Assert.Throws(() => modelBuilder.FinalizeModel()).Message); } [ConditionalFact] @@ -743,7 +742,7 @@ public virtual void Can_configure_fk_on_multiple_ownerships() modelBuilder.Entity().OwnsOne(b => b.Label).Ignore(l => l.Book); modelBuilder.Entity().OwnsOne(b => b.AlternateLabel).Ignore(l => l.Book); - modelBuilder.FinalizeModel(); + modelBuilder.FinalizeModel(); } [ConditionalFact] @@ -1174,11 +1173,12 @@ public virtual void Deriving_from_owned_type_throws() modelBuilder.Entity() .Ignore(b => b.AlternateLabel) .Ignore(b => b.Details) - .OwnsOne(b => b.Label, lb => - { - lb.Ignore(l => l.AnotherBookLabel); - lb.Ignore(l => l.SpecialBookLabel); - }); + .OwnsOne( + b => b.Label, lb => + { + lb.Ignore(l => l.AnotherBookLabel); + lb.Ignore(l => l.SpecialBookLabel); + }); Assert.Equal( CoreStrings.ClashingOwnedEntityType(nameof(AnotherBookLabel)), @@ -1218,7 +1218,8 @@ public virtual void CLR_base_type_can_be_owned_when_not_in_hierarchy() modelBuilder.Entity() .Ignore(b => b.AlternateLabel) .Ignore(b => b.Details) - .OwnsOne(c => c.Label, lb => + .OwnsOne( + c => c.Label, lb => { lb.Ignore(l => l.AnotherBookLabel); lb.Ignore(l => l.SpecialBookLabel); diff --git a/test/EFCore.Tests/ModelSourceTest.cs b/test/EFCore.Tests/ModelSourceTest.cs index 8099da290c7..d709cd95923 100644 --- a/test/EFCore.Tests/ModelSourceTest.cs +++ b/test/EFCore.Tests/ModelSourceTest.cs @@ -175,7 +175,7 @@ public ConcreteModelSource(IDbSetFinder setFinder) new ModelSourceDependencies( new ModelCustomizer(new ModelCustomizerDependencies(setFinder)), InMemoryTestHelpers.Instance.CreateContextServices().GetRequiredService(), - new MemoryCache(new MemoryCacheOptions() { SizeLimit = 200 }))) + new MemoryCache(new MemoryCacheOptions { SizeLimit = 200 }))) { } } diff --git a/test/EFCore.Tests/Query/ExpressionPrinterTest.cs b/test/EFCore.Tests/Query/ExpressionPrinterTest.cs index e11f16b6475..51257f86dad 100644 --- a/test/EFCore.Tests/Query/ExpressionPrinterTest.cs +++ b/test/EFCore.Tests/Query/ExpressionPrinterTest.cs @@ -19,7 +19,9 @@ public void UnaryExpression_printed_correctly() Assert.Equal("(decimal)42", _expressionPrinter.Print(Expression.Convert(Expression.Constant(42), typeof(decimal)))); Assert.Equal("throw \"Some exception\"", _expressionPrinter.Print(Expression.Throw(Expression.Constant("Some exception")))); Assert.Equal("!(True)", _expressionPrinter.Print(Expression.Not(Expression.Constant(true)))); - Assert.Equal("(BaseClass as DerivedClass)", _expressionPrinter.Print(Expression.TypeAs(Expression.Constant(new BaseClass()), typeof(DerivedClass)))); + Assert.Equal( + "(BaseClass as DerivedClass)", + _expressionPrinter.Print(Expression.TypeAs(Expression.Constant(new BaseClass()), typeof(DerivedClass)))); } private class BaseClass @@ -33,22 +35,60 @@ private class DerivedClass : BaseClass [ConditionalFact] public void BinaryExpression_printed_correctly() { - Assert.Equal("7 == 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Equal, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 != 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.NotEqual, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 > 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.GreaterThan, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 >= 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.GreaterThanOrEqual, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 < 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.LessThan, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 <= 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.LessThanOrEqual, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("True && True", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.AndAlso, Expression.Constant(true), Expression.Constant(true)))); - Assert.Equal("True || True", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.OrElse, Expression.Constant(true), Expression.Constant(true)))); - Assert.Equal("7 & 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.And, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 | 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Or, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 ^ 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.ExclusiveOr, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 + 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Add, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 - 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Subtract, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 * 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Multiply, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 / 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Divide, Expression.Constant(7), Expression.Constant(42)))); - Assert.Equal("7 % 42", _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Modulo, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 == 42", + _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Equal, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 != 42", + _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.NotEqual, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 > 42", + _expressionPrinter.Print( + Expression.MakeBinary(ExpressionType.GreaterThan, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 >= 42", + _expressionPrinter.Print( + Expression.MakeBinary(ExpressionType.GreaterThanOrEqual, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 < 42", + _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.LessThan, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 <= 42", + _expressionPrinter.Print( + Expression.MakeBinary(ExpressionType.LessThanOrEqual, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "True && True", + _expressionPrinter.Print( + Expression.MakeBinary(ExpressionType.AndAlso, Expression.Constant(true), Expression.Constant(true)))); + Assert.Equal( + "True || True", + _expressionPrinter.Print( + Expression.MakeBinary(ExpressionType.OrElse, Expression.Constant(true), Expression.Constant(true)))); + Assert.Equal( + "7 & 42", + _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.And, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 | 42", + _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Or, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 ^ 42", + _expressionPrinter.Print( + Expression.MakeBinary(ExpressionType.ExclusiveOr, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 + 42", + _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Add, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 - 42", + _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Subtract, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 * 42", + _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Multiply, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 / 42", + _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Divide, Expression.Constant(7), Expression.Constant(42)))); + Assert.Equal( + "7 % 42", + _expressionPrinter.Print(Expression.MakeBinary(ExpressionType.Modulo, Expression.Constant(7), Expression.Constant(42)))); } [ConditionalFact]