From 5e4ce7b67af08b91bafec5536d782ed2f5eff8d6 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 15 Jun 2023 15:45:16 +0200 Subject: [PATCH] Additional cleanup and modernization --- .../Internal/ObservableBackedBindingList.cs | 6 +- ...dStringUsageInRawQueriesCodeFixProvider.cs | 1 - ...osmosManyToManyJoinEntityTypeConvention.cs | 3 +- .../Query/Internal/CosmosEqualsTranslator.cs | 4 +- ...osmosProjectionBindingExpressionVisitor.cs | 4 +- .../CosmosSqlTranslatingExpressionVisitor.cs | 32 ++++--- .../Internal/CosmosStringMethodTranslator.cs | 7 +- ...eConverterCompensatingExpressionVisitor.cs | 4 +- .../Internal/CosmosExecutionStrategy.cs | 5 +- .../Design/Internal/CSharpHelper.cs | 4 +- .../Migrations/Design/MigrationsBundle.cs | 3 +- .../Scaffolding/Internal/CSharpUtilities.cs | 7 +- ...yExpressionTranslatingExpressionVisitor.cs | 14 ++-- ...emoryProjectionBindingExpressionVisitor.cs | 3 +- ...yableMethodTranslatingExpressionVisitor.cs | 10 +-- .../RelationalPropertyExtensions.cs | 3 +- .../RelationalModelValidator.cs | 12 ++- ...elationalQueryFilterRewritingConvention.cs | 6 +- .../Conventions/SharedTableConvention.cs | 6 +- ...ionalProjectionBindingExpressionVisitor.cs | 3 +- ...eConverterCompensatingExpressionVisitor.cs | 4 +- .../Query/QuerySqlGenerator.cs | 2 +- ...yableMethodTranslatingExpressionVisitor.cs | 2 +- ...sitor.ShaperProcessingExpressionVisitor.cs | 5 +- ...lationalSqlTranslatingExpressionVisitor.cs | 18 ++-- .../Query/SqlExpressions/SelectExpression.cs | 84 ++++++++----------- .../SqlExpressions/SqlBinaryExpression.cs | 2 +- .../Query/SqlNullabilityProcessor.cs | 36 ++++---- .../Storage/RelationalTypeMapping.cs | 3 +- .../Extensions/SqlServerIndexExtensions.cs | 4 +- .../Extensions/SqlServerPropertyExtensions.cs | 9 +- .../SqlServerOnDeleteConvention.cs | 3 +- .../SqlServerTemporalConvention.cs | 3 +- .../SqlServerMigrationsSqlGenerator.cs | 14 ++-- ...rchConditionConvertingExpressionVisitor.cs | 18 ++-- .../SqlServerStringMethodTranslator.cs | 2 +- .../Internal/SqlServerDatabaseCreator.cs | 9 +- .../Internal/SqlServerTypeMappingSource.cs | 2 +- .../Query/Internal/SqliteMathTranslator.cs | 2 +- .../SqliteQueryTranslationPostprocessor.cs | 2 +- .../Internal/SqliteStringMethodTranslator.cs | 2 +- .../Internal/InternalEntityEntry.cs | 27 ++---- .../Internal/NavigationFixer.cs | 13 +-- .../ChangeTracking/Internal/StateManager.cs | 3 +- src/EFCore/ChangeTracking/LocalView.cs | 11 +-- .../Internal/ExpressionExtensions.cs | 16 +--- src/EFCore/Metadata/Internal/EntityType.cs | 4 +- .../Metadata/Internal/EntityTypeExtensions.cs | 3 +- .../Internal/PropertyAccessorsFactory.cs | 1 - .../Internal/PropertyBaseExtensions.cs | 12 +-- .../TypeConfigurationTypeExtensions.cs | 6 +- ...ingExpressionVisitor.ExpressionVisitors.cs | 12 +-- .../NavigationExpandingExpressionVisitor.cs | 2 +- .../NullCheckRemovingExpressionVisitor.cs | 15 +--- .../ParameterExtractingExpressionVisitor.cs | 2 +- .../QueryOptimizingExpressionVisitor.cs | 18 ++-- ...yableMethodNormalizingExpressionVisitor.cs | 3 +- .../Query/ReplacingExpressionVisitor.cs | 5 +- .../ShapedQueryCompilingExpressionVisitor.cs | 15 ++-- .../SqliteCommand.cs | 4 +- .../SqliteConnectionInternal.cs | 4 +- .../SqliteConnectionStringBuilder.cs | 12 +-- .../SqliteDataReader.cs | 4 +- .../SqliteDataRecord.cs | 10 +-- .../SqliteException.cs | 4 +- src/Shared/ExpressionExtensions.cs | 13 +-- src/dotnet-ef/Program.cs | 3 +- .../CommandLineApplication.cs | 3 +- .../CustomPartitionKeyIdGenerator.cs | 9 +- .../Design/SnapshotModelProcessorTest.cs | 4 +- .../Query/NullSemanticsQueryTestBase.cs | 4 +- .../TestRelationalTypeMappingSource.cs | 2 +- .../GraphUpdatesTestBaseOneToMany.cs | 12 +-- .../GraphUpdatesTestBaseOneToManyAk.cs | 9 +- .../GraphUpdatesTestBaseOneToOne.cs | 15 ++-- .../GraphUpdatesTestBaseOneToOneAk.cs | 15 ++-- .../ManyToManyFieldsLoadTestBase.cs | 2 +- .../ManyToManyLoadTestBase.cs | 2 +- .../Query/GearsOfWarQueryTestBase.cs | 2 +- ...NorthwindEFPropertyIncludeQueryTestBase.cs | 29 ++----- .../NorthwindStringIncludeQueryTestBase.cs | 29 ++----- .../ExpectedQueryRewritingVisitor.cs | 32 +++---- .../InjectJoinWithSelfExpressionMutator.cs | 6 +- .../InjectOrderByPropertyExpressionMutator.cs | 5 +- .../InjectThenByPropertyExpressionMutator.cs | 3 +- .../InjectWhereExpressionMutator.cs | 9 +- .../UnidirectionalManyToManyLoadTestBase.cs | 2 +- .../TestUtilities/TestEnvironment.cs | 2 +- .../ChangeTracking/ChangeTrackerTest.cs | 3 +- .../ChangeTracking/Internal/FixupTest.cs | 6 +- .../Internal/InternalClrEntityEntryTest.cs | 4 +- 91 files changed, 299 insertions(+), 495 deletions(-) diff --git a/src/EFCore.Abstractions/ChangeTracking/Internal/ObservableBackedBindingList.cs b/src/EFCore.Abstractions/ChangeTracking/Internal/ObservableBackedBindingList.cs index 917b6386374..005cf82c3cf 100644 --- a/src/EFCore.Abstractions/ChangeTracking/Internal/ObservableBackedBindingList.cs +++ b/src/EFCore.Abstractions/ChangeTracking/Internal/ObservableBackedBindingList.cs @@ -201,8 +201,7 @@ private void ObservableCollectionChanged(object? sender, NotifyCollectionChanged Clear(); } - if (e.Action == NotifyCollectionChangedAction.Remove - || e.Action == NotifyCollectionChangedAction.Replace) + if (e.Action is NotifyCollectionChangedAction.Remove or NotifyCollectionChangedAction.Replace) { foreach (T entity in e.OldItems!) { @@ -210,8 +209,7 @@ private void ObservableCollectionChanged(object? sender, NotifyCollectionChanged } } - if (e.Action == NotifyCollectionChangedAction.Add - || e.Action == NotifyCollectionChangedAction.Replace) + if (e.Action is NotifyCollectionChangedAction.Add or NotifyCollectionChangedAction.Replace) { foreach (T entity in e.NewItems!) { diff --git a/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesCodeFixProvider.cs b/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesCodeFixProvider.cs index 89b8e8f8048..9a6d0f5cbbf 100644 --- a/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesCodeFixProvider.cs +++ b/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesCodeFixProvider.cs @@ -24,7 +24,6 @@ public override FixAllProvider GetFixAllProvider() public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; - var span = context.Span; var cancellationToken = context.CancellationToken; // We report only 1 diagnostic per span, so this is ok diff --git a/src/EFCore.Cosmos/Metadata/Conventions/CosmosManyToManyJoinEntityTypeConvention.cs b/src/EFCore.Cosmos/Metadata/Conventions/CosmosManyToManyJoinEntityTypeConvention.cs index 3ce440bbcc3..cd90484f570 100644 --- a/src/EFCore.Cosmos/Metadata/Conventions/CosmosManyToManyJoinEntityTypeConvention.cs +++ b/src/EFCore.Cosmos/Metadata/Conventions/CosmosManyToManyJoinEntityTypeConvention.cs @@ -41,8 +41,7 @@ public virtual void ProcessEntityTypeAnnotationChanged( IConventionAnnotation? oldAnnotation, IConventionContext context) { - if (name == CosmosAnnotationNames.PartitionKeyName - || name == CosmosAnnotationNames.ContainerName) + if (name is CosmosAnnotationNames.PartitionKeyName or CosmosAnnotationNames.ContainerName) { foreach (var skipNavigation in entityTypeBuilder.Metadata.GetSkipNavigations()) { diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosEqualsTranslator.cs b/src/EFCore.Cosmos/Query/Internal/CosmosEqualsTranslator.cs index 17439669e9f..12a0b4a9b3c 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosEqualsTranslator.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosEqualsTranslator.cs @@ -58,8 +58,8 @@ public CosmosEqualsTranslator(ISqlExpressionFactory sqlExpressionFactory) && right != null) { return left.Type.UnwrapNullableType() == right.Type.UnwrapNullableType() - || (right.Type == typeof(object) && (right is SqlParameterExpression || right is SqlConstantExpression)) - || (left.Type == typeof(object) && (left is SqlParameterExpression || left is SqlConstantExpression)) + || (right.Type == typeof(object) && right is SqlParameterExpression or SqlConstantExpression) + || (left.Type == typeof(object) && left is SqlParameterExpression or SqlConstantExpression) ? _sqlExpressionFactory.Equal(left, right) : _sqlExpressionFactory.Constant(false); } diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs index 75b7352423c..b0c81f4b6c1 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs @@ -92,9 +92,7 @@ public override Expression Visit(Expression expression) return null; } - if (expression is NewExpression - || expression is MemberInitExpression - || expression is EntityShaperExpression) + if (expression is NewExpression or MemberInitExpression or EntityShaperExpression) { return base.Visit(expression); } diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs index 792d27e216a..e9457185276 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs @@ -187,8 +187,7 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) var visitedLeft = Visit(left); var visitedRight = Visit(right); - if ((binaryExpression.NodeType == ExpressionType.Equal - || binaryExpression.NodeType == ExpressionType.NotEqual) + if (binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual // Visited expression could be null, We need to pass MemberInitExpression && TryRewriteEntityEquality( binaryExpression.NodeType, visitedLeft ?? left, visitedRight ?? right, equalsMethod: false, out var result)) @@ -279,21 +278,23 @@ bool IsGetTypeMethodCall(Expression expression, out EntityReferenceExpression en static bool IsTypeConstant(Expression expression, out Type type) { type = null; - if (expression is not UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression - || unaryExpression.Operand is not ConstantExpression constantExpression) + + if (expression is UnaryExpression + { + NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked, + Operand: ConstantExpression { Value: Type t } + }) { - return false; + type = t; + return type != null; } - type = constantExpression.Value as Type; - return type != null; + return false; } static bool TryUnwrapConvertToObject(Expression expression, out Expression operand) { - if (expression is UnaryExpression convertExpression - && (convertExpression.NodeType == ExpressionType.Convert - || convertExpression.NodeType == ExpressionType.ConvertChecked) + if (expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convertExpression && expression.Type == typeof(object)) { operand = convertExpression.Operand; @@ -615,8 +616,7 @@ Expression TranslateContains(Expression untranslatedItem, Expression untranslate } static Expression RemoveObjectConvert(Expression expression) - => expression is UnaryExpression unaryExpression - && (unaryExpression.NodeType == ExpressionType.Convert || unaryExpression.NodeType == ExpressionType.ConvertChecked) + => expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression && unaryExpression.Type == typeof(object) ? unaryExpression.Operand : expression; @@ -672,9 +672,7 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) var operand = Visit(unaryExpression.Operand); if (operand is EntityReferenceExpression entityReferenceExpression - && (unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked - || unaryExpression.NodeType == ExpressionType.TypeAs)) + && unaryExpression.NodeType is ExpressionType.Convert or ExpressionType.ConvertChecked or ExpressionType.TypeAs) { return entityReferenceExpression.Convert(unaryExpression.Type); } @@ -779,9 +777,7 @@ ObjectArrayProjectionExpression objectArrayProjectionExpression private static Expression TryRemoveImplicitConvert(Expression expression) { - if (expression is UnaryExpression unaryExpression - && (unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked)) + if (expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression) { var innerType = unaryExpression.Operand.Type.UnwrapNullableType(); if (innerType.IsEnum) diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosStringMethodTranslator.cs b/src/EFCore.Cosmos/Query/Internal/CosmosStringMethodTranslator.cs index 182ff6c2511..7a644925a6c 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosStringMethodTranslator.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosStringMethodTranslator.cs @@ -235,9 +235,10 @@ public CosmosStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactory) { var comparisonTypeArgument = arguments[^1]; - if (comparisonTypeArgument is SqlConstantExpression { Value: StringComparison comparisonTypeArgumentValue } - && (comparisonTypeArgumentValue == StringComparison.OrdinalIgnoreCase - || comparisonTypeArgumentValue == StringComparison.Ordinal)) + if (comparisonTypeArgument is SqlConstantExpression + { + Value: StringComparison comparisonTypeArgumentValue and (StringComparison.OrdinalIgnoreCase or StringComparison.Ordinal) + }) { return StringComparisonWithComparisonTypeArgumentInstance.Equals(method) ? comparisonTypeArgumentValue == StringComparison.OrdinalIgnoreCase diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosValueConverterCompensatingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosValueConverterCompensatingExpressionVisitor.cs index 7ab2250452a..93186137780 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosValueConverterCompensatingExpressionVisitor.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosValueConverterCompensatingExpressionVisitor.cs @@ -104,9 +104,7 @@ private SqlExpression TryCompensateForBoolWithValueConverter(SqlExpression sqlEx TryCompensateForBoolWithValueConverter(sqlUnaryExpression.Operand)); } - if (sqlExpression is SqlBinaryExpression sqlBinaryExpression - && (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso - || sqlBinaryExpression.OperatorType == ExpressionType.OrElse)) + if (sqlExpression is SqlBinaryExpression { OperatorType: ExpressionType.AndAlso or ExpressionType.OrElse } sqlBinaryExpression) { return sqlBinaryExpression.Update( TryCompensateForBoolWithValueConverter(sqlBinaryExpression.Left), diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosExecutionStrategy.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosExecutionStrategy.cs index af86cd955b7..9dd2b9961f9 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosExecutionStrategy.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosExecutionStrategy.cs @@ -103,10 +103,7 @@ protected override bool ShouldRetryOn(Exception exception) }; static bool IsTransient(HttpStatusCode statusCode) - => statusCode == HttpStatusCode.ServiceUnavailable - || statusCode == HttpStatusCode.TooManyRequests - || statusCode == HttpStatusCode.RequestTimeout - || statusCode == HttpStatusCode.Gone; + => statusCode is HttpStatusCode.ServiceUnavailable or HttpStatusCode.TooManyRequests or HttpStatusCode.RequestTimeout or HttpStatusCode.Gone; } /// diff --git a/src/EFCore.Design/Design/Internal/CSharpHelper.cs b/src/EFCore.Design/Design/Internal/CSharpHelper.cs index ea3fb0f8fc8..5d6631b8b80 100644 --- a/src/EFCore.Design/Design/Internal/CSharpHelper.cs +++ b/src/EFCore.Design/Design/Internal/CSharpHelper.cs @@ -1501,9 +1501,7 @@ private static bool IsIdentifierStartCharacter(char ch) { if (ch < 'a') { - return ch >= 'A' - && (ch <= 'Z' - || ch == '_'); + return ch is >= 'A' and (<= 'Z' or '_'); } if (ch <= 'z') diff --git a/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs b/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs index d41e932e573..e9c4c28173a 100644 --- a/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs +++ b/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs @@ -46,8 +46,7 @@ public static int Execute(string? context, Assembly assembly, Assembly startupAs } catch (Exception ex) { - if (ex is CommandParsingException - || ex is OperationException) + if (ex is CommandParsingException or OperationException) { Reporter.WriteVerbose(ex.ToString()); } diff --git a/src/EFCore.Design/Scaffolding/Internal/CSharpUtilities.cs b/src/EFCore.Design/Scaffolding/Internal/CSharpUtilities.cs index 1faaea89f72..fd23c88501f 100644 --- a/src/EFCore.Design/Scaffolding/Internal/CSharpUtilities.cs +++ b/src/EFCore.Design/Scaffolding/Internal/CSharpUtilities.cs @@ -223,9 +223,7 @@ private static bool IsIdentifierStartCharacter(char ch) { if (ch < 'a') { - return ch >= 'A' - && (ch <= 'Z' - || ch == '_'); + return ch is >= 'A' and (<= 'Z' or '_'); } if (ch <= 'z') @@ -242,8 +240,7 @@ private static bool IsIdentifierPartCharacter(char ch) { return ch < 'A' ? ch is >= '0' and <= '9' - : ch <= 'Z' - || ch == '_'; + : ch is <= 'Z' or '_'; } if (ch <= 'z') diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs index 5db2946faca..16dda60d3c5 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs @@ -162,7 +162,7 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) return Visit(ConvertObjectArrayEqualityComparison(binaryExpression.Left, binaryExpression.Right)); } - if ((binaryExpression.NodeType == ExpressionType.Equal || binaryExpression.NodeType == ExpressionType.NotEqual) + if (binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual && (binaryExpression.Left.IsNullConstantExpression() || binaryExpression.Right.IsNullConstantExpression())) { var nonNullExpression = binaryExpression.Left.IsNullConstantExpression() ? binaryExpression.Right : binaryExpression.Left; @@ -232,8 +232,7 @@ static Expression RemoveConvert(Expression e) return QueryCompilationContext.NotTranslatedExpression; } - if ((binaryExpression.NodeType == ExpressionType.Equal - || binaryExpression.NodeType == ExpressionType.NotEqual) + if (binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual // Visited expression could be null, We need to pass MemberInitExpression && TryRewriteEntityEquality( binaryExpression.NodeType, @@ -252,8 +251,7 @@ static Expression RemoveConvert(Expression e) newRight = ConvertToNullable(newRight); } - if ((binaryExpression.NodeType == ExpressionType.Equal - || binaryExpression.NodeType == ExpressionType.NotEqual) + if (binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual && TryUseComparer(newLeft, newRight, out var updatedExpression)) { if (binaryExpression.NodeType == ExpressionType.NotEqual) @@ -578,7 +576,7 @@ 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))); + && memberName is nameof(Nullable.Value) or nameof(Nullable.HasValue)); } /// @@ -1061,9 +1059,7 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) } if (newOperand is EntityReferenceExpression entityReferenceExpression - && (unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked - || unaryExpression.NodeType == ExpressionType.TypeAs)) + && unaryExpression.NodeType is ExpressionType.Convert or ExpressionType.ConvertChecked or ExpressionType.TypeAs) { return entityReferenceExpression.Convert(unaryExpression.Type); } diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs index 8ad863f1612..280c75cf516 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs @@ -499,8 +499,7 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) { var operand = Visit(unaryExpression.Operand); - return (unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked) + return unaryExpression.NodeType is ExpressionType.Convert or ExpressionType.ConvertChecked && unaryExpression.Type == operand.Type ? operand : unaryExpression.Update(MatchTypes(operand, unaryExpression.Operand.Type)); diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs index a71aa209c08..ea1a5417695 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs @@ -441,7 +441,7 @@ private static ShapedQueryExpression CreateShapedQueryExpressionStatic(IEntityTy return memberInitExpression.Update(updatedNewExpression, newBindings); - case EntityShaperExpression { ValueBufferExpression: ProjectionBindingExpression projectionBindingExpression } entityShaperExpression: + case EntityShaperExpression { ValueBufferExpression: ProjectionBindingExpression } entityShaperExpression: return entityShaperExpression; default: @@ -1174,11 +1174,9 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp } protected override Expression VisitExtension(Expression extensionExpression) - => extensionExpression is EntityShaperExpression - || extensionExpression is ShapedQueryExpression - || extensionExpression is GroupByShaperExpression - ? extensionExpression - : base.VisitExtension(extensionExpression); + => extensionExpression is EntityShaperExpression or ShapedQueryExpression or GroupByShaperExpression + ? extensionExpression + : base.VisitExtension(extensionExpression); private Expression? TryExpand(Expression? source, MemberIdentity member) { diff --git a/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs b/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs index 088bc3c0865..7b100aed1cb 100644 --- a/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs @@ -1737,8 +1737,7 @@ public static IEnumerable GetMappedStoreObjects( yield return declaringStoreObject.Value; } - if (storeObjectType == StoreObjectType.Function - || storeObjectType == StoreObjectType.SqlQuery) + if (storeObjectType is StoreObjectType.Function or StoreObjectType.SqlQuery) { yield break; } diff --git a/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs b/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs index eeea8151f91..a65590104d6 100644 --- a/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs +++ b/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs @@ -2047,9 +2047,9 @@ private static void ValidateNonTphMapping(IEntityType rootEntityType, StoreObjec private static void ValidateTphMapping(IEntityType rootEntityType, StoreObjectType storeObjectType) { - var isSproc = storeObjectType == StoreObjectType.DeleteStoredProcedure - || storeObjectType == StoreObjectType.InsertStoredProcedure - || storeObjectType == StoreObjectType.UpdateStoredProcedure; + var isSproc = storeObjectType is StoreObjectType.DeleteStoredProcedure + or StoreObjectType.InsertStoredProcedure + or StoreObjectType.UpdateStoredProcedure; var rootSproc = isSproc ? StoredProcedure.FindDeclaredStoredProcedure(rootEntityType, storeObjectType) : null; var rootId = StoreObjectIdentifier.Create(rootEntityType, storeObjectType); foreach (var entityType in rootEntityType.GetDerivedTypes()) @@ -2344,8 +2344,7 @@ private static IEnumerable GetAllMappedStoreObjects( yield return declaringStoreObject.Value; } - if (storeObjectType == StoreObjectType.Function - || storeObjectType == StoreObjectType.SqlQuery) + if (storeObjectType is StoreObjectType.Function or StoreObjectType.SqlQuery) { yield break; } @@ -2372,8 +2371,7 @@ private static IEnumerable GetAllMappedStoreObjects( else { var declaringStoreObject = StoreObjectIdentifier.Create(property.DeclaringEntityType, storeObjectType); - if (storeObjectType == StoreObjectType.Function - || storeObjectType == StoreObjectType.SqlQuery) + if (storeObjectType is StoreObjectType.Function or StoreObjectType.SqlQuery) { if (declaringStoreObject != null) { diff --git a/src/EFCore.Relational/Metadata/Conventions/RelationalQueryFilterRewritingConvention.cs b/src/EFCore.Relational/Metadata/Conventions/RelationalQueryFilterRewritingConvention.cs index 906368074a4..8453e441377 100644 --- a/src/EFCore.Relational/Metadata/Conventions/RelationalQueryFilterRewritingConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/RelationalQueryFilterRewritingConvention.cs @@ -67,9 +67,9 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp { var methodName = methodCallExpression.Method.Name; if (methodCallExpression.Method.DeclaringType == typeof(RelationalQueryableExtensions) - && (methodName == nameof(RelationalQueryableExtensions.FromSqlRaw) - || methodName == nameof(RelationalQueryableExtensions.FromSqlInterpolated) - || methodName == nameof(RelationalQueryableExtensions.FromSql))) + && methodName is nameof(RelationalQueryableExtensions.FromSqlRaw) + or nameof(RelationalQueryableExtensions.FromSqlInterpolated) + or nameof(RelationalQueryableExtensions.FromSql)) { var newSource = (EntityQueryRootExpression)Visit(methodCallExpression.Arguments[0]); diff --git a/src/EFCore.Relational/Metadata/Conventions/SharedTableConvention.cs b/src/EFCore.Relational/Metadata/Conventions/SharedTableConvention.cs index d4dbd48d880..7c8475c9401 100644 --- a/src/EFCore.Relational/Metadata/Conventions/SharedTableConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/SharedTableConvention.cs @@ -239,10 +239,8 @@ private static void TryUniquifyColumnNames( { if (property.GetAfterSaveBehavior() == PropertySaveBehavior.Save && otherProperty.GetAfterSaveBehavior() == PropertySaveBehavior.Save - && (property.ValueGenerated == ValueGenerated.Never - || property.ValueGenerated == ValueGenerated.OnUpdateSometimes) - && (otherProperty.ValueGenerated == ValueGenerated.Never - || otherProperty.ValueGenerated == ValueGenerated.OnUpdateSometimes)) + && property.ValueGenerated is ValueGenerated.Never or ValueGenerated.OnUpdateSometimes + && otherProperty.ValueGenerated is ValueGenerated.Never or ValueGenerated.OnUpdateSometimes) { // Handle this with a default value convention #9329 property.Builder.ValueGenerated(ValueGenerated.OnUpdateSometimes); diff --git a/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs index 4dd749c11e3..c310bf18f89 100644 --- a/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs @@ -622,8 +622,7 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) { var operand = Visit(unaryExpression.Operand); - return (unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked) + return unaryExpression.NodeType is ExpressionType.Convert or ExpressionType.ConvertChecked && unaryExpression.Type == operand.Type ? operand : unaryExpression.Update(MatchTypes(operand, unaryExpression.Operand.Type)); diff --git a/src/EFCore.Relational/Query/Internal/RelationalValueConverterCompensatingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/RelationalValueConverterCompensatingExpressionVisitor.cs index b6802750a1d..b82037f6aa0 100644 --- a/src/EFCore.Relational/Query/Internal/RelationalValueConverterCompensatingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/RelationalValueConverterCompensatingExpressionVisitor.cs @@ -157,9 +157,7 @@ private Expression VisitLeftJoin(LeftJoinExpression leftJoinExpression) TryCompensateForBoolWithValueConverter(sqlUnaryExpression.Operand)); } - if (sqlExpression is SqlBinaryExpression sqlBinaryExpression - && (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso - || sqlBinaryExpression.OperatorType == ExpressionType.OrElse)) + if (sqlExpression is SqlBinaryExpression { OperatorType: ExpressionType.AndAlso or ExpressionType.OrElse } sqlBinaryExpression) { return sqlBinaryExpression.Update( TryCompensateForBoolWithValueConverter(sqlBinaryExpression.Left), diff --git a/src/EFCore.Relational/Query/QuerySqlGenerator.cs b/src/EFCore.Relational/Query/QuerySqlGenerator.cs index 839822be9dd..a2d0e963fa4 100644 --- a/src/EFCore.Relational/Query/QuerySqlGenerator.cs +++ b/src/EFCore.Relational/Query/QuerySqlGenerator.cs @@ -1072,7 +1072,7 @@ protected virtual void GenerateOrderings(SelectExpression selectExpression) if (selectExpression.Limit == null && selectExpression.Offset == null) { - orderings.RemoveAll(oe => oe.Expression is SqlConstantExpression || oe.Expression is SqlParameterExpression); + orderings.RemoveAll(oe => oe.Expression is SqlConstantExpression or SqlParameterExpression); } if (orderings.Count > 0) diff --git a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs index bc8643d363d..9d656d89cb7 100644 --- a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs @@ -2002,7 +2002,7 @@ static bool IsValidSelectorForJsonArrayElementAccess(Expression expression, Json if (expression is MemberExpression { Expression: RelationalEntityShaperExpression { ValueBufferExpression: JsonQueryExpression memberJqe } - } memberExpression + } && JsonQueryExpressionIsRootedIn(memberJqe, baselineJsonQuery)) { return true; diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs index cf7b0db7750..3f1855a1f3d 100644 --- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs @@ -522,7 +522,7 @@ protected override Expression VisitExtension(Expression extensionExpression) } case RelationalEntityShaperExpression entityShaperExpression - when _inline && entityShaperExpression.ValueBufferExpression is ProjectionBindingExpression projectionBindingExpression: + when _inline && entityShaperExpression.ValueBufferExpression is ProjectionBindingExpression: { if (entityShaperExpression.EntityType.GetMappingStrategy() == RelationalAnnotationNames.TpcMappingStrategy) { @@ -1876,8 +1876,7 @@ public bool ContainsCollectionMaterialization(Expression expression) return expression; } - if (expression is RelationalCollectionShaperExpression - || expression is RelationalSplitCollectionShaperExpression) + if (expression is RelationalCollectionShaperExpression or RelationalSplitCollectionShaperExpression) { _containsCollection = true; diff --git a/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs index b59f8f1eae0..374926e5819 100644 --- a/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs @@ -335,7 +335,7 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) right = rightOperand!; } - if ((binaryExpression.NodeType == ExpressionType.Equal || binaryExpression.NodeType == ExpressionType.NotEqual) + if (binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual && (left.IsNullConstantExpression() || right.IsNullConstantExpression())) { var nonNullExpression = left.IsNullConstantExpression() ? right : left; @@ -398,8 +398,7 @@ static Expression RemoveConvert(Expression e) var visitedLeft = Visit(left); var visitedRight = Visit(right); - if ((binaryExpression.NodeType == ExpressionType.Equal - || binaryExpression.NodeType == ExpressionType.NotEqual) + if (binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual // Visited expression could be null, We need to pass MemberInitExpression && TryRewriteEntityEquality( binaryExpression.NodeType, @@ -577,9 +576,7 @@ static bool IsTypeConstant(Expression expression, out Type? type) static bool TryUnwrapConvertToObject(Expression expression, out Expression? operand) { - if (expression is UnaryExpression convertExpression - && (convertExpression.NodeType == ExpressionType.Convert - || convertExpression.NodeType == ExpressionType.ConvertChecked) + if (expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convertExpression && expression.Type == typeof(object)) { operand = convertExpression.Operand; @@ -1529,9 +1526,7 @@ private static EnumerableExpression ProcessSelector(EnumerableExpression enumera private static Expression TryRemoveImplicitConvert(Expression expression) { - if (expression is UnaryExpression unaryExpression - && (unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked)) + if (expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression) { var innerType = unaryExpression.Operand.Type.UnwrapNullableType(); if (innerType.IsEnum) @@ -1557,8 +1552,7 @@ private static Expression TryRemoveImplicitConvert(Expression expression) } private static Expression RemoveObjectConvert(Expression expression) - => expression is UnaryExpression unaryExpression - && (unaryExpression.NodeType == ExpressionType.Convert || unaryExpression.NodeType == ExpressionType.ConvertChecked) + => expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression && unaryExpression.Type == typeof(object) ? unaryExpression.Operand : expression; @@ -1885,7 +1879,7 @@ private static bool CanEvaluate(Expression expression) }; private static bool IsNullSqlConstantExpression(Expression expression) - => expression is SqlConstantExpression { Value: null } sqlConstant; + => expression is SqlConstantExpression { Value: null }; [DebuggerStepThrough] private static bool TranslationFailed(Expression? original, Expression? translation, out SqlExpression? castTranslation) diff --git a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs index d515782c6df..f9a6294b358 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs @@ -26,17 +26,6 @@ public sealed partial class SelectExpression : TableExpressionBase private const string DiscriminatorColumnAlias = "Discriminator"; private static readonly IdentifierComparer IdentifierComparerInstance = new(); - private static readonly Dictionary MirroredOperationMap = - new() - { - { ExpressionType.Equal, ExpressionType.Equal }, - { ExpressionType.NotEqual, ExpressionType.NotEqual }, - { ExpressionType.LessThan, ExpressionType.GreaterThan }, - { ExpressionType.LessThanOrEqual, ExpressionType.GreaterThanOrEqual }, - { ExpressionType.GreaterThan, ExpressionType.LessThan }, - { ExpressionType.GreaterThanOrEqual, ExpressionType.LessThanOrEqual } - }; - private readonly List _projection = new(); private readonly List _tables = new(); private readonly List _tableReferences = new(); @@ -632,7 +621,7 @@ public void ApplyTags(ISet tags) public void ApplyDistinct() { if (_clientProjections.Count > 0 - && _clientProjections.Any(e => e is ShapedQueryExpression { ResultCardinality: ResultCardinality.Enumerable } sqe)) + && _clientProjections.Any(e => e is ShapedQueryExpression { ResultCardinality: ResultCardinality.Enumerable })) { throw new InvalidOperationException(RelationalStrings.DistinctOnCollectionNotSupported); } @@ -852,8 +841,7 @@ public Expression ApplyProjection( containsCollection = true; } - if (sqe.ResultCardinality == ResultCardinality.Single - || sqe.ResultCardinality == ResultCardinality.SingleOrDefault) + if (sqe.ResultCardinality is ResultCardinality.Single or ResultCardinality.SingleOrDefault) { containsSingleResult = true; } @@ -966,9 +954,7 @@ Expression AddGroupByKeySelectorToProjection( return memberInitExpression.Update((NewExpression)updatedNewExpression, newBindings); - case UnaryExpression unaryExpression - when unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked: + case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression: return unaryExpression.Update( AddGroupByKeySelectorToProjection( selectExpression, clientProjectionList, projectionBindingMap, unaryExpression.Operand)); @@ -1043,8 +1029,7 @@ Expression AddGroupByKeySelectorToProjection( baseSelectExpression = (SelectExpression)cloningExpressionVisitor!.Visit(this); // We mark this as mutable because the split query will combine into this and take it over. baseSelectExpression._mutable = true; - if (resultCardinality == ResultCardinality.Single - || resultCardinality == ResultCardinality.SingleOrDefault) + if (resultCardinality is ResultCardinality.Single or ResultCardinality.SingleOrDefault) { // Update limit since split queries don't need limit 2 if (pushdownOccurred) @@ -1118,9 +1103,10 @@ static void UpdateLimit(SelectExpression selectExpression) break; } - case ShapedQueryExpression shapedQueryExpression - when shapedQueryExpression.ResultCardinality == ResultCardinality.Single - || shapedQueryExpression.ResultCardinality == ResultCardinality.SingleOrDefault: + case ShapedQueryExpression + { + ResultCardinality: ResultCardinality.Single or ResultCardinality.SingleOrDefault + } shapedQueryExpression: { var innerSelectExpression = (SelectExpression)shapedQueryExpression.QueryExpression; var innerShaperExpression = shapedQueryExpression.ShaperExpression; @@ -1695,7 +1681,7 @@ ConstantExpression AddJsonProjection(JsonQueryExpression jsonQueryExpression, Js { additionalPathList.Add((additionalPathSegment.PropertyName, null, null)); } - else if (additionalPathSegment.ArrayIndex is SqlConstantExpression { Value: int intValue } sqlConstant) + else if (additionalPathSegment.ArrayIndex is SqlConstantExpression { Value: int intValue }) { additionalPathList.Add((null, intValue, null)); } @@ -1764,9 +1750,7 @@ public void ReplaceProjection(IReadOnlyDictionary foreach (var (projectionMember, expression) in projectionMapping) { Check.DebugAssert( - expression is SqlExpression - || expression is EntityProjectionExpression - || expression is JsonQueryExpression, + expression is SqlExpression or EntityProjectionExpression or JsonQueryExpression, "Invalid operation in the projection."); _projectionMapping[projectionMember] = expression; } @@ -1784,10 +1768,7 @@ public void ReplaceProjection(IReadOnlyList clientProjections) foreach (var expression in clientProjections) { Check.DebugAssert( - expression is SqlExpression - || expression is EntityProjectionExpression - || expression is ShapedQueryExpression - || expression is JsonQueryExpression, + expression is SqlExpression or EntityProjectionExpression or ShapedQueryExpression or JsonQueryExpression, "Invalid operation in the projection."); _clientProjections.Add(expression); _aliasForClientProjections.Add(null); @@ -2105,9 +2086,7 @@ private static void PopulateGroupByTerms( break; - case UnaryExpression unaryExpression - when unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked: + case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression: PopulateGroupByTerms(unaryExpression.Operand, groupByTerms, groupByAliases, name); break; @@ -2916,7 +2895,7 @@ private Expression AddJoin( var innerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Inner")!; var outerClientEval = _clientProjections.Count > 0; var innerClientEval = innerSelectExpression._clientProjections.Count > 0; - var innerNullable = joinType == JoinType.LeftJoin || joinType == JoinType.OuterApply; + var innerNullable = joinType is JoinType.LeftJoin or JoinType.OuterApply; if (outerClientEval) { @@ -3019,8 +2998,7 @@ private void AddJoin( { innerPushdownOccurred = false; // Try to convert Apply to normal join - if (joinType == JoinType.CrossApply - || joinType == JoinType.OuterApply) + if (joinType is JoinType.CrossApply or JoinType.OuterApply) { var limit = innerSelectExpression.Limit; var offset = innerSelectExpression.Offset; @@ -3160,8 +3138,7 @@ private void AddJoin( if (_identifier.Count > 0 && innerSelectExpression._identifier.Count > 0) { - if (joinType == JoinType.LeftJoin - || joinType == JoinType.OuterApply) + if (joinType is JoinType.LeftJoin or JoinType.OuterApply) { _identifier.AddRange(innerSelectExpression._identifier.Select(e => (e.Column.MakeNullable(), e.Comparer))); } @@ -3327,11 +3304,11 @@ static void GetPartitions(SelectExpression selectExpression, SqlExpression sqlEx { if (sqlBinaryExpression.OperatorType == ExpressionType.Equal || (allowNonEquality - && (sqlBinaryExpression.OperatorType == ExpressionType.NotEqual - || sqlBinaryExpression.OperatorType == ExpressionType.GreaterThan - || sqlBinaryExpression.OperatorType == ExpressionType.GreaterThanOrEqual - || sqlBinaryExpression.OperatorType == ExpressionType.LessThan - || sqlBinaryExpression.OperatorType == ExpressionType.LessThanOrEqual))) + && sqlBinaryExpression.OperatorType is ExpressionType.NotEqual + or ExpressionType.GreaterThan + or ExpressionType.GreaterThanOrEqual + or ExpressionType.LessThan + or ExpressionType.LessThanOrEqual)) { if (IsContainedSql(outer, sqlBinaryExpression.Left) && IsContainedSql(inner, sqlBinaryExpression.Right)) @@ -3346,8 +3323,20 @@ static void GetPartitions(SelectExpression selectExpression, SqlExpression sqlEx { outerColumnExpressions.Add(sqlBinaryExpression.Right); + var mirroredOperation = sqlBinaryExpression.OperatorType switch + { + ExpressionType.Equal => ExpressionType.Equal, + ExpressionType.NotEqual => ExpressionType.NotEqual, + ExpressionType.LessThan => ExpressionType.GreaterThan, + ExpressionType.LessThanOrEqual => ExpressionType.GreaterThanOrEqual, + ExpressionType.GreaterThan => ExpressionType.LessThan, + ExpressionType.GreaterThanOrEqual => ExpressionType.LessThanOrEqual, + + _ => throw new InvalidOperationException("IMPOSSIBLE") + }; + return new SqlBinaryExpression( - MirroredOperationMap[sqlBinaryExpression.OperatorType], + mirroredOperation, sqlBinaryExpression.Right, sqlBinaryExpression.Left, sqlBinaryExpression.Type, @@ -3435,7 +3424,7 @@ static List ExtractColumnsFromProjectionMapping( IDictionary projectionMapping) { var result = new List(); - foreach (var (projectionMember, expression) in projectionMapping) + foreach (var (_, expression) in projectionMapping) { if (expression is EntityProjectionExpression entityProjection) { @@ -4016,9 +4005,8 @@ private SelectExpression Prune(IReadOnlyCollection? referencedColumns) var table = _tables[i]; var tableAlias = GetAliasFromTableExpressionBase(table); if (columnsMap[tableAlias] == null - && (table is LeftJoinExpression - || table is OuterApplyExpression - || table is InnerJoinExpression) // This is only valid for removable join table which are from entity splitting + // InnerJoin is only valid for removable join table which are from entity splitting + && table is LeftJoinExpression or OuterApplyExpression or InnerJoinExpression && _removableJoinTables?.Contains(i + removedTableCount) == true) { _tables.RemoveAt(i); diff --git a/src/EFCore.Relational/Query/SqlExpressions/SqlBinaryExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SqlBinaryExpression.cs index 50bc6969911..b61fded1edb 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SqlBinaryExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SqlBinaryExpression.cs @@ -139,7 +139,7 @@ protected override void Print(ExpressionPrinter expressionPrinter) } static bool RequiresBrackets(SqlExpression expression) - => expression is SqlBinaryExpression || expression is LikeExpression; + => expression is SqlBinaryExpression or LikeExpression; } /// diff --git a/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs b/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs index e715084361c..90b037fbf93 100644 --- a/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs +++ b/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs @@ -1081,8 +1081,7 @@ protected virtual SqlExpression VisitSqlBinary( var optimize = allowOptimizedExpansion; allowOptimizedExpansion = allowOptimizedExpansion - && (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso - || sqlBinaryExpression.OperatorType == ExpressionType.OrElse); + && sqlBinaryExpression.OperatorType is ExpressionType.AndAlso or ExpressionType.OrElse; var currentNonNullableColumnsCount = _nonNullableColumns.Count; var currentNullValueColumnsCount = _nullValueColumns.Count; @@ -1154,8 +1153,7 @@ protected virtual SqlExpression VisitSqlBinary( return sqlBinaryExpression.Update(left, right); } - if (sqlBinaryExpression.OperatorType == ExpressionType.Equal - || sqlBinaryExpression.OperatorType == ExpressionType.NotEqual) + if (sqlBinaryExpression.OperatorType is ExpressionType.Equal or ExpressionType.NotEqual) { var updated = sqlBinaryExpression.Update(left, right); @@ -1211,13 +1209,12 @@ protected virtual SqlExpression VisitSqlBinary( var result = sqlBinaryExpression.Update(left, right); return result is SqlBinaryExpression sqlBinaryResult - && (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso - || sqlBinaryExpression.OperatorType == ExpressionType.OrElse) + && sqlBinaryExpression.OperatorType is ExpressionType.AndAlso or ExpressionType.OrElse ? SimplifyLogicalSqlBinaryExpression(sqlBinaryResult) : result; SqlExpression AddNullConcatenationProtection(SqlExpression argument, RelationalTypeMapping typeMapping) - => argument is SqlConstantExpression || argument is SqlParameterExpression + => argument is SqlConstantExpression or SqlParameterExpression ? _sqlExpressionFactory.Constant(string.Empty, typeMapping) : _sqlExpressionFactory.Coalesce(argument, _sqlExpressionFactory.Constant(string.Empty, typeMapping)); } @@ -1346,8 +1343,7 @@ protected virtual SqlExpression VisitSqlUnary( var operand = Visit(sqlUnaryExpression.Operand, out var operandNullable); var updated = sqlUnaryExpression.Update(operand); - if (sqlUnaryExpression.OperatorType == ExpressionType.Equal - || sqlUnaryExpression.OperatorType == ExpressionType.NotEqual) + if (sqlUnaryExpression.OperatorType is ExpressionType.Equal or ExpressionType.NotEqual) { var result = ProcessNullNotNull(updated, operandNullable); @@ -1438,12 +1434,12 @@ private SqlExpression ProcessJoinPredicate(SqlExpression predicate) return result; } - if (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso - || sqlBinaryExpression.OperatorType == ExpressionType.NotEqual - || sqlBinaryExpression.OperatorType == ExpressionType.GreaterThan - || sqlBinaryExpression.OperatorType == ExpressionType.GreaterThanOrEqual - || sqlBinaryExpression.OperatorType == ExpressionType.LessThan - || sqlBinaryExpression.OperatorType == ExpressionType.LessThanOrEqual) + if (sqlBinaryExpression.OperatorType is ExpressionType.AndAlso + or ExpressionType.NotEqual + or ExpressionType.GreaterThan + or ExpressionType.GreaterThanOrEqual + or ExpressionType.LessThan + or ExpressionType.LessThanOrEqual) { return Visit(sqlBinaryExpression, allowOptimizedExpansion: true, out _); } @@ -1461,8 +1457,8 @@ private SqlExpression OptimizeComparison( bool rightNullable, out bool nullable) { - var leftNullValue = leftNullable && (left is SqlConstantExpression || left is SqlParameterExpression); - var rightNullValue = rightNullable && (right is SqlConstantExpression || right is SqlParameterExpression); + var leftNullValue = leftNullable && left is SqlConstantExpression or SqlParameterExpression; + var rightNullValue = rightNullable && right is SqlConstantExpression or SqlParameterExpression; // a == null -> a IS NULL // a != null -> a IS NOT NULL @@ -1537,8 +1533,7 @@ private SqlExpression OptimizeComparison( if (!leftNullable && !rightNullable - && (sqlBinaryExpression.OperatorType == ExpressionType.Equal - || sqlBinaryExpression.OperatorType == ExpressionType.NotEqual)) + && sqlBinaryExpression.OperatorType is ExpressionType.Equal or ExpressionType.NotEqual) { var leftUnary = left as SqlUnaryExpression; var rightUnary = right as SqlUnaryExpression; @@ -1796,8 +1791,7 @@ protected virtual SqlExpression OptimizeNonNullableNotExpression(SqlUnaryExpress { // optimizations below are only correct in 2-value logic // De Morgan's - if (sqlBinaryOperand.OperatorType == ExpressionType.AndAlso - || sqlBinaryOperand.OperatorType == ExpressionType.OrElse) + if (sqlBinaryOperand.OperatorType is ExpressionType.AndAlso or ExpressionType.OrElse) { // since entire AndAlso/OrElse expression is non-nullable, both sides of it (left and right) must also be non-nullable // so it's safe to perform recursive optimization here diff --git a/src/EFCore.Relational/Storage/RelationalTypeMapping.cs b/src/EFCore.Relational/Storage/RelationalTypeMapping.cs index 484428e7be3..a245c446b55 100644 --- a/src/EFCore.Relational/Storage/RelationalTypeMapping.cs +++ b/src/EFCore.Relational/Storage/RelationalTypeMapping.cs @@ -460,8 +460,7 @@ protected virtual string ProcessStoreType( { storeType = storeTypeNameBase + "(" + (size < 0 ? "max" : size.ToString()) + ")"; } - else if (parameters.StoreTypePostfix == StoreTypePostfix.PrecisionAndScale - || parameters.StoreTypePostfix == StoreTypePostfix.Precision) + else if (parameters.StoreTypePostfix is StoreTypePostfix.PrecisionAndScale or StoreTypePostfix.Precision) { var precision = parameters.Precision; if (precision != null) diff --git a/src/EFCore.SqlServer/Extensions/SqlServerIndexExtensions.cs b/src/EFCore.SqlServer/Extensions/SqlServerIndexExtensions.cs index 7568b318f2b..af32ab3f1dd 100644 --- a/src/EFCore.SqlServer/Extensions/SqlServerIndexExtensions.cs +++ b/src/EFCore.SqlServer/Extensions/SqlServerIndexExtensions.cs @@ -257,7 +257,7 @@ public static void SetIsCreatedOnline(this IMutableIndex index, bool? createdOnl /// The value to set. public static void SetFillFactor(this IMutableIndex index, int? fillFactor) { - if (fillFactor != null && (fillFactor <= 0 || fillFactor > 100)) + if (fillFactor is <= 0 or > 100) { throw new ArgumentOutOfRangeException(nameof(fillFactor)); } @@ -279,7 +279,7 @@ public static void SetFillFactor(this IMutableIndex index, int? fillFactor) int? fillFactor, bool fromDataAnnotation = false) { - if (fillFactor != null && (fillFactor <= 0 || fillFactor > 100)) + if (fillFactor is <= 0 or > 100) { throw new ArgumentOutOfRangeException(nameof(fillFactor)); } diff --git a/src/EFCore.SqlServer/Extensions/SqlServerPropertyExtensions.cs b/src/EFCore.SqlServer/Extensions/SqlServerPropertyExtensions.cs index 08c23997cc8..890c57a1005 100644 --- a/src/EFCore.SqlServer/Extensions/SqlServerPropertyExtensions.cs +++ b/src/EFCore.SqlServer/Extensions/SqlServerPropertyExtensions.cs @@ -811,8 +811,7 @@ private static SqlServerValueGenerationStrategy GetDefaultValueGenerationStrateg { var modelStrategy = property.DeclaringEntityType.Model.GetValueGenerationStrategy(); - if ((modelStrategy == SqlServerValueGenerationStrategy.SequenceHiLo - || modelStrategy == SqlServerValueGenerationStrategy.Sequence) + if (modelStrategy is SqlServerValueGenerationStrategy.SequenceHiLo or SqlServerValueGenerationStrategy.Sequence && IsCompatibleWithValueGeneration(property)) { return modelStrategy.Value; @@ -831,8 +830,7 @@ private static SqlServerValueGenerationStrategy GetDefaultValueGenerationStrateg { var modelStrategy = property.DeclaringEntityType.Model.GetValueGenerationStrategy(); - if ((modelStrategy == SqlServerValueGenerationStrategy.SequenceHiLo - || modelStrategy == SqlServerValueGenerationStrategy.Sequence) + if (modelStrategy is SqlServerValueGenerationStrategy.SequenceHiLo or SqlServerValueGenerationStrategy.Sequence && IsCompatibleWithValueGeneration(property, storeObject, typeMappingSource)) { return modelStrategy.Value; @@ -950,8 +948,7 @@ public static void SetValueGenerationStrategy( property.Name, property.DeclaringEntityType.DisplayName(), propertyType.ShortDisplayName())); } - if ((value == SqlServerValueGenerationStrategy.SequenceHiLo - || value == SqlServerValueGenerationStrategy.Sequence) + if (value is SqlServerValueGenerationStrategy.SequenceHiLo or SqlServerValueGenerationStrategy.Sequence && !IsCompatibleWithValueGeneration(property)) { throw new ArgumentException( diff --git a/src/EFCore.SqlServer/Metadata/Conventions/SqlServerOnDeleteConvention.cs b/src/EFCore.SqlServer/Metadata/Conventions/SqlServerOnDeleteConvention.cs index d73aa2a8f99..3c29be31606 100644 --- a/src/EFCore.SqlServer/Metadata/Conventions/SqlServerOnDeleteConvention.cs +++ b/src/EFCore.SqlServer/Metadata/Conventions/SqlServerOnDeleteConvention.cs @@ -125,8 +125,7 @@ public virtual void ProcessEntityTypeAnnotationChanged( IConventionAnnotation? oldAnnotation, IConventionContext context) { - if (name == RelationalAnnotationNames.TableName - || name == RelationalAnnotationNames.Schema) + if (name is RelationalAnnotationNames.TableName or RelationalAnnotationNames.Schema) { ProcessSkipNavigations(entityTypeBuilder.Metadata.GetDeclaredSkipNavigations()); diff --git a/src/EFCore.SqlServer/Metadata/Conventions/SqlServerTemporalConvention.cs b/src/EFCore.SqlServer/Metadata/Conventions/SqlServerTemporalConvention.cs index 3ac9a323cf4..be5829edd73 100644 --- a/src/EFCore.SqlServer/Metadata/Conventions/SqlServerTemporalConvention.cs +++ b/src/EFCore.SqlServer/Metadata/Conventions/SqlServerTemporalConvention.cs @@ -85,8 +85,7 @@ public virtual void ProcessEntityTypeAnnotationChanged( } } - if (name == SqlServerAnnotationNames.TemporalPeriodStartPropertyName - || name == SqlServerAnnotationNames.TemporalPeriodEndPropertyName) + if (name is SqlServerAnnotationNames.TemporalPeriodStartPropertyName or SqlServerAnnotationNames.TemporalPeriodEndPropertyName) { if (oldAnnotation?.Value is string oldPeriodPropertyName) { diff --git a/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs b/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs index 9b8199c32f5..e2993ce5fe4 100644 --- a/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs +++ b/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs @@ -2813,13 +2813,13 @@ static bool ColumnOperationsOnlyDifferByTemporalTableAnnotation(ColumnOperation } return unmatched.All( - a => a.Name == SqlServerAnnotationNames.IsTemporal - || a.Name == SqlServerAnnotationNames.TemporalHistoryTableName - || a.Name == SqlServerAnnotationNames.TemporalHistoryTableSchema - || a.Name == SqlServerAnnotationNames.TemporalPeriodStartPropertyName - || a.Name == SqlServerAnnotationNames.TemporalPeriodEndPropertyName - || a.Name == SqlServerAnnotationNames.TemporalPeriodStartColumnName - || a.Name == SqlServerAnnotationNames.TemporalPeriodEndColumnName); + a => a.Name is SqlServerAnnotationNames.IsTemporal + or SqlServerAnnotationNames.TemporalHistoryTableName + or SqlServerAnnotationNames.TemporalHistoryTableSchema + or SqlServerAnnotationNames.TemporalPeriodStartPropertyName + or SqlServerAnnotationNames.TemporalPeriodEndPropertyName + or SqlServerAnnotationNames.TemporalPeriodStartColumnName + or SqlServerAnnotationNames.TemporalPeriodEndColumnName); } static TOperation CopyColumnOperation(ColumnOperation source) diff --git a/src/EFCore.SqlServer/Query/Internal/SearchConditionConvertingExpressionVisitor.cs b/src/EFCore.SqlServer/Query/Internal/SearchConditionConvertingExpressionVisitor.cs index 32da0a2ef15..11aca0c9429 100644 --- a/src/EFCore.SqlServer/Query/Internal/SearchConditionConvertingExpressionVisitor.cs +++ b/src/EFCore.SqlServer/Query/Internal/SearchConditionConvertingExpressionVisitor.cs @@ -386,14 +386,14 @@ protected override Expression VisitSqlBinary(SqlBinaryExpression sqlBinaryExpres _isSearchCondition = parentIsSearchCondition; sqlBinaryExpression = sqlBinaryExpression.Update(newLeft, newRight); - var condition = sqlBinaryExpression.OperatorType == ExpressionType.AndAlso - || sqlBinaryExpression.OperatorType == ExpressionType.OrElse - || sqlBinaryExpression.OperatorType == ExpressionType.Equal - || sqlBinaryExpression.OperatorType == ExpressionType.NotEqual - || sqlBinaryExpression.OperatorType == ExpressionType.GreaterThan - || sqlBinaryExpression.OperatorType == ExpressionType.GreaterThanOrEqual - || sqlBinaryExpression.OperatorType == ExpressionType.LessThan - || sqlBinaryExpression.OperatorType == ExpressionType.LessThanOrEqual; + var condition = sqlBinaryExpression.OperatorType is ExpressionType.AndAlso + or ExpressionType.OrElse + or ExpressionType.Equal + or ExpressionType.NotEqual + or ExpressionType.GreaterThan + or ExpressionType.GreaterThanOrEqual + or ExpressionType.LessThan + or ExpressionType.LessThanOrEqual; return ApplyConversion(sqlBinaryExpression, condition); } @@ -493,7 +493,7 @@ protected override Expression VisitSqlFunction(SqlFunctionExpression sqlFunction _isSearchCondition = parentSearchCondition; var newFunction = sqlFunctionExpression.Update(instance, arguments); - var condition = sqlFunctionExpression.Name == "FREETEXT" || sqlFunctionExpression.Name == "CONTAINS"; + var condition = sqlFunctionExpression.Name is "FREETEXT" or "CONTAINS"; return ApplyConversion(newFunction, condition); } diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerStringMethodTranslator.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerStringMethodTranslator.cs index 4393d2d3e15..306648dec52 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerStringMethodTranslator.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerStringMethodTranslator.cs @@ -500,7 +500,7 @@ private SqlExpression TranslateIndexOf( // See https://docs.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql private static bool IsLikeWildChar(char c) - => c == '%' || c == '_' || c == '['; + => c is '%' or '_' or '['; private static string EscapeLikePattern(string pattern) { diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs index 25163a198bf..c85be77e61c 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerDatabaseCreator.cs @@ -297,7 +297,7 @@ await _rawSqlCommandBuilder // Unable to attach database file is thrown when file does not exist (See Issue #2810) // Unable to open the physical file is thrown when file does not exist (See Issue #2810) private static bool IsDoesNotExist(SqlException exception) - => exception.Number == 4060 || exception.Number == 1832 || exception.Number == 5120; + => exception.Number is 4060 or 1832 or 5120; // See Issue #985 private bool RetryOnExistsFailure(SqlException exception) @@ -322,12 +322,7 @@ private bool RetryOnExistsFailure(SqlException exception) // Microsoft.Data.SqlClient.SqlException: Unable to open the physical file xxxxxxx. // And (Number 18456) // Microsoft.Data.SqlClient.SqlException: Login failed for user 'xxxxxxx'. - if (exception.Number == 233 - || exception.Number == -2 - || exception.Number == 4060 - || exception.Number == 1832 - || exception.Number == 5120 - || exception.Number == 18456) + if (exception.Number is 233 or -2 or 4060 or 1832 or 5120 or 18456) { ClearPool(); return true; diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerTypeMappingSource.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerTypeMappingSource.cs index ae258e38bd7..c08810d8318 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerTypeMappingSource.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerTypeMappingSource.cs @@ -406,7 +406,7 @@ public SqlServerTypeMappingSource( var isFixedLength = mappingInfo.IsFixedLength == true; var size = mappingInfo.Size ?? (mappingInfo.IsKeyOrIndex ? 900 : null); - if (size < 0 || size > 8000) + if (size is < 0 or > 8000) { size = isFixedLength ? 8000 : null; } diff --git a/src/EFCore.Sqlite.Core/Query/Internal/SqliteMathTranslator.cs b/src/EFCore.Sqlite.Core/Query/Internal/SqliteMathTranslator.cs index 0de6635e2a0..0387d4c1cc6 100644 --- a/src/EFCore.Sqlite.Core/Query/Internal/SqliteMathTranslator.cs +++ b/src/EFCore.Sqlite.Core/Query/Internal/SqliteMathTranslator.cs @@ -84,7 +84,7 @@ public SqliteMathTranslator(ISqlExpressionFactory sqlExpressionFactory) { RelationalTypeMapping? typeMapping; List? newArguments = null; - if (sqlFunctionName == "max" || sqlFunctionName == "min") + if (sqlFunctionName is "max" or "min") { typeMapping = ExpressionExtensions.InferTypeMapping(arguments[0], arguments[1]); newArguments = new List diff --git a/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryTranslationPostprocessor.cs b/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryTranslationPostprocessor.cs index 74095a2beb9..e1a77bbd629 100644 --- a/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryTranslationPostprocessor.cs +++ b/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryTranslationPostprocessor.cs @@ -57,7 +57,7 @@ protected override Expression VisitExtension(Expression extensionExpression) } if (extensionExpression is SelectExpression selectExpression - && selectExpression.Tables.Any(t => t is CrossApplyExpression || t is OuterApplyExpression)) + && selectExpression.Tables.Any(t => t is CrossApplyExpression or OuterApplyExpression)) { throw new InvalidOperationException(SqliteStrings.ApplyNotSupported); } diff --git a/src/EFCore.Sqlite.Core/Query/Internal/SqliteStringMethodTranslator.cs b/src/EFCore.Sqlite.Core/Query/Internal/SqliteStringMethodTranslator.cs index c9c3442c421..840cabb2d30 100644 --- a/src/EFCore.Sqlite.Core/Query/Internal/SqliteStringMethodTranslator.cs +++ b/src/EFCore.Sqlite.Core/Query/Internal/SqliteStringMethodTranslator.cs @@ -389,7 +389,7 @@ private SqlExpression TranslateStartsEndsWith(SqlExpression instance, SqlExpress // See https://www.sqlite.org/lang_expr.html private static bool IsLikeWildChar(char c) - => c == '%' || c == '_'; + => c is '%' or '_'; private static string EscapeLikePattern(string pattern) { diff --git a/src/EFCore/ChangeTracking/Internal/InternalEntityEntry.cs b/src/EFCore/ChangeTracking/Internal/InternalEntityEntry.cs index 9fa4eccb2ba..dbd8d4f3d04 100644 --- a/src/EFCore/ChangeTracking/Internal/InternalEntityEntry.cs +++ b/src/EFCore/ChangeTracking/Internal/InternalEntityEntry.cs @@ -368,25 +368,20 @@ private void SetEntityState(EntityState oldState, EntityState newState, bool acc StateManager.StopTracking(this, oldState); } - if ((newState == EntityState.Deleted - || newState == EntityState.Detached) + if (newState is EntityState.Deleted or EntityState.Detached && HasConceptualNull) { _stateData.FlagAllProperties(entityType.PropertyCount(), PropertyFlag.Null, flagged: false); } - if (oldState == EntityState.Detached - || oldState == EntityState.Unchanged) + if (oldState is EntityState.Detached or EntityState.Unchanged) { - if (newState == EntityState.Added - || newState == EntityState.Deleted - || newState == EntityState.Modified) + if (newState is EntityState.Added or EntityState.Deleted or EntityState.Modified) { StateManager.ChangedCount++; } } - else if (newState == EntityState.Detached - || newState == EntityState.Unchanged) + else if (newState is EntityState.Detached or EntityState.Unchanged) { StateManager.ChangedCount--; } @@ -395,8 +390,7 @@ private void SetEntityState(EntityState oldState, EntityState newState, bool acc HandleSharedIdentityEntry(newState); - if ((newState == EntityState.Deleted - || newState == EntityState.Detached) + if (newState is EntityState.Deleted or EntityState.Detached && sharedIdentityEntry == null && StateManager.CascadeDeleteTiming == CascadeTiming.Immediate) { @@ -419,8 +413,7 @@ private void HandleSharedIdentityEntry(EntityState newState) break; case EntityState.Added: case EntityState.Modified: - if (sharedIdentityEntry.EntityState == EntityState.Added - || sharedIdentityEntry.EntityState == EntityState.Modified) + if (sharedIdentityEntry.EntityState is EntityState.Added or EntityState.Modified) { if (StateManager.SensitiveLoggingEnabled) { @@ -1333,9 +1326,7 @@ private void SetProperty( && valueType == CurrentValueType.Normal && (!asProperty.ClrType.IsNullableType() || asProperty.GetContainingForeignKeys().Any( - fk => fk.IsRequired - && (fk.DeleteBehavior == DeleteBehavior.Cascade - || fk.DeleteBehavior == DeleteBehavior.ClientCascade) + fk => fk is { IsRequired: true, DeleteBehavior: DeleteBehavior.Cascade or DeleteBehavior.ClientCascade } && fk.DeclaringEntityType.IsAssignableFrom(EntityType)))) { if (value == null) @@ -1616,9 +1607,7 @@ public void HandleConceptualNulls(bool sensitiveLoggingEnabled, bool force, bool } } - var cascadeFk = fks.FirstOrDefault( - fk => fk.DeleteBehavior == DeleteBehavior.Cascade - || fk.DeleteBehavior == DeleteBehavior.ClientCascade); + var cascadeFk = fks.FirstOrDefault(fk => fk.DeleteBehavior is DeleteBehavior.Cascade or DeleteBehavior.ClientCascade); if (cascadeFk != null && (force || (!isCascadeDelete diff --git a/src/EFCore/ChangeTracking/Internal/NavigationFixer.cs b/src/EFCore/ChangeTracking/Internal/NavigationFixer.cs index f8bfe00babc..afab8c6525c 100644 --- a/src/EFCore/ChangeTracking/Internal/NavigationFixer.cs +++ b/src/EFCore/ChangeTracking/Internal/NavigationFixer.cs @@ -505,9 +505,7 @@ var targetDependentEntry } if (newValue == null - && foreignKey.IsRequired - && (foreignKey.DeleteBehavior == DeleteBehavior.Cascade - || foreignKey.DeleteBehavior == DeleteBehavior.ClientCascade)) + && foreignKey is { IsRequired: true, DeleteBehavior: DeleteBehavior.Cascade or DeleteBehavior.ClientCascade }) { entry.HandleNullForeignKey(property); } @@ -610,8 +608,7 @@ public virtual void StateChanged( { InitialFixup(entry, null, fromQuery); } - else if ((oldState == EntityState.Deleted - || oldState == EntityState.Added) + else if (oldState is EntityState.Deleted or EntityState.Added && entry.EntityState == EntityState.Detached) { DeleteFixup(entry); @@ -993,8 +990,7 @@ private void InitialFixup( } private static bool IsAmbiguous(InternalEntityEntry dependentEntry) - => (dependentEntry.EntityState == EntityState.Detached - || dependentEntry.EntityState == EntityState.Deleted) + => dependentEntry.EntityState is EntityState.Detached or EntityState.Deleted && (dependentEntry.SharedIdentityEntry != null || dependentEntry.EntityType.HasSharedClrType && dependentEntry.StateManager.TryGetEntry(dependentEntry.Entity, throwOnNonUniqueness: false) != dependentEntry); @@ -1356,8 +1352,7 @@ private static void UndeleteDependent( InternalEntityEntry principalEntry) { if (dependentEntry.EntityState == EntityState.Deleted - && (principalEntry.EntityState == EntityState.Unchanged - || principalEntry.EntityState == EntityState.Modified)) + && principalEntry.EntityState is EntityState.Unchanged or EntityState.Modified) { dependentEntry.SetEntityState(EntityState.Modified); } diff --git a/src/EFCore/ChangeTracking/Internal/StateManager.cs b/src/EFCore/ChangeTracking/Internal/StateManager.cs index 2fbdcb43c89..c6cb87aab01 100644 --- a/src/EFCore/ChangeTracking/Internal/StateManager.cs +++ b/src/EFCore/ChangeTracking/Internal/StateManager.cs @@ -1223,8 +1223,7 @@ public virtual void CascadeDelete(InternalEntityEntry entry, bool force, IEnumer && (dependent.EntityState == EntityState.Added || KeysEqual(entry, fk, dependent))) { - if ((fk.DeleteBehavior == DeleteBehavior.Cascade - || fk.DeleteBehavior == DeleteBehavior.ClientCascade) + if (fk.DeleteBehavior is DeleteBehavior.Cascade or DeleteBehavior.ClientCascade && doCascadeDelete) { var cascadeState = principalIsDetached diff --git a/src/EFCore/ChangeTracking/LocalView.cs b/src/EFCore/ChangeTracking/LocalView.cs index 75011127780..6ab659f170a 100644 --- a/src/EFCore/ChangeTracking/LocalView.cs +++ b/src/EFCore/ChangeTracking/LocalView.cs @@ -104,7 +104,7 @@ public virtual ObservableCollection ToObservableCollection() private void LocalViewCollectionChanged(object? _, NotifyCollectionChangedEventArgs args) { Check.DebugAssert( - args.Action == NotifyCollectionChangedAction.Add || args.Action == NotifyCollectionChangedAction.Remove, + args.Action is NotifyCollectionChangedAction.Add or NotifyCollectionChangedAction.Remove, "action is not Add or Remove"); if (_triggeringLocalViewChange) @@ -150,8 +150,7 @@ private void ObservableCollectionChanged(object? _, NotifyCollectionChangedEvent } else { - if (args.Action == NotifyCollectionChangedAction.Remove - || args.Action == NotifyCollectionChangedAction.Replace) + if (args.Action is NotifyCollectionChangedAction.Remove or NotifyCollectionChangedAction.Replace) { foreach (TEntity entity in args.OldItems!) { @@ -159,8 +158,7 @@ private void ObservableCollectionChanged(object? _, NotifyCollectionChangedEvent } } - if (args.Action == NotifyCollectionChangedAction.Add - || args.Action == NotifyCollectionChangedAction.Replace) + if (args.Action is NotifyCollectionChangedAction.Add or NotifyCollectionChangedAction.Replace) { foreach (TEntity entity in args.NewItems!) { @@ -213,8 +211,7 @@ public virtual void Add(TEntity item) // was wanted in this case. var entry = _context.GetDependencies().StateManager.GetOrCreateEntry(item, _entityType); - if (entry.EntityState == EntityState.Deleted - || entry.EntityState == EntityState.Detached) + if (entry.EntityState is EntityState.Deleted or EntityState.Detached) { try { diff --git a/src/EFCore/Extensions/Internal/ExpressionExtensions.cs b/src/EFCore/Extensions/Internal/ExpressionExtensions.cs index e21a30e6884..f90969772e0 100644 --- a/src/EFCore/Extensions/Internal/ExpressionExtensions.cs +++ b/src/EFCore/Extensions/Internal/ExpressionExtensions.cs @@ -171,8 +171,7 @@ var memberInfos /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public static bool IsLogicalOperation(this Expression expression) - => expression.NodeType == ExpressionType.AndAlso - || expression.NodeType == ExpressionType.OrElse; + => expression.NodeType is ExpressionType.AndAlso or ExpressionType.OrElse; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -200,16 +199,9 @@ public static bool IsLogicalNot(this UnaryExpression sqlUnaryExpression) [return: NotNullIfNotNull("expression")] private static Expression? RemoveConvert(Expression? expression) - { - if (expression is UnaryExpression unaryExpression - && (expression.NodeType == ExpressionType.Convert - || expression.NodeType == ExpressionType.ConvertChecked)) - { - return RemoveConvert(unaryExpression.Operand); - } - - return expression; - } + => expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression + ? RemoveConvert(unaryExpression.Operand) + : expression; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to diff --git a/src/EFCore/Metadata/Internal/EntityType.cs b/src/EFCore/Metadata/Internal/EntityType.cs index 2bcaf6f5025..dc249917a9c 100644 --- a/src/EFCore/Metadata/Internal/EntityType.cs +++ b/src/EFCore/Metadata/Internal/EntityType.cs @@ -3322,8 +3322,8 @@ public virtual ChangeTrackingStrategy GetChangeTrackingStrategy() return CoreStrings.ChangeTrackingInterfaceMissing(entityType.DisplayName(), value, nameof(INotifyPropertyChanged)); } - if ((value == ChangeTrackingStrategy.ChangingAndChangedNotifications - || value == ChangeTrackingStrategy.ChangingAndChangedNotificationsWithOriginalValues) + if (value is ChangeTrackingStrategy.ChangingAndChangedNotifications + or ChangeTrackingStrategy.ChangingAndChangedNotificationsWithOriginalValues && !typeof(INotifyPropertyChanging).IsAssignableFrom(entityType.ClrType)) { return CoreStrings.ChangeTrackingInterfaceMissing(entityType.DisplayName(), value, nameof(INotifyPropertyChanging)); diff --git a/src/EFCore/Metadata/Internal/EntityTypeExtensions.cs b/src/EFCore/Metadata/Internal/EntityTypeExtensions.cs index d6697ef782d..3eb5bef2b0f 100644 --- a/src/EFCore/Metadata/Internal/EntityTypeExtensions.cs +++ b/src/EFCore/Metadata/Internal/EntityTypeExtensions.cs @@ -178,8 +178,7 @@ public static bool UseEagerSnapshots(this IReadOnlyEntityType entityType) { var changeTrackingStrategy = entityType.GetChangeTrackingStrategy(); - return changeTrackingStrategy == ChangeTrackingStrategy.Snapshot - || changeTrackingStrategy == ChangeTrackingStrategy.ChangedNotifications; + return changeTrackingStrategy is ChangeTrackingStrategy.Snapshot or ChangeTrackingStrategy.ChangedNotifications; } /// diff --git a/src/EFCore/Metadata/Internal/PropertyAccessorsFactory.cs b/src/EFCore/Metadata/Internal/PropertyAccessorsFactory.cs index bc821a12371..8c3fa13636a 100644 --- a/src/EFCore/Metadata/Internal/PropertyAccessorsFactory.cs +++ b/src/EFCore/Metadata/Internal/PropertyAccessorsFactory.cs @@ -48,7 +48,6 @@ private static Func CreateCurrentValueGetter public static bool IsEntityType(this TypeConfigurationType configurationType) - => configurationType == TypeConfigurationType.EntityType - || configurationType == TypeConfigurationType.SharedTypeEntityType - || configurationType == TypeConfigurationType.OwnedEntityType; + => configurationType is TypeConfigurationType.EntityType + or TypeConfigurationType.SharedTypeEntityType + or TypeConfigurationType.OwnedEntityType; } diff --git a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs index 4b23425bb6a..285c4dd5bf1 100644 --- a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs +++ b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs @@ -514,17 +514,14 @@ public IncludeExpandingExpressionVisitor( : base(navigationExpandingExpressionVisitor, source, extensibilityHelper) { _logger = navigationExpandingExpressionVisitor._queryCompilationContext.Logger; - _queryStateManager = navigationExpandingExpressionVisitor._queryCompilationContext.QueryTrackingBehavior - == QueryTrackingBehavior.TrackAll - || navigationExpandingExpressionVisitor._queryCompilationContext.QueryTrackingBehavior - == QueryTrackingBehavior.NoTrackingWithIdentityResolution; + _queryStateManager = navigationExpandingExpressionVisitor._queryCompilationContext.QueryTrackingBehavior is + QueryTrackingBehavior.TrackAll or QueryTrackingBehavior.NoTrackingWithIdentityResolution; _ignoreAutoIncludes = navigationExpandingExpressionVisitor._queryCompilationContext.IgnoreAutoIncludes; } protected override Expression VisitBinary(BinaryExpression binaryExpression) { - if (binaryExpression.NodeType == ExpressionType.Equal - || binaryExpression.NodeType == ExpressionType.NotEqual) + if (binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual) { // This could be entity equality. We don't want to expand include nodes over them // as either they translate or throw. @@ -1225,8 +1222,7 @@ public RemoveRedundantNavigationComparisonExpressionVisitor(IDiagnosticsLogger (binaryExpression.NodeType == ExpressionType.Equal - || binaryExpression.NodeType == ExpressionType.NotEqual) + => binaryExpression.NodeType is ExpressionType.Equal or ExpressionType.NotEqual && TryRemoveNavigationComparison( binaryExpression.NodeType, binaryExpression.Left, binaryExpression.Right, out var result) ? result diff --git a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs index 5b70684e068..07a042ad3eb 100644 --- a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs @@ -1085,7 +1085,7 @@ private NavigationExpansionExpression ProcessInclude( } #pragma warning restore CS0618 // Type or member is obsolete - if (expression is ConstantExpression { Value: string navigationChain } includeConstant) + if (expression is ConstantExpression { Value: string navigationChain }) { var navigationPaths = navigationChain.Split(new[] { "." }, StringSplitOptions.None); var includeTreeNodes = new Queue(); diff --git a/src/EFCore/Query/Internal/NullCheckRemovingExpressionVisitor.cs b/src/EFCore/Query/Internal/NullCheckRemovingExpressionVisitor.cs index f8bd314174c..9be9eccf3cb 100644 --- a/src/EFCore/Query/Internal/NullCheckRemovingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/NullCheckRemovingExpressionVisitor.cs @@ -39,9 +39,7 @@ protected override Expression VisitConditional(ConditionalExpression conditional { var test = Visit(conditionalExpression.Test); - if (test is BinaryExpression binaryTest - && (binaryTest.NodeType == ExpressionType.Equal - || binaryTest.NodeType == ExpressionType.NotEqual)) + if (test is BinaryExpression { NodeType: ExpressionType.Equal or ExpressionType.NotEqual } binaryTest) { var isLeftNullConstant = IsNullConstant(binaryTest.Left); var isRightNullConstant = IsNullConstant(binaryTest.Right); @@ -60,14 +58,10 @@ protected override Expression VisitConditional(ConditionalExpression conditional ? conditionalExpression.IfFalse : conditionalExpression.IfTrue; - if (accessOperation is UnaryExpression outerUnary - && (outerUnary.NodeType == ExpressionType.Convert - || outerUnary.NodeType == ExpressionType.ConvertChecked) + if (accessOperation is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } outerUnary && accessOperation.Type.IsNullableType() && accessOperation.Type.UnwrapNullableType() == outerUnary.Operand.Type - && outerUnary.Operand is UnaryExpression innerUnary - && (innerUnary.NodeType == ExpressionType.Convert - || innerUnary.NodeType == ExpressionType.ConvertChecked)) + && outerUnary.Operand is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } innerUnary) { // If expression is of type Convert(Convert(a, type), type?) // then we convert it to Convert(a, type?) since a can be nullable after removing check @@ -157,8 +151,7 @@ protected override Expression VisitMember(MemberExpression memberExpression) protected override Expression VisitUnary(UnaryExpression unaryExpression) { var operand = Visit(unaryExpression.Operand); - if ((unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked) + if (unaryExpression.NodeType is ExpressionType.Convert or ExpressionType.ConvertChecked && _nullSafeAccesses.Contains(operand)) { _nullSafeAccesses.Add(unaryExpression); diff --git a/src/EFCore/Query/Internal/ParameterExtractingExpressionVisitor.cs b/src/EFCore/Query/Internal/ParameterExtractingExpressionVisitor.cs index 8a9fbe4eb7c..aedb1b2c2dc 100644 --- a/src/EFCore/Query/Internal/ParameterExtractingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/ParameterExtractingExpressionVisitor.cs @@ -115,7 +115,7 @@ public virtual Expression ExtractParameters(Expression expression, bool clearEva } private static bool PreserveInitializationConstant(Expression expression, bool generateParameter) - => !generateParameter && (expression is NewExpression || expression is MemberInitExpression); + => !generateParameter && expression is NewExpression or MemberInitExpression; private bool PreserveConvertNode(Expression expression) { diff --git a/src/EFCore/Query/Internal/QueryOptimizingExpressionVisitor.cs b/src/EFCore/Query/Internal/QueryOptimizingExpressionVisitor.cs index 48903d88446..4e7deb8ab01 100644 --- a/src/EFCore/Query/Internal/QueryOptimizingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/QueryOptimizingExpressionVisitor.cs @@ -259,12 +259,16 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp // In VB.NET, comparison operators between strings (equality, greater-than, less-than) yield // calls to a VB-specific CompareString method. Normalize that to string.Compare. - if (visited.Method.Name == "CompareString" - && (visited.Method.DeclaringType?.Name == "Operators" - || visited.Method.DeclaringType?.Name == "EmbeddedOperators") - && visited.Method.DeclaringType?.Namespace == "Microsoft.VisualBasic.CompilerServices" - && visited.Object == null - && visited.Arguments is [_, _, ConstantExpression textCompareConstantExpression]) + if (visited is + { + Method: + { + Name: "CompareString", + DeclaringType: { Name: "Operators" or "EmbeddedOperators", Namespace: "Microsoft.VisualBasic.CompilerServices" } + }, + Object: null, + Arguments: [_, _, ConstantExpression textCompareConstantExpression] + }) { return textCompareConstantExpression.Value is true ? Expression.Call( @@ -481,5 +485,5 @@ when unaryExpression.IsLogicalNot(): } private static bool IsNullConstant(Expression expression) - => expression is ConstantExpression { Value: null } constantExpression; + => expression is ConstantExpression { Value: null }; } diff --git a/src/EFCore/Query/Internal/QueryableMethodNormalizingExpressionVisitor.cs b/src/EFCore/Query/Internal/QueryableMethodNormalizingExpressionVisitor.cs index 4a663378654..7a7b99fa6b4 100644 --- a/src/EFCore/Query/Internal/QueryableMethodNormalizingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/QueryableMethodNormalizingExpressionVisitor.cs @@ -306,8 +306,7 @@ private Expression TryConvertEnumerableToQueryable(MethodCallExpression methodCa var enumerableMethod = methodCallExpression.Method; var enumerableParameters = enumerableMethod.GetParameters(); var genericTypeArguments = Array.Empty(); - if (enumerableMethod.Name == nameof(Enumerable.Min) - || enumerableMethod.Name == nameof(Enumerable.Max)) + if (enumerableMethod.Name is nameof(Enumerable.Min) or nameof(Enumerable.Max)) { genericTypeArguments = new Type[methodCallExpression.Arguments.Count]; diff --git a/src/EFCore/Query/ReplacingExpressionVisitor.cs b/src/EFCore/Query/ReplacingExpressionVisitor.cs index ef98fb944c4..4b42252b102 100644 --- a/src/EFCore/Query/ReplacingExpressionVisitor.cs +++ b/src/EFCore/Query/ReplacingExpressionVisitor.cs @@ -48,10 +48,7 @@ public ReplacingExpressionVisitor(IReadOnlyList originals, IReadOnly [return: NotNullIfNotNull("expression")] public override Expression? Visit(Expression? expression) { - if (expression == null - || expression is ShapedQueryExpression - || expression is EntityShaperExpression - || expression is GroupByShaperExpression) + if (expression is null or ShapedQueryExpression or EntityShaperExpression or GroupByShaperExpression) { return expression; } diff --git a/src/EFCore/Query/ShapedQueryCompilingExpressionVisitor.cs b/src/EFCore/Query/ShapedQueryCompilingExpressionVisitor.cs index a554a2be72d..0721a0a4c60 100644 --- a/src/EFCore/Query/ShapedQueryCompilingExpressionVisitor.cs +++ b/src/EFCore/Query/ShapedQueryCompilingExpressionVisitor.cs @@ -250,16 +250,13 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp } protected override Expression VisitExtension(Expression extensionExpression) - => extensionExpression is EntityShaperExpression - || extensionExpression is ProjectionBindingExpression - ? extensionExpression - : base.VisitExtension(extensionExpression); + => extensionExpression is EntityShaperExpression or ProjectionBindingExpression + ? extensionExpression + : base.VisitExtension(extensionExpression); private static Expression? RemoveConvert(Expression? expression) { - while (expression != null - && (expression.NodeType == ExpressionType.Convert - || expression.NodeType == ExpressionType.ConvertChecked)) + while (expression is { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked }) { expression = RemoveConvert(((UnaryExpression)expression).Operand); } @@ -309,8 +306,8 @@ public EntityMaterializerInjectingExpressionVisitor( { _entityMaterializerSource = entityMaterializerSource; _queryTrackingBehavior = queryTrackingBehavior; - _queryStateManager = queryTrackingBehavior == QueryTrackingBehavior.TrackAll - || queryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution; + _queryStateManager = + queryTrackingBehavior is QueryTrackingBehavior.TrackAll or QueryTrackingBehavior.NoTrackingWithIdentityResolution; } public Expression Inject(Expression expression) diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs b/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs index 0dee589f365..7ea911ecb93 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs @@ -544,8 +544,6 @@ private void DisposePreparedStatements(bool disposing = true) } private static bool IsBusy(int rc) - => rc == SQLITE_LOCKED - || rc == SQLITE_BUSY - || rc == SQLITE_LOCKED_SHAREDCACHE; + => rc is SQLITE_LOCKED or SQLITE_BUSY or SQLITE_LOCKED_SHAREDCACHE; } } diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionInternal.cs b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionInternal.cs index 0a0a72602c7..3fd58ba6599 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionInternal.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionInternal.cs @@ -233,8 +233,6 @@ private void RetryWhileBusy(Func action, Action reset, int timeout, Stopwat } private static bool IsBusy(int rc) - => rc == SQLITE_LOCKED - || rc == SQLITE_BUSY - || rc == SQLITE_LOCKED_SHAREDCACHE; + => rc is SQLITE_LOCKED or SQLITE_BUSY or SQLITE_LOCKED_SHAREDCACHE; } } diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs index af98601bdf9..ade9c15e176 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs @@ -311,15 +311,9 @@ private static TEnum ConvertToEnum(object value) } private static bool? ConvertToNullableBoolean(object value) - { - if (value == null - || value is string { Length: 0 }) - { - return null; - } - - return Convert.ToBoolean(value, CultureInfo.InvariantCulture); - } + => value is null or string { Length: 0 } + ? null + : Convert.ToBoolean(value, CultureInfo.InvariantCulture); /// /// Clears the contents of the builder. diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteDataReader.cs b/src/Microsoft.Data.Sqlite.Core/SqliteDataReader.cs index 6220966d84f..f18627a43e7 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteDataReader.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteDataReader.cs @@ -216,9 +216,7 @@ public override bool NextResult() } private static bool IsBusy(int rc) - => rc == SQLITE_LOCKED - || rc == SQLITE_BUSY - || rc == SQLITE_LOCKED_SHAREDCACHE; + => rc is SQLITE_LOCKED or SQLITE_BUSY or SQLITE_LOCKED_SHAREDCACHE; /// /// Closes the data reader. diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteDataRecord.cs b/src/Microsoft.Data.Sqlite.Core/SqliteDataRecord.cs index 08a0d5bf55e..450e08f1286 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteDataRecord.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteDataRecord.cs @@ -185,9 +185,7 @@ public virtual string GetDataTypeName(int ordinal) return "TEXT"; default: - Debug.Assert( - sqliteType == SQLITE_BLOB || sqliteType == SQLITE_NULL, - "Unexpected column type: " + sqliteType); + Debug.Assert(sqliteType is SQLITE_BLOB or SQLITE_NULL, "Unexpected column type: " + sqliteType); return "BLOB"; } } @@ -228,9 +226,7 @@ internal static Type GetFieldTypeFromSqliteType(int sqliteType) return typeof(string); default: - Debug.Assert( - sqliteType == SQLITE_BLOB || sqliteType == SQLITE_NULL, - "Unexpected column type: " + sqliteType); + Debug.Assert(sqliteType is SQLITE_BLOB or SQLITE_NULL, "Unexpected column type: " + sqliteType); return typeof(byte[]); } } @@ -252,7 +248,7 @@ public static Type GetFieldType(string type) return typeof(string); default: - Debug.Assert(type == "blob" || type == null, "Unexpected column type: " + type); + Debug.Assert(type is "blob" or null, "Unexpected column type: " + type); return typeof(byte[]); } } diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteException.cs b/src/Microsoft.Data.Sqlite.Core/SqliteException.cs index 4f0e8fbf000..953f3140427 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteException.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteException.cs @@ -61,9 +61,7 @@ public SqliteException(string? message, int errorCode, int extendedErrorCode) /// public static void ThrowExceptionForRC(int rc, sqlite3? db) { - if (rc == SQLITE_OK - || rc == SQLITE_ROW - || rc == SQLITE_DONE) + if (rc is SQLITE_OK or SQLITE_ROW or SQLITE_DONE) { return; } diff --git a/src/Shared/ExpressionExtensions.cs b/src/Shared/ExpressionExtensions.cs index 0aa2ad03def..0835bd7ad95 100644 --- a/src/Shared/ExpressionExtensions.cs +++ b/src/Shared/ExpressionExtensions.cs @@ -40,16 +40,9 @@ public static LambdaExpression UnwrapLambdaFromQuote(this Expression expression) } private static Expression RemoveConvert(Expression expression) - { - if (expression is UnaryExpression unaryExpression - && (expression.NodeType == ExpressionType.Convert - || expression.NodeType == ExpressionType.ConvertChecked)) - { - return RemoveConvert(unaryExpression.Operand); - } - - return expression; - } + => expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression + ? RemoveConvert(unaryExpression.Operand) + : expression; public static T GetConstantValue(this Expression expression) => expression is ConstantExpression constantExpression diff --git a/src/dotnet-ef/Program.cs b/src/dotnet-ef/Program.cs index 53ddad78240..0ad0cbb64e4 100644 --- a/src/dotnet-ef/Program.cs +++ b/src/dotnet-ef/Program.cs @@ -19,8 +19,7 @@ private static int Main(string[] args) } catch (Exception ex) { - if (ex is CommandException - || ex is CommandParsingException) + if (ex is CommandException or CommandParsingException) { Reporter.WriteVerbose(ex.ToString()); } diff --git a/src/ef/CommandLineUtils/CommandLineApplication.cs b/src/ef/CommandLineUtils/CommandLineApplication.cs index 026a66b2a7d..3fadcac5bd6 100644 --- a/src/ef/CommandLineUtils/CommandLineApplication.cs +++ b/src/ef/CommandLineUtils/CommandLineApplication.cs @@ -245,8 +245,7 @@ private static ParseOptionResult ParseOption( } else { - if (option.OptionType == CommandOptionType.NoValue - || option.OptionType == CommandOptionType.BoolValue) + if (option.OptionType is CommandOptionType.NoValue or CommandOptionType.BoolValue) { // No value is needed for this option option.TryParse(null); diff --git a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CustomPartitionKeyIdGenerator.cs b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CustomPartitionKeyIdGenerator.cs index 530cb38419c..975513e01bb 100644 --- a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CustomPartitionKeyIdGenerator.cs +++ b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CustomPartitionKeyIdGenerator.cs @@ -44,13 +44,10 @@ protected override object NextValue(EntityEntry entry) value = converter.ConvertToProvider(value); } - if (value is int x) + // We don't allow the Id to be zero for our custom generator. + if (value is 0) { - // We don't allow the Id to be zero for our custom generator. - if (x == 0) - { - return default; - } + return default; } AppendString(builder, value); diff --git a/test/EFCore.Design.Tests/Migrations/Design/SnapshotModelProcessorTest.cs b/test/EFCore.Design.Tests/Migrations/Design/SnapshotModelProcessorTest.cs index 1932ffc4ce8..097d3d461e0 100644 --- a/test/EFCore.Design.Tests/Migrations/Design/SnapshotModelProcessorTest.cs +++ b/test/EFCore.Design.Tests/Migrations/Design/SnapshotModelProcessorTest.cs @@ -90,7 +90,7 @@ public void Warns_for_conflicting_annotations() Assert.Equal(2, model.GetAnnotations().Count()); var actual = (string)model["Relational:DefaultSchema"]; - Assert.True(actual == "Value1" || actual == "Value2"); + Assert.True(actual is "Value1" or "Value2"); } [ConditionalFact] @@ -113,7 +113,7 @@ public void Warns_for_conflicting_annotations_one_relational() Assert.Equal(2, model.GetAnnotations().Count()); var actual = (string)model["Relational:DefaultSchema"]; - Assert.True(actual == "Value1" || actual == "Value2"); + Assert.True(actual is "Value1" or "Value2"); } [ConditionalFact] diff --git a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs index 0cdf792d0fc..cac161b3732 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NullSemanticsQueryTestBase.cs @@ -678,7 +678,7 @@ public virtual void Where_contains_on_parameter_array_with_relational_null_seman .Where(e => names.Contains(e.NullableStringA)) .Select(e => e.NullableStringA).ToList(); - Assert.True(result.All(r => r == "Foo" || r == "Bar")); + Assert.True(result.All(r => r is "Foo" or "Bar")); } [ConditionalFact] @@ -1825,7 +1825,7 @@ public virtual async Task Multiple_equality_comparisons_including_null_compariso { var ctx = CreateContext(useRelationalNulls: true); - var expected = ctx.Entities1.AsEnumerable().Where(e => e.NullableIntA == 1 || e.NullableIntA == null).ToList(); + var expected = ctx.Entities1.AsEnumerable().Where(e => e.NullableIntA is 1 or null).ToList(); ClearLog(); var query = ctx.Entities1.Where(e => e.NullableIntA == 1 || e.NullableIntA == null); diff --git a/test/EFCore.Relational.Tests/TestUtilities/TestRelationalTypeMappingSource.cs b/test/EFCore.Relational.Tests/TestUtilities/TestRelationalTypeMappingSource.cs index e094bd10b17..434f491c029 100644 --- a/test/EFCore.Relational.Tests/TestUtilities/TestRelationalTypeMappingSource.cs +++ b/test/EFCore.Relational.Tests/TestUtilities/TestRelationalTypeMappingSource.cs @@ -203,7 +203,7 @@ protected override RelationalTypeMapping FindMapping(in RelationalTypeMappingInf return _defaultDecimalMapping; } - if (scale == null || scale == 0) + if (scale is null or 0) { return new DecimalTypeMapping( "decimal_mapping(" + precision + ")", diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs index 913769005a3..f0d0d6c124a 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs @@ -1491,8 +1491,7 @@ public virtual void Optional_many_to_one_dependents_are_orphaned( context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Modified : EntityState.Unchanged; @@ -1911,8 +1910,7 @@ public virtual void Required_many_to_one_dependents_are_cascade_deleted_starting context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Deleted : EntityState.Unchanged; @@ -2008,8 +2006,7 @@ public virtual void Optional_many_to_one_dependents_are_orphaned_starting_detach context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Modified : EntityState.Unchanged; @@ -2125,8 +2122,7 @@ public virtual void Required_many_to_one_dependents_are_cascade_detached_when_Ad context.ChangeTracker.CascadeChanges(); } - if ((cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + if (cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction) { Assert.Equal(EntityState.Detached, context.Entry(added).State); diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToManyAk.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToManyAk.cs index 44557f3ac72..9d6c130a0d4 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToManyAk.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToManyAk.cs @@ -1092,8 +1092,7 @@ public virtual void Optional_many_to_one_dependents_with_alternate_key_are_orpha context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Modified : EntityState.Unchanged; @@ -1191,8 +1190,7 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Deleted : EntityState.Unchanged; @@ -1311,8 +1309,7 @@ public virtual void Required_many_to_one_dependents_with_alternate_key_are_casca context.ChangeTracker.CascadeChanges(); } - if ((cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + if (cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction) { Assert.Equal(EntityState.Detached, context.Entry(added).State); diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOne.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOne.cs index 75d85ca5701..12c2555559b 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOne.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOne.cs @@ -727,8 +727,7 @@ public virtual void Optional_one_to_one_are_orphaned_starting_detached( context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Modified : EntityState.Unchanged; @@ -2102,8 +2101,7 @@ public virtual void Required_one_to_one_are_cascade_deleted_starting_detached( context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Deleted : EntityState.Unchanged; @@ -2198,8 +2196,7 @@ public virtual void Required_non_PK_one_to_one_are_cascade_deleted_starting_deta context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Deleted : EntityState.Unchanged; @@ -2299,8 +2296,7 @@ public virtual void Required_one_to_one_are_cascade_detached_when_Added( context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Detached : EntityState.Added; @@ -2409,8 +2405,7 @@ public virtual void Required_non_PK_one_to_one_are_cascade_detached_when_Added( context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Detached : EntityState.Added; diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOneAk.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOneAk.cs index e7fcfd1f0cd..1eb8ec2c82c 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOneAk.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToOneAk.cs @@ -902,8 +902,7 @@ public virtual void Optional_one_to_one_with_alternate_key_are_orphaned_starting context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Modified : EntityState.Unchanged; @@ -2325,8 +2324,7 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_deleted_s context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Deleted : EntityState.Unchanged; @@ -2430,8 +2428,7 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Deleted : EntityState.Unchanged; @@ -2541,8 +2538,7 @@ public virtual void Required_one_to_one_with_alternate_key_are_cascade_detached_ context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Detached : EntityState.Added; @@ -2659,8 +2655,7 @@ public virtual void Required_non_PK_one_to_one_with_alternate_key_are_cascade_de context.ChangeTracker.CascadeChanges(); } - var expectedState = (cascadeDeleteTiming == CascadeTiming.Immediate - || cascadeDeleteTiming == null) + var expectedState = cascadeDeleteTiming is CascadeTiming.Immediate or null && !Fixture.ForceClientNoAction ? EntityState.Detached : EntityState.Added; diff --git a/test/EFCore.Specification.Tests/ManyToManyFieldsLoadTestBase.cs b/test/EFCore.Specification.Tests/ManyToManyFieldsLoadTestBase.cs index 63a9d084ab2..79167e2964e 100644 --- a/test/EFCore.Specification.Tests/ManyToManyFieldsLoadTestBase.cs +++ b/test/EFCore.Specification.Tests/ManyToManyFieldsLoadTestBase.cs @@ -836,7 +836,7 @@ public virtual async Task Load_collection_using_Query_with_filtered_Include(bool Assert.Contains(left, right.OneSkipShared); foreach (var three in right.ThreeSkipFull) { - Assert.True(three.Id == 11 || three.Id == 13); + Assert.True(three.Id is 11 or 13); Assert.Contains(right, three.TwoSkipFull); } } diff --git a/test/EFCore.Specification.Tests/ManyToManyLoadTestBase.cs b/test/EFCore.Specification.Tests/ManyToManyLoadTestBase.cs index 1e8ee4941ba..95d61643ade 100644 --- a/test/EFCore.Specification.Tests/ManyToManyLoadTestBase.cs +++ b/test/EFCore.Specification.Tests/ManyToManyLoadTestBase.cs @@ -1312,7 +1312,7 @@ public virtual async Task Load_collection_using_Query_with_filtered_Include(bool Assert.Contains(left, right.OneSkipShared); foreach (var three in right.ThreeSkipFull) { - Assert.True(three.Id == 11 || three.Id == 13); + Assert.True(three.Id is 11 or 13); Assert.Contains(right, three.TwoSkipFull); } } diff --git a/test/EFCore.Specification.Tests/Query/GearsOfWarQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/GearsOfWarQueryTestBase.cs index 4ad1d8ac4c0..fdf5ffe2d6a 100644 --- a/test/EFCore.Specification.Tests/Query/GearsOfWarQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/GearsOfWarQueryTestBase.cs @@ -2614,7 +2614,7 @@ private static Weapon FavoriteWeapon(IEnumerable weapons) => weapons.OrderBy(w => w.Id).FirstOrDefault(); private static IEnumerable Veterans(IEnumerable gears) - => gears.Where(g => g.Nickname == "Marcus" || g.Nickname == "Dom" || g.Nickname == "Cole Train" || g.Nickname == "Baird"); + => gears.Where(g => g.Nickname is "Marcus" or "Dom" or "Cole Train" or "Baird"); [ConditionalTheory] [MemberData(nameof(IsAsyncData))] diff --git a/test/EFCore.Specification.Tests/Query/NorthwindEFPropertyIncludeQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindEFPropertyIncludeQueryTestBase.cs index 35e2f09250e..5ea87896cc8 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindEFPropertyIncludeQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindEFPropertyIncludeQueryTestBase.cs @@ -204,26 +204,15 @@ Expression BuildEFPropertyCallExpression(int entityTypeIndex, int propertyTypeIn } private static string GetPath(Expression expression) - { - switch (expression) + => expression switch { - case MemberExpression memberExpression: - if (memberExpression.Expression is ParameterExpression) - { - return memberExpression.Member.Name; - } - - return $"{GetPath(memberExpression.Expression)}.{memberExpression.Member.Name}"; - - case UnaryExpression unaryExpression - when unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.TypeAs: - return GetPath(unaryExpression.Operand); - - default: - return null; - } - } + MemberExpression { Expression: ParameterExpression } memberExpression + => memberExpression.Member.Name, + MemberExpression memberExpression + => $"{GetPath(memberExpression.Expression)}.{memberExpression.Member.Name}", + UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.Convert or ExpressionType.TypeAs } unaryExpression + => GetPath(unaryExpression.Operand), + _ => null + }; } } diff --git a/test/EFCore.Specification.Tests/Query/NorthwindStringIncludeQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindStringIncludeQueryTestBase.cs index 7b9feb7babe..dddf56a7f65 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindStringIncludeQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindStringIncludeQueryTestBase.cs @@ -223,26 +223,15 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp } private static string GetPath(Expression expression) - { - switch (expression) + => expression switch { - case MemberExpression memberExpression: - if (memberExpression.Expression is ParameterExpression) - { - return memberExpression.Member.Name; - } - - return $"{GetPath(memberExpression.Expression)}.{memberExpression.Member.Name}"; - - case UnaryExpression unaryExpression - when unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.TypeAs: - return GetPath(unaryExpression.Operand); - - default: - throw new NotImplementedException("Unhandled expression tree in Include lambda"); - } - } + MemberExpression { Expression: ParameterExpression } memberExpression + => memberExpression.Member.Name, + MemberExpression memberExpression + => $"{GetPath(memberExpression.Expression)}.{memberExpression.Member.Name}", + UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.Convert or ExpressionType.TypeAs } unaryExpression + => GetPath(unaryExpression.Operand), + _ => throw new NotImplementedException("Unhandled expression tree in Include lambda") + }; } } diff --git a/test/EFCore.Specification.Tests/TestUtilities/ExpectedQueryRewritingVisitor.cs b/test/EFCore.Specification.Tests/TestUtilities/ExpectedQueryRewritingVisitor.cs index 0a331b71d95..8baebd92a27 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/ExpectedQueryRewritingVisitor.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/ExpectedQueryRewritingVisitor.cs @@ -246,7 +246,7 @@ private Expression TryConvertEFPropertyToMemberAccess(Expression expression) var methodInfo = _getShadowPropertyValueMethodInfo.MakeGenericMethod(caller.Type, methodCallExpression.Type); result = Expression.Call(methodInfo, caller, Expression.Constant(shadowPropertyMapping)); } - else if (caller.Type.GetMembers().Where(m => m.Name == propertyName).SingleOrDefault() is MemberInfo matchingMember) + else if (caller.Type.GetMembers().SingleOrDefault(m => m.Name == propertyName) is MemberInfo) { result = Expression.Property(caller, propertyName); } @@ -268,9 +268,7 @@ private Expression TryConvertEFPropertyToMemberAccess(Expression expression) return expression; static Expression RemoveConvertToObject(Expression expression) - => expression is UnaryExpression unaryExpression - && (expression.NodeType == ExpressionType.Convert - || expression.NodeType == ExpressionType.ConvertChecked) + => expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unaryExpression && expression.Type == typeof(object) ? RemoveConvertToObject(unaryExpression.Operand) : expression; @@ -307,12 +305,16 @@ private Expression AddNullProtectionForNonNullableMemberAccess(Expression expres protected override Expression VisitUnary(UnaryExpression unaryExpression) { - if ((unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked - || unaryExpression.NodeType == ExpressionType.TypeAs) - && unaryExpression.Operand is MemberExpression { Type.IsValueType: true } memberOperand + if (unaryExpression is + { + NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked or ExpressionType.TypeAs, + Operand: MemberExpression + { + Type.IsValueType: true, + Expression: not null + } memberOperand + } && !memberOperand.Type.IsNullableValueType() - && memberOperand.Expression != null && unaryExpression.Type.IsNullableValueType() && unaryExpression.Type.UnwrapNullableType() == memberOperand.Type) { @@ -341,12 +343,12 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) protected override Expression VisitBinary(BinaryExpression binaryExpression) { - if (binaryExpression.NodeType == ExpressionType.Equal - || binaryExpression.NodeType == ExpressionType.NotEqual - || binaryExpression.NodeType == ExpressionType.GreaterThan - || binaryExpression.NodeType == ExpressionType.GreaterThanOrEqual - || binaryExpression.NodeType == ExpressionType.LessThan - || binaryExpression.NodeType == ExpressionType.LessThanOrEqual) + if (binaryExpression.NodeType is ExpressionType.Equal + or ExpressionType.NotEqual + or ExpressionType.GreaterThan + or ExpressionType.GreaterThanOrEqual + or ExpressionType.LessThan + or ExpressionType.LessThanOrEqual) { var left = AddNullProtectionForNonNullableMemberAccess(binaryExpression.Left); var right = AddNullProtectionForNonNullableMemberAccess(binaryExpression.Right); diff --git a/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectJoinWithSelfExpressionMutator.cs b/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectJoinWithSelfExpressionMutator.cs index b4118cd3787..3a5a23e2a09 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectJoinWithSelfExpressionMutator.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectJoinWithSelfExpressionMutator.cs @@ -60,9 +60,9 @@ public ExpressionFinder(InjectJoinWithSelfExpressionMutator mutator) protected override Expression VisitMethodCall(MethodCallExpression node) { - if (node?.Method.Name == nameof(Queryable.ThenBy) - || node?.Method.Name == nameof(Queryable.ThenByDescending) - || node?.Method.Name == nameof(EntityFrameworkQueryableExtensions.ThenInclude)) + if (node?.Method.Name is nameof(Queryable.ThenBy) + or nameof(Queryable.ThenByDescending) + or nameof(EntityFrameworkQueryableExtensions.ThenInclude)) { return node; } diff --git a/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectOrderByPropertyExpressionMutator.cs b/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectOrderByPropertyExpressionMutator.cs index f7c458c69cd..86a32cba154 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectOrderByPropertyExpressionMutator.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectOrderByPropertyExpressionMutator.cs @@ -82,10 +82,7 @@ public override Expression Visit(Expression expression) { // can't inject OrderBy inside of include - would have to rewrite the ThenInclude method to one that accepts ordered input var insideThenInclude = default(bool?); - if (expression is MethodCallExpression methodCallExpression - && (methodCallExpression.Method.Name == "ThenInclude" - || methodCallExpression.Method.Name == "ThenBy" - || methodCallExpression.Method.Name == "ThenByDescending")) + if (expression is MethodCallExpression { Method.Name: "ThenInclude" or "ThenBy" or "ThenByDescending" }) { insideThenInclude = _insideThenInclude; _insideThenInclude = true; diff --git a/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectThenByPropertyExpressionMutator.cs b/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectThenByPropertyExpressionMutator.cs index 4cfa17fc7eb..64c79647a47 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectThenByPropertyExpressionMutator.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectThenByPropertyExpressionMutator.cs @@ -82,8 +82,7 @@ public override Expression Visit(Expression expression) { // can't inject OrderBy inside of include - would have to rewrite the ThenInclude method to one that accepts ordered input var insideThenInclude = default(bool?); - if (expression is MethodCallExpression methodCallExpression - && (methodCallExpression.Method.Name == "ThenInclude" || methodCallExpression.Method.Name == "ThenIncludeDescending")) + if (expression is MethodCallExpression { Method.Name: "ThenInclude" or "ThenIncludeDescending" }) { insideThenInclude = _insideThenInclude; _insideThenInclude = true; diff --git a/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectWhereExpressionMutator.cs b/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectWhereExpressionMutator.cs index 67038e3f858..e707a10ffdd 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectWhereExpressionMutator.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectWhereExpressionMutator.cs @@ -85,8 +85,6 @@ public override Expression Apply(Expression expression, Random random) any, Expression.Property(prm, collectionNavigation.PropertyInfo))); } - - var navigation = random.Choose(navigations); } var lambdaBody = random.Choose(candidateExpressions); @@ -117,12 +115,7 @@ public ExpressionFinder(InjectWhereExpressionMutator mutator) public override Expression Visit(Expression expression) { - if (expression is MethodCallExpression methodCallExpression - && (methodCallExpression.Method.Name == "ThenInclude" - || methodCallExpression.Method.Name == "ThenBy" - || methodCallExpression.Method.Name == "ThenByDescending" - || methodCallExpression.Method.Name == "Skip" - || methodCallExpression.Method.Name == "Take")) + if (expression is MethodCallExpression { Method.Name: "ThenInclude" or "ThenBy" or "ThenByDescending" or "Skip" or "Take" }) { return expression; } diff --git a/test/EFCore.Specification.Tests/UnidirectionalManyToManyLoadTestBase.cs b/test/EFCore.Specification.Tests/UnidirectionalManyToManyLoadTestBase.cs index c71decb216a..2a14ec25c16 100644 --- a/test/EFCore.Specification.Tests/UnidirectionalManyToManyLoadTestBase.cs +++ b/test/EFCore.Specification.Tests/UnidirectionalManyToManyLoadTestBase.cs @@ -886,7 +886,7 @@ public virtual async Task Load_collection_using_Query_with_filtered_Include_unid Assert.Contains(left, context.Entry(right).Collection("UnidirectionalEntityOne").CurrentValue!.Cast()); foreach (var three in context.Entry(right).Collection("UnidirectionalEntityThree").CurrentValue!) { - Assert.True(three.Id == 11 || three.Id == 13); + Assert.True(three.Id is 11 or 13); Assert.Contains(right, three.TwoSkipFull); } } diff --git a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/TestEnvironment.cs b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/TestEnvironment.cs index 206b9170cc7..0179757e7d4 100644 --- a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/TestEnvironment.cs +++ b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/TestEnvironment.cs @@ -67,7 +67,7 @@ public static bool IsSqlAzure { _engineEdition = GetEngineEdition(); - _isAzureSqlDb = (_engineEdition == 5 || _engineEdition == 8); + _isAzureSqlDb = _engineEdition is 5 or 8; } catch (PlatformNotSupportedException) { diff --git a/test/EFCore.Tests/ChangeTracking/ChangeTrackerTest.cs b/test/EFCore.Tests/ChangeTracking/ChangeTrackerTest.cs index d9fdc658187..1436c53ce10 100644 --- a/test/EFCore.Tests/ChangeTracking/ChangeTrackerTest.cs +++ b/test/EFCore.Tests/ChangeTracking/ChangeTrackerTest.cs @@ -2879,8 +2879,7 @@ public void Optional_relationship_with_cascade_can_be_forced_to_delete_orphans( Assert.Equal(EntityState.Unchanged, context.Entry(attachedContainer).State); Assert.Equal(EntityState.Unchanged, context.Entry(attachedTroduct!).State); - if (orphanTiming == null - || orphanTiming == CascadeTiming.Immediate) + if (orphanTiming is null or CascadeTiming.Immediate) { Assert.Equal(EntityState.Deleted, context.Entry(attachedRoom).State); } diff --git a/test/EFCore.Tests/ChangeTracking/Internal/FixupTest.cs b/test/EFCore.Tests/ChangeTracking/Internal/FixupTest.cs index bd4a2efa67c..eeb03f1ca2d 100644 --- a/test/EFCore.Tests/ChangeTracking/Internal/FixupTest.cs +++ b/test/EFCore.Tests/ChangeTracking/Internal/FixupTest.cs @@ -3323,8 +3323,7 @@ protected virtual void AssertAllFixedUp(DbContext context) foreach (var entry in context.ChangeTracker.Entries()) { var product = entry.Entity; - if (product.CategoryId == 11 - || product.CategoryId == 12) + if (product.CategoryId is 11 or 12) { Assert.Equal(product.CategoryId, product.Category.Id); Assert.Contains(product, product.Category.Products); @@ -3338,8 +3337,7 @@ protected virtual void AssertAllFixedUp(DbContext context) foreach (var entry in context.ChangeTracker.Entries()) { var offer = entry.Entity; - if (offer.ProductId == 22 - || offer.ProductId == 24) + if (offer.ProductId is 22 or 24) { Assert.Equal(offer.ProductId, offer.Product.Id); Assert.Contains(offer, offer.Product.SpecialOffers); diff --git a/test/EFCore.Tests/ChangeTracking/Internal/InternalClrEntityEntryTest.cs b/test/EFCore.Tests/ChangeTracking/Internal/InternalClrEntityEntryTest.cs index ac4dbde2fda..08ea6fd818d 100644 --- a/test/EFCore.Tests/ChangeTracking/Internal/InternalClrEntityEntryTest.cs +++ b/test/EFCore.Tests/ChangeTracking/Internal/InternalClrEntityEntryTest.cs @@ -125,7 +125,7 @@ public void AcceptChanges_handles_different_entity_states_for_owned_types(Entity entry.AcceptChanges(); Assert.Equal( - entityState == EntityState.Deleted || entityState == EntityState.Detached + entityState is EntityState.Deleted or EntityState.Detached ? EntityState.Detached : EntityState.Unchanged, entry.EntityState); @@ -138,7 +138,7 @@ public void AcceptChanges_handles_different_entity_states_for_owned_types(Entity { Assert.Equal("Pickle", entry[valueProperty]); Assert.Equal( - entityState == EntityState.Detached || entityState == EntityState.Deleted ? "Cheese" : "Pickle", + entityState is EntityState.Detached or EntityState.Deleted ? "Cheese" : "Pickle", entry.GetOriginalValue(valueProperty)); } }