From 6da90b8f219bf4b013918e3e430e0d8eb783e4a4 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 14 Jun 2023 00:32:20 +0200 Subject: [PATCH] Code cleanup & modernization --- .../InternalUsageDiagnosticAnalyzer.cs | 10 +- .../Internal/CosmosLoggerExtensions.cs | 4 +- ...osmosManyToManyJoinEntityTypeConvention.cs | 6 +- .../CosmosValueGenerationConvention.cs | 3 +- .../Internal/CosmosPropertyExtensions.cs | 3 +- ...osmosProjectionBindingExpressionVisitor.cs | 6 +- ...yableMethodTranslatingExpressionVisitor.cs | 10 +- ...ionBindingRemovingExpressionVisitorBase.cs | 10 +- ...ssionVisitor.ReadItemQueryingEnumerable.cs | 2 +- .../CosmosSqlTranslatingExpressionVisitor.cs | 15 +- .../Internal/CosmosStringMethodTranslator.cs | 9 +- .../Query/Internal/ExpressionExtensions.cs | 3 +- .../Query/Internal/SelectExpression.cs | 4 +- .../Query/Internal/SqlConstantExpression.cs | 4 +- .../Query/Internal/SqlExpressionFactory.cs | 1 - .../Storage/Internal/CosmosClientWrapper.cs | 3 +- .../Internal/CosmosTypeMappingSource.cs | 3 +- .../Design/Internal/CSharpHelper.cs | 5 +- .../Design/Internal/DbContextOperations.cs | 2 +- .../Extensions/ScaffoldingModelExtensions.cs | 3 +- .../Design/CSharpSnapshotGenerator.cs | 2 +- .../Internal/SnapshotModelProcessor.cs | 4 +- .../Internal/CSharpEntityTypeGenerator.tt | 4 +- .../Scaffolding/Internal/CSharpUtilities.cs | 3 +- .../RelationalScaffoldingModelFactory.cs | 4 +- ...yExpressionTranslatingExpressionVisitor.cs | 43 +-- ...emoryProjectionBindingExpressionVisitor.cs | 8 +- .../Query/Internal/InMemoryQueryExpression.cs | 8 +- .../InMemoryQueryTranslationPreprocessor.cs | 4 +- ...yableMethodTranslatingExpressionVisitor.cs | 7 +- ...erExpressionProcessingExpressionVisitor.cs | 11 +- .../Internal/LazyLoadingInterceptor.cs | 4 +- .../Internal/PropertyChangedInterceptor.cs | 1 - .../Internal/PropertyChangingInterceptor.cs | 1 - .../Internal/ProxiesOptionsExtension.cs | 2 +- .../Proxies/Internal/ProxyBindingRewriter.cs | 3 +- .../Design/AnnotationCodeGenerator.cs | 3 +- .../RelationalPropertyInternalExtensions.cs | 3 +- .../RelationalEntityTypeExtensions.cs | 3 +- .../RelationalPropertyExtensions.cs | 3 +- .../RelationalOptionsExtension.cs | 3 +- .../RelationalMapToJsonConvention.cs | 2 - .../Internal/InternalDbFunctionBuilder.cs | 2 +- .../Metadata/Internal/JsonColumnBase.cs | 1 - .../Metadata/Internal/RelationalModel.cs | 1 - .../StoreStoredProcedureResultColumn.cs | 2 - .../StoreStoredProcedureReturnValue.cs | 2 - .../Query/EntityProjectionExpression.cs | 3 +- .../Query/EnumerableExpression.cs | 4 +- .../Query/IAggregateMethodCallTranslator.cs | 2 +- .../Query/Internal/CollateTranslator.cs | 3 +- .../Query/Internal/ContainsTranslator.cs | 3 +- ...mSqlParameterExpandingExpressionVisitor.cs | 1 - .../GroupBySingleQueryingEnumerable.cs | 2 +- ...ionalProjectionBindingExpressionVisitor.cs | 6 +- ...sionProjectionApplyingExpressionVisitor.cs | 5 +- ...lExpressionSimplifyingExpressionVisitor.cs | 1 - .../Query/JsonQueryExpression.cs | 2 +- .../Query/QuerySqlGenerator.cs | 27 +- ...alAggregateMethodCallTranslatorProvider.cs | 5 +- .../Query/RelationalEntityShaperExpression.cs | 4 +- .../RelationalGroupByResultExpression.cs | 6 +- .../RelationalParameterBasedSqlProcessor.cs | 6 +- ...lParameterBasedSqlProcessorDependencies.cs | 2 +- ...yableMethodTranslatingExpressionVisitor.cs | 43 +-- ...ranslatingExpressionVisitorDependencies.cs | 2 +- ...ocessingExpressionVisitor.ClientMethods.cs | 6 +- ...sitor.ShaperProcessingExpressionVisitor.cs | 31 +- ...lationalSqlTranslatingExpressionVisitor.cs | 24 +- ...ranslatingExpressionVisitorDependencies.cs | 2 +- .../Query/SqlExpressionFactory.cs | 20 +- .../SqlExpressions/RowValueExpression.cs | 3 - .../SqlExpressions/SelectExpression.Helper.cs | 35 +- .../Query/SqlExpressions/SelectExpression.cs | 183 +++++----- .../Query/SqlNullabilityProcessor.cs | 30 +- .../Storage/DbContextTransactionExtensions.cs | 2 +- .../DbParameterCollectionExtensions.cs | 3 +- .../Storage/RelationalConnection.cs | 3 +- .../Storage/TypeMaterializationInfo.cs | 2 +- .../Update/Internal/CommandBatchPreparer.cs | 3 +- .../Internal/CompositeRowIndexValueFactory.cs | 2 - .../Update/Internal/IRowIndexValueFactory`.cs | 2 - .../Internal/SimpleRowIndexValueFactory.cs | 1 - .../Update/ModificationCommand.cs | 2 +- .../Update/UpdateAndSelectSqlGenerator.cs | 11 +- .../SqlServerHierarchyIdOptionsExtension.cs | 1 - .../SqlServerHierarchyIdMethodTranslator.cs | 3 +- ...SqlServerHierarchyIdCodeGeneratorPlugin.cs | 1 - .../SqlServerGeometryMethodTranslator.cs | 3 +- .../SqlServerOutputClauseConvention.cs | 2 +- .../SqlServerTemporalConvention.cs | 6 +- .../SqlServerMigrationsSqlGenerator.cs | 5 +- ...rchConditionConvertingExpressionVisitor.cs | 28 +- .../SkipTakeCollapsingExpressionVisitor.cs | 5 +- ...ServerFullTextSearchFunctionsTranslator.cs | 2 +- .../SqlServerObjectToStringTranslator.cs | 2 +- .../Internal/SqlServerQuerySqlGenerator.cs | 3 +- .../Internal/SqlServerQueryStringFactory.cs | 3 +- ...qlServerSqlTranslatingExpressionVisitor.cs | 1 - ...qlServerStringAggregateMethodTranslator.cs | 4 +- .../Internal/SqlServerDatabaseModelFactory.cs | 2 +- .../Internal/SqlServerByteArrayTypeMapping.cs | 3 +- .../SqlServerDateTimeOffsetTypeMapping.cs | 3 +- .../Storage/Internal/SqlServerTransaction.cs | 2 +- .../SqlServerModificationCommandBatch.cs | 2 +- .../Internal/SqlServerUpdateSqlGenerator.cs | 2 +- .../SqliteServiceCollectionExtensions.cs | 1 - .../Internal/SqliteModelValidator.cs | 1 - .../Internal/SqliteAnnotationProvider.cs | 3 +- .../SqliteMigrationsSqlGenerator.cs | 3 +- .../SqliteObjectToStringTranslator.cs | 2 +- ...yableMethodTranslatingExpressionVisitor.cs | 1 - .../Internal/SqliteSqlExpressionFactory.cs | 15 +- .../SqliteSqlTranslatingExpressionVisitor.cs | 3 +- .../Internal/SqliteDatabaseModelFactory.cs | 2 +- .../Storage/Internal/SqliteJsonTypeMapping.cs | 1 - .../ChangeTracking/Internal/ChangeDetector.cs | 1 - .../Internal/EntityGraphAttacher.cs | 3 +- .../Internal/EntityReferenceMap.cs | 13 +- .../ChangeTracking/Internal/IdentityMap.cs | 1 - .../Internal/InternalEntityEntry.cs | 17 +- .../ChangeTracking/Internal/KeyPropagator.cs | 1 - .../Internal/RelationshipsSnapshot.cs | 4 +- .../SimplePrincipalKeyValueFactory.cs | 1 - .../ChangeTracking/Internal/StateManager.cs | 2 +- src/EFCore/ChangeTracking/ReferenceEntry.cs | 3 +- src/EFCore/DbSet.cs | 1 - .../Diagnostics/Internal/DiagnosticsLogger.cs | 3 +- src/EFCore/EF.CompileAsyncQuery.cs | 7 +- src/EFCore/EF.CompileAsyncQuery.tt | 1 - src/EFCore/EF.CompileQuery.cs | 5 - src/EFCore/EF.CompileQuery.tt | 1 - .../Extensions/Internal/TypeExtensions.cs | 3 +- .../Infrastructure/CoreOptionsExtension.cs | 2 +- src/EFCore/Infrastructure/DbSetProperty.cs | 1 - src/EFCore/Infrastructure/ModelValidator.cs | 12 +- src/EFCore/Internal/DbContextFactorySource.cs | 2 +- src/EFCore/Internal/DbContextPool.cs | 2 +- src/EFCore/Internal/EntityFinderSource.cs | 1 - src/EFCore/Internal/IDbSetCache.cs | 1 - src/EFCore/Internal/IDbSetSource.cs | 1 - .../Builders/ReferenceNavigationBuilder.cs | 3 +- .../Conventions/DiscriminatorConvention.cs | 4 +- .../ForeignKeyAttributeConvention.cs | 3 +- .../ForeignKeyPropertyDiscoveryConvention.cs | 10 +- ...tionDispatcher.ImmediateConventionScope.cs | 10 +- .../ManyToManyJoinEntityTypeConvention.cs | 4 +- .../Internal/ClrCollectionAccessorFactory.cs | 1 - .../Internal/InternalEntityTypeBuilder.cs | 20 +- .../Internal/InternalForeignKeyBuilder.cs | 51 +-- src/EFCore/Metadata/Internal/Model.cs | 3 +- src/EFCore/Metadata/Internal/Property.cs | 2 +- .../Internal/PropertyConfiguration.cs | 2 +- src/EFCore/Metadata/RuntimeModel.cs | 3 +- src/EFCore/Metadata/RuntimeServiceProperty.cs | 1 - src/EFCore/ModelBuilder.cs | 3 +- src/EFCore/Query/EntityShaperExpression.cs | 2 +- src/EFCore/Query/ExpressionPrinter.cs | 8 +- .../Query/Internal/EntityQueryProvider.cs | 4 +- ...tionExpressionRemovingExpressionVisitor.cs | 3 +- ...ingExpressionVisitor.ExpressionVisitors.cs | 25 +- .../NavigationExpandingExpressionVisitor.cs | 44 +-- .../NullCheckRemovingExpressionVisitor.cs | 6 +- .../QueryOptimizingExpressionVisitor.cs | 54 ++- ...yableMethodNormalizingExpressionVisitor.cs | 21 +- ...SubqueryMemberPushdownExpressionVisitor.cs | 16 +- src/EFCore/Query/ProjectionMember.cs | 4 +- src/EFCore/Query/QueryCompilationContext.cs | 2 - .../ShapedQueryCompilingExpressionVisitor.cs | 7 +- src/EFCore/Storage/ExecutionStrategy.cs | 5 +- src/EFCore/Storage/TypeMappingInfo.cs | 2 +- .../SqliteConnection.cs | 1 - .../SqliteConnectionFactory.cs | 3 +- .../SqliteConnectionStringBuilder.cs | 2 +- .../SqliteValueReader.cs | 1 - src/Shared/Check.cs | 2 - src/Shared/DisposableExtensions.cs | 3 - src/Shared/EnumerableExtensions.cs | 5 - src/Shared/ExpressionExtensions.cs | 3 +- src/Shared/Graph.cs | 3 - src/Shared/MemberInfoExtensions.cs | 4 +- src/Shared/MethodInfoExtensions.cs | 5 +- src/Shared/NonCapturingLazyInitializer.cs | 1 - src/Shared/PropertyInfoExtensions.cs | 3 +- src/Shared/SharedTypeExtensions.cs | 16 +- src/ef/CommandLineUtils/CommandOption.cs | 2 +- .../TestUtilities/CosmosTestStore.cs | 3 +- .../DesignExceptionTest.cs | 2 - .../CustomConvertersInMemoryTest.cs | 1 - .../Query/FromSqlQueryTestBase.cs | 3 - .../Query/NorthwindQueryRelationalFixture.cs | 2 - ...windSplitIncludeNoTrackingQueryTestBase.cs | 1 - .../NorthwindSplitIncludeQueryTestBase.cs | 1 - .../Query/OperatorsProceduralQueryTestBase.cs | 5 +- .../TransactionTestBase.cs | 5 +- .../Metadata/RelationalModelTest.cs | 1 - .../Internal/MigrationsModelDifferTest.cs | 2 +- .../Storage/RelationalDataReaderTest.cs | 6 - .../GraphUpdates/GraphUpdatesTestBase.cs | 1 - .../GraphUpdatesTestBaseOneToMany.cs | 2 +- .../ProxyGraphUpdatesFixtureBase.cs | 2 - .../ProxyGraphUpdatesTestBaseOneToMany.cs | 2 +- ...NorthwindEFPropertyIncludeQueryTestBase.cs | 1 - ...NorthwindIncludeNoTrackingQueryTestBase.cs | 1 - .../Query/NorthwindIncludeQueryTestBase.cs | 1 - .../NorthwindMiscellaneousQueryTestBase.cs | 2 +- .../NorthwindStringIncludeQueryTestBase.cs | 1 - .../SerializationTestBase.cs | 1 - .../TestModels/Northwind/Employee.cs | 1 - .../ExpectedQueryRewritingVisitor.cs | 3 +- .../InjectThenByPropertyExpressionMutator.cs | 3 +- .../NorthwindBulkUpdatesSqlServerTest.cs | 2 - .../NorthwindCompiledQuerySqlServerTest.cs | 2 - .../SqlServerDatabaseModelFactoryTest.cs | 34 +- .../TestUtilities/SqlServerDatabaseCleaner.cs | 2 +- .../TestSqlServerRetryingExecutionStrategy.cs | 3 +- .../Migrations/AnonymousArraySeedContext.cs | 2 - .../Migrations/TypedArraySeedContext.cs | 2 - .../SqlServerOutputClauseConventionTest.cs | 2 - .../SqlServerBuilderExtensionsTest.cs | 2 - .../Query/NorthwindCompiledQuerySqliteTest.cs | 2 - .../NorthwindMiscellaneousQuerySqliteTest.cs | 1 - .../Query/NullSemanticsQuerySqliteTest.cs | 1 - .../ChangeTracking/Internal/OwnedFixupTest.cs | 1 - .../ChangeTracking/ObservableHashSetTest.cs | 1 - .../ChangeTracking/TrackGraphTestBase.cs | 2 +- test/EFCore.Tests/ExceptionTest.cs | 1 - .../Extensions/QueryableExtensionsTest.cs | 1 - .../ClrCollectionAccessorFactoryTest.cs | 2 +- .../Storage/TimeOnlyConvertersTest.cs | 2 - .../EFCore.Tests/Storage/ValueComparerTest.cs | 2 +- .../SqliteTransactionTest.cs | 333 ++++++++---------- 232 files changed, 668 insertions(+), 1098 deletions(-) diff --git a/src/EFCore.Analyzers/InternalUsageDiagnosticAnalyzer.cs b/src/EFCore.Analyzers/InternalUsageDiagnosticAnalyzer.cs index 68eaeb6c88e..7e610a8dea6 100644 --- a/src/EFCore.Analyzers/InternalUsageDiagnosticAnalyzer.cs +++ b/src/EFCore.Analyzers/InternalUsageDiagnosticAnalyzer.cs @@ -194,8 +194,7 @@ private static void AnalyzeNamedTypeSymbol(SymbolAnalysisContext context, INamed { var location = declaringSyntax.GetSyntax() switch { - CSharpSyntax.ClassDeclarationSyntax s when s.BaseList?.Types.Count > 0 - => s.BaseList.Types[0].GetLocation(), + CSharpSyntax.ClassDeclarationSyntax { BaseList.Types.Count: > 0 } s => s.BaseList.Types[0].GetLocation(), { } otherSyntax => otherSyntax.GetLocation() }; @@ -246,7 +245,8 @@ private static void AnalyzeMethodTypeSymbol(SymbolAnalysisContext context, IMeth { var location = declaringSyntax.GetSyntax() switch { - CSharpSyntax.ParameterSyntax s when s.Type != null => s.Type.GetLocation(), + CSharpSyntax.ParameterSyntax { Type: not null } s => s.Type.GetLocation(), + { } otherSyntax => otherSyntax.GetLocation() }; @@ -283,9 +283,7 @@ private static void ReportDiagnostic(SymbolAnalysisContext context, SyntaxNode s private static SyntaxNode NarrowDownSyntax(SyntaxNode syntax) => syntax switch { - CSharpSyntax.InvocationExpressionSyntax s - when s.Expression is CSharpSyntax.MemberAccessExpressionSyntax memberAccessSyntax - => memberAccessSyntax.Name, + CSharpSyntax.InvocationExpressionSyntax { Expression: CSharpSyntax.MemberAccessExpressionSyntax memberAccessSyntax } => memberAccessSyntax.Name, CSharpSyntax.MemberAccessExpressionSyntax s => s.Name, CSharpSyntax.ObjectCreationExpressionSyntax s => s.Type, CSharpSyntax.PropertyDeclarationSyntax s => s.Type, diff --git a/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs b/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs index c4c173183ca..2048ca35836 100644 --- a/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs +++ b/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs @@ -68,7 +68,7 @@ private static string ExecutingSqlQuery(EventDefinitionBase definition, EventDat return d.GenerateMessage( p.ContainerId, p.LogSensitiveData ? p.PartitionKey : "?", - FormatParameters(p.Parameters, p.LogSensitiveData && p.Parameters.Count > 0), + FormatParameters(p.Parameters, p is { LogSensitiveData: true, Parameters.Count: > 0 }), Environment.NewLine, p.QuerySql); } @@ -183,7 +183,7 @@ private static string ExecutedReadNext(EventDefinitionBase definition, EventData p.ActivityId, p.ContainerId, p.LogSensitiveData ? p.PartitionKey : "?", - FormatParameters(p.Parameters, p.LogSensitiveData && p.Parameters.Count > 0), + FormatParameters(p.Parameters, p is { LogSensitiveData: true, Parameters.Count: > 0 }), Environment.NewLine, p.QuerySql)); } diff --git a/src/EFCore.Cosmos/Metadata/Conventions/CosmosManyToManyJoinEntityTypeConvention.cs b/src/EFCore.Cosmos/Metadata/Conventions/CosmosManyToManyJoinEntityTypeConvention.cs index c33f05ba630..3ce440bbcc3 100644 --- a/src/EFCore.Cosmos/Metadata/Conventions/CosmosManyToManyJoinEntityTypeConvention.cs +++ b/src/EFCore.Cosmos/Metadata/Conventions/CosmosManyToManyJoinEntityTypeConvention.cs @@ -142,10 +142,8 @@ private void CreateSkipNavigationForeignKey( private void ProcessJoinPartitionKey(IConventionSkipNavigation skipNavigation) { var inverseSkipNavigation = skipNavigation.Inverse; - if (skipNavigation.JoinEntityType != null - && skipNavigation.IsCollection - && inverseSkipNavigation != null - && inverseSkipNavigation.IsCollection + if (skipNavigation is { JoinEntityType: not null, IsCollection: true } + && inverseSkipNavigation is { IsCollection: true } && inverseSkipNavigation.JoinEntityType == skipNavigation.JoinEntityType) { var joinEntityType = skipNavigation.JoinEntityType; diff --git a/src/EFCore.Cosmos/Metadata/Conventions/CosmosValueGenerationConvention.cs b/src/EFCore.Cosmos/Metadata/Conventions/CosmosValueGenerationConvention.cs index 50ddd2f2a2b..64828e5aa56 100644 --- a/src/EFCore.Cosmos/Metadata/Conventions/CosmosValueGenerationConvention.cs +++ b/src/EFCore.Cosmos/Metadata/Conventions/CosmosValueGenerationConvention.cs @@ -72,8 +72,7 @@ public virtual void ProcessEntityTypeAnnotationChanged( if (propertyType == typeof(int)) { var ownership = entityType.FindOwnership(); - if (ownership != null - && !ownership.IsUnique + if (ownership is { IsUnique: false } && !entityType.IsDocumentRoot()) { var pk = property.FindContainingPrimaryKey(); diff --git a/src/EFCore.Cosmos/Metadata/Internal/CosmosPropertyExtensions.cs b/src/EFCore.Cosmos/Metadata/Internal/CosmosPropertyExtensions.cs index 9faad7252fb..a115200db60 100644 --- a/src/EFCore.Cosmos/Metadata/Internal/CosmosPropertyExtensions.cs +++ b/src/EFCore.Cosmos/Metadata/Internal/CosmosPropertyExtensions.cs @@ -23,8 +23,7 @@ public static bool IsOrdinalKeyProperty(this IReadOnlyProperty property) property.DeclaringEntityType.IsOwned(), $"Expected {property.DeclaringEntityType.DisplayName()} to be owned."); Check.DebugAssert(property.GetJsonPropertyName().Length == 0, $"Expected {property.Name} to be non-persisted."); - return property.FindContainingPrimaryKey() is IReadOnlyKey key - && key.Properties.Count > 1 + return property.FindContainingPrimaryKey() is IReadOnlyKey { Properties.Count: > 1 } && !property.IsForeignKey() && property.ClrType == typeof(int) && (property.ValueGenerated & ValueGenerated.OnAdd) != 0; diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs index d071f276165..75b7352423c 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs @@ -316,7 +316,7 @@ protected override Expression VisitMember(MemberExpression memberExpression) var navigationProjection = innerEntityProjection.BindMember( memberExpression.Member, innerExpression.Type, clientEval: true, out var propertyBase); - if (!(propertyBase is INavigation navigation) + if (propertyBase is not INavigation navigation || !navigation.IsEmbedded()) { return NullSafeUpdate(innerExpression); @@ -509,7 +509,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp navigationProjection = innerEntityProjection.BindMember( memberName, visitedSource.Type, clientEval: true, out var propertyBase); - if (!(propertyBase is INavigation projectedNavigation) + if (propertyBase is not INavigation projectedNavigation || !projectedNavigation.IsEmbedded()) { return null; @@ -567,7 +567,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp case nameof(Queryable.Select) when genericMethod == QueryableMethods.Select: - if (!(visitedSource is CollectionShaperExpression shaper)) + if (visitedSource is not CollectionShaperExpression shaper) { return null; } diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs index 670786f6228..2c5f36bd029 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs @@ -78,8 +78,7 @@ protected CosmosQueryableMethodTranslatingExpressionVisitor( /// public override Expression Visit(Expression expression) { - if (expression is MethodCallExpression methodCallExpression - && methodCallExpression.Method.IsGenericMethod + if (expression is MethodCallExpression { Method.IsGenericMethod: true } methodCallExpression && methodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.FirstOrDefaultWithoutPredicate) { if (methodCallExpression.Arguments[0] is MethodCallExpression queryRootMethodCallExpression @@ -90,8 +89,7 @@ public override Expression Visit(Expression expression) { var entityType = entityQueryRootExpression.EntityType; - if (queryRootMethodCallExpression.Arguments[1] is UnaryExpression unaryExpression - && unaryExpression.Operand is LambdaExpression lambdaExpression) + if (queryRootMethodCallExpression.Arguments[1] is UnaryExpression { Operand: LambdaExpression lambdaExpression }) { var queryProperties = new List(); var parameterNames = new List(); @@ -636,9 +634,7 @@ protected override ShapedQueryExpression TranslateOfType(ShapedQueryExpression s } var selectExpression = (SelectExpression)source.QueryExpression; - if (!(translation is SqlConstantExpression sqlConstantExpression - && sqlConstantExpression.Value is bool constantValue - && constantValue)) + if (translation is not SqlConstantExpression { Value: true }) { selectExpression.ApplyPredicate(translation); } diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitorBase.cs b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitorBase.cs index c24cf9f867b..620034dee62 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitorBase.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitorBase.cs @@ -86,8 +86,7 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) projectionExpression = projection.Expression; storeName = projection.Alias; } - else if (projectionExpression is UnaryExpression convertExpression - && convertExpression.NodeType == ExpressionType.Convert) + else if (projectionExpression is UnaryExpression { NodeType: ExpressionType.Convert } convertExpression) { // Unwrap EntityProjectionExpression when the root entity is not projected projectionExpression = ((UnaryExpression)convertExpression.Operand).Operand; @@ -155,9 +154,7 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) } } - if (binaryExpression.Left is MemberExpression memberExpression - && memberExpression.Member is FieldInfo fieldInfo - && fieldInfo.IsInitOnly) + if (binaryExpression.Left is MemberExpression { Member: FieldInfo { IsInitOnly: true } } memberExpression) { return memberExpression.Assign(Visit(binaryExpression.Right)); } @@ -418,8 +415,7 @@ private static void IncludeReference( if (relatedEntity != null) { fixup(includingEntity, relatedEntity); - if (inverseNavigation != null - && !inverseNavigation.IsCollection) + if (inverseNavigation is { IsCollection: false }) { inverseNavigation.SetIsLoadedWhenNoTracking(relatedEntity); } diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ReadItemQueryingEnumerable.cs b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ReadItemQueryingEnumerable.cs index 3033433143d..fcdaa95da0e 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ReadItemQueryingEnumerable.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ReadItemQueryingEnumerable.cs @@ -322,7 +322,7 @@ public void Reset() private bool ShapeResult() { - var hasNext = !(_item is null); + var hasNext = _item is not null; _cosmosQueryContext.InitializeStateManager(_standAloneStateManager); diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs index 54b75a57ab3..792d27e216a 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs @@ -4,7 +4,6 @@ #nullable disable using System.Collections; -using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Cosmos.Internal; namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal; @@ -354,8 +353,7 @@ protected override Expression VisitExtension(Expression extensionExpression) if (result.NodeType == ExpressionType.Convert && result.Type == typeof(ValueBuffer) - && result is UnaryExpression outerUnary - && outerUnary.Operand.NodeType == ExpressionType.Convert + && result is UnaryExpression { Operand.NodeType: ExpressionType.Convert } outerUnary && outerUnary.Operand.Type == typeof(object)) { result = ((UnaryExpression)outerUnary.Operand).Operand; @@ -751,7 +749,7 @@ protected override Expression VisitTypeBinary(TypeBinaryExpression typeBinaryExp private Expression TryBindMember(Expression source, MemberIdentity member) { - if (!(source is EntityReferenceExpression entityReferenceExpression)) + if (source is not EntityReferenceExpression entityReferenceExpression) { return null; } @@ -814,7 +812,7 @@ private bool TryRewriteContainsEntity(Expression source, Expression item, out Ex { result = null; - if (!(item is EntityReferenceExpression itemEntityReference)) + if (item is not EntityReferenceExpression itemEntityReference) { return false; } @@ -1026,7 +1024,7 @@ private static List ParameterListValueExtractor( } private static bool IsNullSqlConstantExpression(Expression expression) - => expression is SqlConstantExpression sqlConstant && sqlConstant.Value == null; + => expression is SqlConstantExpression { Value: null }; private static bool TryEvaluateToConstant(Expression expression, out SqlConstantExpression sqlConstantExpression) { @@ -1061,7 +1059,7 @@ private static bool CanEvaluate(Expression expression) private static bool TranslationFailed(Expression original, Expression translation, out SqlExpression castTranslation) { if (original != null - && !(translation is SqlExpression)) + && translation is not SqlExpression) { castTranslation = null; return true; @@ -1106,8 +1104,7 @@ private sealed class SqlTypeMappingVerifyingExpressionVisitor : ExpressionVisito { protected override Expression VisitExtension(Expression extensionExpression) { - if (extensionExpression is SqlExpression sqlExpression - && sqlExpression.TypeMapping == null) + if (extensionExpression is SqlExpression { TypeMapping: null } sqlExpression) { throw new InvalidOperationException(CosmosStrings.NullTypeMappingInSqlTree(sqlExpression.Print())); } diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosStringMethodTranslator.cs b/src/EFCore.Cosmos/Query/Internal/CosmosStringMethodTranslator.cs index 7df140c9b40..182ff6c2511 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosStringMethodTranslator.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosStringMethodTranslator.cs @@ -187,10 +187,8 @@ public CosmosStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactory) if (SubstringMethodInfoWithTwoArgs.Equals(method)) { - return arguments[0] is SqlConstantExpression constant - && constant.Value is int intValue - && intValue == 0 - ? TranslateSystemFunction("LEFT", method.ReturnType, instance, arguments[1]) + return arguments[0] is SqlConstantExpression { Value: 0 } + ? TranslateSystemFunction("LEFT", method.ReturnType, instance, arguments[1]) : TranslateSystemFunction("SUBSTRING", method.ReturnType, instance, arguments[0], arguments[1]); } } @@ -237,8 +235,7 @@ public CosmosStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactory) { var comparisonTypeArgument = arguments[^1]; - if (comparisonTypeArgument is SqlConstantExpression constantComparisonTypeArgument - && constantComparisonTypeArgument.Value is StringComparison comparisonTypeArgumentValue + if (comparisonTypeArgument is SqlConstantExpression { Value: StringComparison comparisonTypeArgumentValue } && (comparisonTypeArgumentValue == StringComparison.OrdinalIgnoreCase || comparisonTypeArgumentValue == StringComparison.Ordinal)) { diff --git a/src/EFCore.Cosmos/Query/Internal/ExpressionExtensions.cs b/src/EFCore.Cosmos/Query/Internal/ExpressionExtensions.cs index b1120877d90..56b797680d9 100644 --- a/src/EFCore.Cosmos/Query/Internal/ExpressionExtensions.cs +++ b/src/EFCore.Cosmos/Query/Internal/ExpressionExtensions.cs @@ -21,8 +21,7 @@ public static class ExpressionExtensions { for (var i = 0; i < expressions.Length; i++) { - if (expressions[i] is SqlExpression sql - && sql.TypeMapping != null) + if (expressions[i] is SqlExpression { TypeMapping: not null } sql) { return sql.TypeMapping; } diff --git a/src/EFCore.Cosmos/Query/Internal/SelectExpression.cs b/src/EFCore.Cosmos/Query/Internal/SelectExpression.cs index 44e308fc959..18338422928 100644 --- a/src/EFCore.Cosmos/Query/Internal/SelectExpression.cs +++ b/src/EFCore.Cosmos/Query/Internal/SelectExpression.cs @@ -304,9 +304,7 @@ public virtual void ClearOrdering() /// public virtual void ApplyPredicate(SqlExpression expression) { - if (expression is SqlConstantExpression sqlConstant - && sqlConstant.Value is bool boolValue - && boolValue) + if (expression is SqlConstantExpression { Value: true }) { return; } diff --git a/src/EFCore.Cosmos/Query/Internal/SqlConstantExpression.cs b/src/EFCore.Cosmos/Query/Internal/SqlConstantExpression.cs index 5df217331e9..30fe132d68b 100644 --- a/src/EFCore.Cosmos/Query/Internal/SqlConstantExpression.cs +++ b/src/EFCore.Cosmos/Query/Internal/SqlConstantExpression.cs @@ -70,9 +70,7 @@ private void Print( object? value, ExpressionPrinter expressionPrinter) { - if (value is IEnumerable enumerable - && !(value is string) - && !(value is byte[])) + if (value is IEnumerable enumerable and not (string or byte[])) { var first = true; foreach (var item in enumerable) diff --git a/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs b/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs index d1ad7893f98..428e89b00e4 100644 --- a/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs +++ b/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs @@ -3,7 +3,6 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Cosmos.Internal; -using Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal; using Microsoft.EntityFrameworkCore.Internal; namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal; diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs index 247acd2af4a..3bd43272772 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs @@ -484,8 +484,7 @@ private static void ProcessResponse(ResponseMessage response, IUpdateEntry entry } var jObjectProperty = entry.EntityType.FindProperty(StoreKeyConvention.JObjectPropertyName); - if (jObjectProperty != null - && jObjectProperty.ValueGenerated == ValueGenerated.OnAddOrUpdate + if (jObjectProperty is { ValueGenerated: ValueGenerated.OnAddOrUpdate } && response.Content != null) { using var responseStream = response.Content; diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs index f555011281c..ce9dd461aaf 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs @@ -90,8 +90,7 @@ public CosmosTypeMappingSource(TypeMappingSourceDependencies dependencies) clrType, CreateArrayComparer(elementMapping, elementType), jsonValueReaderWriter: jsonValueReaderWriter); } - if (clrType.IsGenericType - && !clrType.IsGenericTypeDefinition) + if (clrType is { IsGenericType: true, IsGenericTypeDefinition: false }) { var genericTypeDefinition = clrType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(List<>) diff --git a/src/EFCore.Design/Design/Internal/CSharpHelper.cs b/src/EFCore.Design/Design/Internal/CSharpHelper.cs index cea921d95ef..ea3fb0f8fc8 100644 --- a/src/EFCore.Design/Design/Internal/CSharpHelper.cs +++ b/src/EFCore.Design/Design/Internal/CSharpHelper.cs @@ -1028,7 +1028,7 @@ public virtual string UnknownLiteral(object? value) } var valueType = value.GetType(); - if (valueType.IsGenericType && !valueType.IsGenericTypeDefinition) + if (valueType is { IsGenericType: true, IsGenericTypeDefinition: false }) { var genericArguments = valueType.GetGenericArguments(); switch (value) @@ -1519,8 +1519,7 @@ private static bool IsIdentifierPartCharacter(char ch) if (ch < 'a') { return (ch < 'A' - ? ch >= '0' - && ch <= '9' + ? ch is >= '0' and <= '9' : ch <= 'Z') || ch == '_'; } diff --git a/src/EFCore.Design/Design/Internal/DbContextOperations.cs b/src/EFCore.Design/Design/Internal/DbContextOperations.cs index bc354a1733a..c0c9aeb0570 100644 --- a/src/EFCore.Design/Design/Internal/DbContextOperations.cs +++ b/src/EFCore.Design/Design/Internal/DbContextOperations.cs @@ -161,7 +161,7 @@ public virtual void Optimize(string? outputDir, string? modelNamespace, string? _reporter.WriteInformation(DesignStrings.CompiledModelGenerated($"options.UseModel({fullName}.Instance)")); var cacheKeyFactory = context.GetService(); - if (!(cacheKeyFactory is ModelCacheKeyFactory)) + if (cacheKeyFactory is not ModelCacheKeyFactory) { _reporter.WriteWarning(DesignStrings.CompiledModelCustomCacheKeyFactory(cacheKeyFactory.GetType().ShortDisplayName())); } diff --git a/src/EFCore.Design/Extensions/ScaffoldingModelExtensions.cs b/src/EFCore.Design/Extensions/ScaffoldingModelExtensions.cs index 98193c73d2b..c03dec53472 100644 --- a/src/EFCore.Design/Extensions/ScaffoldingModelExtensions.cs +++ b/src/EFCore.Design/Extensions/ScaffoldingModelExtensions.cs @@ -27,8 +27,7 @@ public static bool IsSimpleManyToManyJoinEntityType(this IEntityType entityType) var primaryKey = entityType.FindPrimaryKey(); var properties = entityType.GetProperties().ToList(); var foreignKeys = entityType.GetForeignKeys().ToList(); - if (primaryKey != null - && primaryKey.Properties.Count > 1 + if (primaryKey is { Properties.Count: > 1 } && foreignKeys.Count == 2 && primaryKey.Properties.Count == properties.Count && foreignKeys[0].Properties.Count + foreignKeys[1].Properties.Count == properties.Count diff --git a/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs b/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs index 74dd9204456..10237c7410e 100644 --- a/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs +++ b/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs @@ -91,7 +91,7 @@ protected virtual void GenerateEntityTypes( } foreach (var entityType in nonOwnedTypes.Where( - e => e.GetDeclaredNavigations().Any(n => !n.IsOnDependent && !n.ForeignKey.IsOwnership))) + e => e.GetDeclaredNavigations().Any(n => n is { IsOnDependent: false, ForeignKey.IsOwnership: false }))) { stringBuilder.AppendLine(); diff --git a/src/EFCore.Design/Migrations/Internal/SnapshotModelProcessor.cs b/src/EFCore.Design/Migrations/Internal/SnapshotModelProcessor.cs index 0313ecc4853..edda96f37d2 100644 --- a/src/EFCore.Design/Migrations/Internal/SnapshotModelProcessor.cs +++ b/src/EFCore.Design/Migrations/Internal/SnapshotModelProcessor.cs @@ -136,7 +136,7 @@ private static void UpdateSequences(IReadOnlyModel model, string version) if ((!version.StartsWith("1.", StringComparison.Ordinal) && !version.StartsWith("2.", StringComparison.Ordinal) && !version.StartsWith("3.", StringComparison.Ordinal)) - || !(model is IMutableModel mutableModel)) + || model is not IMutableModel mutableModel) { return; } @@ -161,7 +161,7 @@ private static void UpdateSequences(IReadOnlyModel model, string version) private static void UpdateOwnedTypes(IMutableEntityType entityType) { - var ownerships = entityType.GetDeclaredReferencingForeignKeys().Where(fk => fk.IsOwnership && fk.IsUnique) + var ownerships = entityType.GetDeclaredReferencingForeignKeys().Where(fk => fk is { IsOwnership: true, IsUnique: true }) .ToList(); foreach (var ownership in ownerships) { diff --git a/src/EFCore.Design/Scaffolding/Internal/CSharpEntityTypeGenerator.tt b/src/EFCore.Design/Scaffolding/Internal/CSharpEntityTypeGenerator.tt index fedb55bae0c..80642ee0497 100644 --- a/src/EFCore.Design/Scaffolding/Internal/CSharpEntityTypeGenerator.tt +++ b/src/EFCore.Design/Scaffolding/Internal/CSharpEntityTypeGenerator.tt @@ -98,8 +98,8 @@ public partial class <#= EntityType.Name #> usings.AddRange(code.GetRequiredUsings(property.ClrType)); - var needsNullable = Options.UseNullableReferenceTypes && property.IsNullable && !property.ClrType.IsValueType; - var needsInitializer = Options.UseNullableReferenceTypes && !property.IsNullable && !property.ClrType.IsValueType; + var needsNullable = Options.UseNullableReferenceTypes && property is { IsNullable: true,ClrType.IsValueType: false }; + var needsInitializer = Options.UseNullableReferenceTypes && property is { IsNullable: false,ClrType.IsValueType: false }; #> public <#= code.Reference(property.ClrType) #><#= needsNullable ? "?" : "" #> <#= property.Name #> { get; set; }<#= needsInitializer ? " = null!;" : "" #> <# diff --git a/src/EFCore.Design/Scaffolding/Internal/CSharpUtilities.cs b/src/EFCore.Design/Scaffolding/Internal/CSharpUtilities.cs index 4261887b8ea..1faaea89f72 100644 --- a/src/EFCore.Design/Scaffolding/Internal/CSharpUtilities.cs +++ b/src/EFCore.Design/Scaffolding/Internal/CSharpUtilities.cs @@ -241,8 +241,7 @@ private static bool IsIdentifierPartCharacter(char ch) if (ch < 'a') { return ch < 'A' - ? ch >= '0' - && ch <= '9' + ? ch is >= '0' and <= '9' : ch <= 'Z' || ch == '_'; } diff --git a/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs b/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs index 3f45fc9d67b..40032248f1c 100644 --- a/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs +++ b/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs @@ -523,9 +523,7 @@ protected virtual EntityTypeBuilder VisitColumns(EntityTypeBuilder builder, ICol var keyBuilder = builder.HasKey(primaryKey.Columns.Select(GetPropertyName).ToArray()); - if (primaryKey.Columns.Count == 1 - && primaryKey.Columns[0].ValueGenerated == null - && primaryKey.Columns[0].DefaultValueSql == null) + if (primaryKey.Columns is [{ ValueGenerated: null, DefaultValueSql: null }]) { var property = builder.Metadata.FindProperty(GetPropertyName(primaryKey.Columns[0])); if (property != null) diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs index cacec189203..5db2946faca 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs @@ -157,8 +157,7 @@ protected virtual void AddTranslationErrorDetails(string details) protected override Expression VisitBinary(BinaryExpression binaryExpression) { if (binaryExpression.Left.Type == typeof(object[]) - && binaryExpression.Left is NewArrayExpression - && binaryExpression.NodeType == ExpressionType.Equal) + && binaryExpression is { Left: NewArrayExpression, NodeType: ExpressionType.Equal }) { return Visit(ConvertObjectArrayEqualityComparison(binaryExpression.Left, binaryExpression.Right)); } @@ -627,8 +626,7 @@ protected override Expression VisitMemberInit(MemberInitExpression memberInitExp } newBindings[i] = VisitMemberBinding(memberInitExpression.Bindings[i]); - if (((MemberAssignment)newBindings[i]).Expression is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Convert + if (((MemberAssignment)newBindings[i]).Expression is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression && unaryExpression.Operand == QueryCompilationContext.NotTranslatedExpression) { return QueryCompilationContext.NotTranslatedExpression; @@ -679,8 +677,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp var shaperExpression = subqueryTranslation.ShaperExpression; var innerExpression = shaperExpression; Type? convertedType = null; - if (shaperExpression is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Convert) + if (shaperExpression is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression) { convertedType = unaryExpression.Type; innerExpression = unaryExpression.Operand; @@ -743,8 +740,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp var method = methodCallExpression.Method; if (method.Name == nameof(object.Equals) - && methodCallExpression.Object != null - && methodCallExpression.Arguments.Count == 1) + && methodCallExpression is { Object: not null, Arguments.Count: 1 }) { var left = Visit(methodCallExpression.Object); var right = Visit(methodCallExpression.Arguments[0]); @@ -1085,10 +1081,11 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) } var result = (Expression)Expression.MakeUnary(unaryExpression.NodeType, newOperand, unaryExpression.Type); - if (result is UnaryExpression outerUnary - && outerUnary.NodeType == ExpressionType.Convert - && outerUnary.Operand is UnaryExpression innerUnary - && innerUnary.NodeType == ExpressionType.Convert) + if (result is UnaryExpression + { + NodeType: ExpressionType.Convert, + Operand: UnaryExpression { NodeType: ExpressionType.Convert } innerUnary + } outerUnary) { var innerMostType = innerUnary.Operand.Type; var intermediateType = innerUnary.Type; @@ -1111,7 +1108,7 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) private Expression? TryBindMember(Expression? source, MemberIdentity member, Type type) { - if (!(source is EntityReferenceExpression entityReferenceExpression)) + if (source is not EntityReferenceExpression entityReferenceExpression) { return null; } @@ -1193,8 +1190,7 @@ private static Expression ProcessSingleResultScalar( var serverQuery = inMemoryQueryExpression.ServerQueryExpression; serverQuery = ((LambdaExpression)((NewExpression)serverQuery).Arguments[0]).Body; - if (serverQuery is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Convert + if (serverQuery is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression && unaryExpression.Type == typeof(object)) { serverQuery = unaryExpression.Operand; @@ -1247,8 +1243,7 @@ private static Expression ConvertToNonNullable(Expression expression) expression = unaryExpression.Operand; } - if (expression is MethodCallExpression readValueMethodCall - && readValueMethodCall.Method.IsGenericMethod + if (expression is MethodCallExpression { Method.IsGenericMethod: true } readValueMethodCall && readValueMethodCall.Method.GetGenericMethodDefinition() == ExpressionExtensions.ValueBufferTryReadValueMethod) { return readValueMethodCall.Arguments[2].GetConstantValue(); @@ -1261,7 +1256,7 @@ private bool TryRewriteContainsEntity(Expression? source, Expression item, [NotN { result = null; - if (!(item is EntityReferenceExpression itemEntityReference)) + if (item is not EntityReferenceExpression itemEntityReference) { return false; } @@ -1299,9 +1294,8 @@ private bool TryRewriteContainsEntity(Expression? source, Expression item, [NotN rewrittenSource = Expression.Constant(propertyValueList); break; - case MethodCallExpression methodCallExpression - when methodCallExpression.Method.IsGenericMethod - && methodCallExpression.Method.GetGenericMethodDefinition() == GetParameterValueMethodInfo: + case MethodCallExpression { Method.IsGenericMethod: true } methodCallExpression + when methodCallExpression.Method.GetGenericMethodDefinition() == GetParameterValueMethodInfo: var parameterName = methodCallExpression.Arguments[1].GetConstantValue(); var lambda = Expression.Lambda( Expression.Call( @@ -1445,9 +1439,8 @@ constantExpression.Value is null : property.GetGetter().GetClrValue(constantExpression.Value), property.ClrType.MakeNullable()); - case MethodCallExpression methodCallExpression - when methodCallExpression.Method.IsGenericMethod - && methodCallExpression.Method.GetGenericMethodDefinition() == GetParameterValueMethodInfo: + case MethodCallExpression { Method.IsGenericMethod: true } methodCallExpression + when methodCallExpression.Method.GetGenericMethodDefinition() == GetParameterValueMethodInfo: var parameterName = methodCallExpression.Arguments[1].GetConstantValue(); var lambda = Expression.Lambda( Expression.Call( @@ -1565,7 +1558,7 @@ static Expression RemoveObjectConvert(Expression expression) } private static bool IsNullConstantExpression(Expression expression) - => expression is ConstantExpression constantExpression && constantExpression.Value == null; + => expression is ConstantExpression { Value: null }; [DebuggerStepThrough] private static bool TranslationFailed(Expression? original, Expression? translation) diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs index 5e143d40040..8ad863f1612 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryProjectionBindingExpressionVisitor.cs @@ -93,10 +93,7 @@ public virtual Expression Translate(InMemoryQueryExpression queryExpression, Exp return null; } - if (!(expression is NewExpression - || expression is MemberInitExpression - || expression is EntityShaperExpression - || expression is IncludeExpression)) + if (expression is not (NewExpression or MemberInitExpression or EntityShaperExpression or IncludeExpression)) { if (_indexBasedBinding) { @@ -388,8 +385,7 @@ protected override Expression VisitMemberInit(MemberInitExpression memberInitExp } newBindings[i] = VisitMemberBinding(memberInitExpression.Bindings[i]); - if (((MemberAssignment)newBindings[i]).Expression is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Convert + if (((MemberAssignment)newBindings[i]).Expression is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression && unaryExpression.Operand == QueryCompilationContext.NotTranslatedExpression) { return QueryCompilationContext.NotTranslatedExpression; diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs b/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs index dba6a1388c7..1774c93672f 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs @@ -849,7 +849,7 @@ private static Expression GetGroupingKey(Expression key, List groupi return newExpression.Update(arguments); case MemberInitExpression memberInitExpression: - if (memberInitExpression.Bindings.Any(mb => !(mb is MemberAssignment))) + if (memberInitExpression.Bindings.Any(mb => mb is not MemberAssignment)) { goto default; } @@ -869,8 +869,7 @@ private static Expression GetGroupingKey(Expression key, List groupi return memberInitExpression.Update(updatedNewExpression, memberBindings); - case EntityShaperExpression entityShaperExpression - when entityShaperExpression.ValueBufferExpression is ProjectionBindingExpression projectionBindingExpression: + case EntityShaperExpression { ValueBufferExpression: ProjectionBindingExpression projectionBindingExpression } entityShaperExpression: var entityProjectionExpression = (EntityProjectionExpression)((InMemoryQueryExpression)projectionBindingExpression.QueryExpression) .GetProjection(projectionBindingExpression); @@ -1162,8 +1161,7 @@ private static IEnumerable GetAllPropertiesInHierarchy(IEntityType en .SelectMany(t => t.GetDeclaredProperties()); private static IPropertyBase? InferPropertyFromInner(Expression expression) - => expression is MethodCallExpression methodCallExpression - && methodCallExpression.Method.IsGenericMethod + => expression is MethodCallExpression { Method.IsGenericMethod: true } methodCallExpression && methodCallExpression.Method.GetGenericMethodDefinition() == ExpressionExtensions.ValueBufferTryReadValueMethod ? methodCallExpression.Arguments[2].GetConstantValue() : null; diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryQueryTranslationPreprocessor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryQueryTranslationPreprocessor.cs index f4284566961..14d4bd6d74e 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryQueryTranslationPreprocessor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryQueryTranslationPreprocessor.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.EntityFrameworkCore.InMemory.Internal; -using System.Linq.Expressions; namespace Microsoft.EntityFrameworkCore.InMemory.Query.Internal; @@ -37,8 +36,7 @@ public override Expression Process(Expression query) { var result = base.Process(query); - if (result is MethodCallExpression methodCallExpression - && methodCallExpression.Method.IsGenericMethod + if (result is MethodCallExpression { Method.IsGenericMethod: true } methodCallExpression && (methodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.GroupByWithKeySelector || methodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.GroupByWithKeyElementSelector)) { diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs index f2961ba9cc2..a71aa209c08 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs @@ -441,8 +441,7 @@ private static ShapedQueryExpression CreateShapedQueryExpressionStatic(IEntityTy return memberInitExpression.Update(updatedNewExpression, newBindings); - case EntityShaperExpression entityShaperExpression - when entityShaperExpression.ValueBufferExpression is ProjectionBindingExpression projectionBindingExpression: + case EntityShaperExpression { ValueBufferExpression: ProjectionBindingExpression projectionBindingExpression } entityShaperExpression: return entityShaperExpression; default: @@ -583,9 +582,7 @@ private static bool ProcessJoinCondition( } } - if (joinCondition is MethodCallExpression methodCallExpression - && methodCallExpression.Method.Name == nameof(object.Equals) - && methodCallExpression.Arguments.Count == 2 + if (joinCondition is MethodCallExpression { Method.Name: nameof(object.Equals), Arguments.Count: 2 } methodCallExpression && ((methodCallExpression.Method.IsStatic && methodCallExpression.Method.DeclaringType == typeof(object)) || typeof(ValueComparer).IsAssignableFrom(methodCallExpression.Method.DeclaringType))) diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.ShaperExpressionProcessingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.ShaperExpressionProcessingExpressionVisitor.cs index e7a4125c9c5..465fae18a97 100644 --- a/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.ShaperExpressionProcessingExpressionVisitor.cs +++ b/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.ShaperExpressionProcessingExpressionVisitor.cs @@ -201,8 +201,7 @@ protected override Expression VisitExtension(Expression extensionExpression) protected override Expression VisitBinary(BinaryExpression binaryExpression) { - if (binaryExpression.NodeType == ExpressionType.Assign - && binaryExpression.Left is ParameterExpression parameterExpression + if (binaryExpression is { NodeType: ExpressionType.Assign, Left: ParameterExpression parameterExpression } && parameterExpression.Type == typeof(MaterializationContext)) { var newExpression = (NewExpression)binaryExpression.Right; @@ -220,10 +219,7 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) return Expression.MakeBinary(ExpressionType.Assign, binaryExpression.Left, updatedExpression); } - if (binaryExpression.NodeType == ExpressionType.Assign - && binaryExpression.Left is MemberExpression memberExpression - && memberExpression.Member is FieldInfo fieldInfo - && fieldInfo.IsInitOnly) + if (binaryExpression is { NodeType: ExpressionType.Assign, Left: MemberExpression { Member: FieldInfo { IsInitOnly: true } } memberExpression }) { return memberExpression.Assign(Visit(binaryExpression.Right)); } @@ -282,8 +278,7 @@ private static void IncludeReference if (relatedEntity != null) { fixup(includingEntity, relatedEntity); - if (inverseNavigation != null - && !inverseNavigation.IsCollection) + if (inverseNavigation is { IsCollection: false }) { inverseNavigation.SetIsLoadedWhenNoTracking(relatedEntity); } diff --git a/src/EFCore.Proxies/Proxies/Internal/LazyLoadingInterceptor.cs b/src/EFCore.Proxies/Proxies/Internal/LazyLoadingInterceptor.cs index f6e4cfe6f5b..ec096a7471b 100644 --- a/src/EFCore.Proxies/Proxies/Internal/LazyLoadingInterceptor.cs +++ b/src/EFCore.Proxies/Proxies/Internal/LazyLoadingInterceptor.cs @@ -64,9 +64,7 @@ public virtual void Intercept(IInvocation invocation) var navigationBase = _entityType.FindNavigation(navigationName) ?? (INavigationBase?)_entityType.FindSkipNavigation(navigationName); - if (navigationBase != null - && (!(navigationBase is INavigation navigation - && navigation.ForeignKey.IsOwnership))) + if (navigationBase is not (null or INavigation { ForeignKey.IsOwnership: true })) { _loader.Load(invocation.Proxy, navigationName); } diff --git a/src/EFCore.Proxies/Proxies/Internal/PropertyChangedInterceptor.cs b/src/EFCore.Proxies/Proxies/Internal/PropertyChangedInterceptor.cs index e78c7bf02b8..f67e5fc52a0 100644 --- a/src/EFCore.Proxies/Proxies/Internal/PropertyChangedInterceptor.cs +++ b/src/EFCore.Proxies/Proxies/Internal/PropertyChangedInterceptor.cs @@ -4,7 +4,6 @@ using System.Collections; using System.ComponentModel; using Castle.DynamicProxy; -using Microsoft.EntityFrameworkCore.Internal; using IInterceptor = Castle.DynamicProxy.IInterceptor; namespace Microsoft.EntityFrameworkCore.Proxies.Internal; diff --git a/src/EFCore.Proxies/Proxies/Internal/PropertyChangingInterceptor.cs b/src/EFCore.Proxies/Proxies/Internal/PropertyChangingInterceptor.cs index 8b467c0e563..670639d5369 100644 --- a/src/EFCore.Proxies/Proxies/Internal/PropertyChangingInterceptor.cs +++ b/src/EFCore.Proxies/Proxies/Internal/PropertyChangingInterceptor.cs @@ -4,7 +4,6 @@ using System.Collections; using System.ComponentModel; using Castle.DynamicProxy; -using Microsoft.EntityFrameworkCore.Internal; using IInterceptor = Castle.DynamicProxy.IInterceptor; namespace Microsoft.EntityFrameworkCore.Proxies.Internal; diff --git a/src/EFCore.Proxies/Proxies/Internal/ProxiesOptionsExtension.cs b/src/EFCore.Proxies/Proxies/Internal/ProxiesOptionsExtension.cs index 170b0367e51..1d57fd733c0 100644 --- a/src/EFCore.Proxies/Proxies/Internal/ProxiesOptionsExtension.cs +++ b/src/EFCore.Proxies/Proxies/Internal/ProxiesOptionsExtension.cs @@ -201,7 +201,7 @@ public override bool IsDatabaseProvider => false; public override string LogFragment - => _logFragment ??= Extension.UseLazyLoadingProxies && Extension.UseChangeTrackingProxies + => _logFragment ??= Extension is { UseLazyLoadingProxies: true, UseChangeTrackingProxies: true } ? "using lazy loading and change tracking proxies " : Extension.UseLazyLoadingProxies ? "using lazy loading proxies " diff --git a/src/EFCore.Proxies/Proxies/Internal/ProxyBindingRewriter.cs b/src/EFCore.Proxies/Proxies/Internal/ProxyBindingRewriter.cs index 316e33b9aae..8d14b9ab1ed 100644 --- a/src/EFCore.Proxies/Proxies/Internal/ProxyBindingRewriter.cs +++ b/src/EFCore.Proxies/Proxies/Internal/ProxyBindingRewriter.cs @@ -101,8 +101,7 @@ public virtual void ProcessModelFinalizing( || !navigationBase.PropertyInfo.GetMethod!.IsReallyVirtual()) { if (!_options.IgnoreNonVirtualNavigations - && !(navigationBase is INavigation navigation - && navigation.ForeignKey.IsOwnership)) + && navigationBase is not INavigation { ForeignKey.IsOwnership: true }) { if (navigationBase.PropertyInfo == null) { diff --git a/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs b/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs index c15cda1c5fd..e506eae509b 100644 --- a/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs +++ b/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs @@ -217,8 +217,7 @@ public virtual IReadOnlyList GenerateFluentApiCalls( } if (annotations.TryGetValue(RelationalAnnotationNames.ContainerColumnName, out var containerColumnNameAnnotation) - && containerColumnNameAnnotation != null - && containerColumnNameAnnotation.Value is string containerColumnName + && containerColumnNameAnnotation is { Value: string containerColumnName } && entityType.IsOwned()) { methodCallCodeFragments.Add( diff --git a/src/EFCore.Relational/Extensions/Internal/RelationalPropertyInternalExtensions.cs b/src/EFCore.Relational/Extensions/Internal/RelationalPropertyInternalExtensions.cs index 904292a95b0..f1e3e035d6b 100644 --- a/src/EFCore.Relational/Extensions/Internal/RelationalPropertyInternalExtensions.cs +++ b/src/EFCore.Relational/Extensions/Internal/RelationalPropertyInternalExtensions.cs @@ -18,8 +18,7 @@ public static class RelationalPropertyInternalExtensions /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public static bool IsOrdinalKeyProperty(this IReadOnlyProperty property) - => property.FindContainingPrimaryKey() is IReadOnlyKey key - && key.Properties.Count > 1 + => property.FindContainingPrimaryKey() is IReadOnlyKey { Properties.Count: > 1 } && !property.IsForeignKey() && property.ClrType == typeof(int) && property.GetJsonPropertyName() == null; diff --git a/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs b/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs index 98d80bc64dc..f07f43709ef 100644 --- a/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs @@ -375,8 +375,7 @@ public static void SetViewName(this IMutableEntityType entityType, string? name) public static string? GetDefaultViewSchema(this IReadOnlyEntityType entityType) { var ownership = entityType.FindOwnership(); - if (ownership != null - && ownership.IsUnique) + if (ownership is { IsUnique: true }) { return ownership.PrincipalEntityType.GetViewSchema(); } diff --git a/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs b/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs index 3ae8d586c88..088bc3c0865 100644 --- a/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs @@ -167,8 +167,7 @@ public static string GetDefaultColumnName(this IReadOnlyProperty property) { var foreignKey = property.GetContainingForeignKeys().First(); var principalEntityType = foreignKey.PrincipalEntityType; - if (!principalEntityType.HasSharedClrType - && principalEntityType.ClrType.IsConstructedGenericType + if (principalEntityType is { HasSharedClrType: false, ClrType.IsConstructedGenericType: true } && foreignKey.DependentToPrincipal == null) { var principalProperty = property.FindFirstPrincipal()!; diff --git a/src/EFCore.Relational/Infrastructure/RelationalOptionsExtension.cs b/src/EFCore.Relational/Infrastructure/RelationalOptionsExtension.cs index 225065d9289..925ed928e79 100644 --- a/src/EFCore.Relational/Infrastructure/RelationalOptionsExtension.cs +++ b/src/EFCore.Relational/Infrastructure/RelationalOptionsExtension.cs @@ -149,8 +149,7 @@ public virtual int? CommandTimeout /// A new instance with the option changed. public virtual RelationalOptionsExtension WithCommandTimeout(int? commandTimeout) { - if (commandTimeout.HasValue - && commandTimeout <= 0) + if (commandTimeout is <= 0) { throw new InvalidOperationException(RelationalStrings.InvalidCommandTimeout(commandTimeout)); } diff --git a/src/EFCore.Relational/Metadata/Conventions/RelationalMapToJsonConvention.cs b/src/EFCore.Relational/Metadata/Conventions/RelationalMapToJsonConvention.cs index a418180661b..4197f5ed9a8 100644 --- a/src/EFCore.Relational/Metadata/Conventions/RelationalMapToJsonConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/RelationalMapToJsonConvention.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Text.Json; - namespace Microsoft.EntityFrameworkCore.Metadata.Conventions; /// diff --git a/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionBuilder.cs b/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionBuilder.cs index 3e06d0c71e8..ea8b52edbc7 100644 --- a/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionBuilder.cs +++ b/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionBuilder.cs @@ -218,7 +218,7 @@ public virtual bool CanSetTypeMapping(RelationalTypeMapping? returnTypeMapping, public virtual bool CanSetTranslation( Func, SqlExpression>? translation, ConfigurationSource configurationSource) - => (Metadata.IsScalar && !Metadata.IsAggregate || configurationSource == ConfigurationSource.Explicit) + => (Metadata is { IsScalar: true, IsAggregate: false } || configurationSource == ConfigurationSource.Explicit) && (configurationSource.Overrides(Metadata.GetTranslationConfigurationSource()) || Metadata.Translation == translation); diff --git a/src/EFCore.Relational/Metadata/Internal/JsonColumnBase.cs b/src/EFCore.Relational/Metadata/Internal/JsonColumnBase.cs index 5cbf630b762..57b441ae5e4 100644 --- a/src/EFCore.Relational/Metadata/Internal/JsonColumnBase.cs +++ b/src/EFCore.Relational/Metadata/Internal/JsonColumnBase.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Text.Json; -using Microsoft.EntityFrameworkCore.Update.Internal; namespace Microsoft.EntityFrameworkCore.Metadata.Internal; diff --git a/src/EFCore.Relational/Metadata/Internal/RelationalModel.cs b/src/EFCore.Relational/Metadata/Internal/RelationalModel.cs index 7a59f24b6d5..da1b1879f4c 100644 --- a/src/EFCore.Relational/Metadata/Internal/RelationalModel.cs +++ b/src/EFCore.Relational/Metadata/Internal/RelationalModel.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Data; using System.Text.Json; namespace Microsoft.EntityFrameworkCore.Metadata.Internal; diff --git a/src/EFCore.Relational/Metadata/Internal/StoreStoredProcedureResultColumn.cs b/src/EFCore.Relational/Metadata/Internal/StoreStoredProcedureResultColumn.cs index 19efea82fb4..b3e0684261f 100644 --- a/src/EFCore.Relational/Metadata/Internal/StoreStoredProcedureResultColumn.cs +++ b/src/EFCore.Relational/Metadata/Internal/StoreStoredProcedureResultColumn.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; - namespace Microsoft.EntityFrameworkCore.Metadata.Internal; /// diff --git a/src/EFCore.Relational/Metadata/Internal/StoreStoredProcedureReturnValue.cs b/src/EFCore.Relational/Metadata/Internal/StoreStoredProcedureReturnValue.cs index 67d9266a88a..27b6e1702b1 100644 --- a/src/EFCore.Relational/Metadata/Internal/StoreStoredProcedureReturnValue.cs +++ b/src/EFCore.Relational/Metadata/Internal/StoreStoredProcedureReturnValue.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; - namespace Microsoft.EntityFrameworkCore.Metadata.Internal; /// diff --git a/src/EFCore.Relational/Query/EntityProjectionExpression.cs b/src/EFCore.Relational/Query/EntityProjectionExpression.cs index 2fff09d7754..de75b1589d0 100644 --- a/src/EFCore.Relational/Query/EntityProjectionExpression.cs +++ b/src/EFCore.Relational/Query/EntityProjectionExpression.cs @@ -121,7 +121,8 @@ public virtual EntityProjectionExpression MakeNullable() if (shaper.EntityType.IsMappedToJson()) { // even if shaper is nullable, we need to make sure key property map contains nullable keys, - // if json entity itself is optional, the shaper would be null, but the PK of the owner entity would be non-nullable intially + // if json entity itself is optional, the shaper would be null, but the PK of the owner entity would be non-nullable + // initially var jsonQueryExpression = (JsonQueryExpression)shaper.ValueBufferExpression; var newJsonQueryExpression = jsonQueryExpression.MakeNullable(); var newShaper = shaper.Update(newJsonQueryExpression).MakeNullable(); diff --git a/src/EFCore.Relational/Query/EnumerableExpression.cs b/src/EFCore.Relational/Query/EnumerableExpression.cs index ce77a06395b..a038c641d9f 100644 --- a/src/EFCore.Relational/Query/EnumerableExpression.cs +++ b/src/EFCore.Relational/Query/EnumerableExpression.cs @@ -81,9 +81,7 @@ public virtual EnumerableExpression ApplyDistinct() /// The new expression with specified component updated. public virtual EnumerableExpression ApplyPredicate(SqlExpression sqlExpression) { - if (sqlExpression is SqlConstantExpression sqlConstant - && sqlConstant.Value is bool boolValue - && boolValue) + if (sqlExpression is SqlConstantExpression { Value: true }) { return this; } diff --git a/src/EFCore.Relational/Query/IAggregateMethodCallTranslator.cs b/src/EFCore.Relational/Query/IAggregateMethodCallTranslator.cs index 58d7f8b8334..2d4ed30e3fb 100644 --- a/src/EFCore.Relational/Query/IAggregateMethodCallTranslator.cs +++ b/src/EFCore.Relational/Query/IAggregateMethodCallTranslator.cs @@ -7,7 +7,7 @@ namespace Microsoft.EntityFrameworkCore.Query; /// /// -/// A SQL translator for LINQ expression represending an aggregate function. +/// A SQL translator for LINQ expression representing an aggregate function. /// /// /// This interface is typically used by database providers (and other extensions). It is generally diff --git a/src/EFCore.Relational/Query/Internal/CollateTranslator.cs b/src/EFCore.Relational/Query/Internal/CollateTranslator.cs index eeef6da8c31..faebaa9af3e 100644 --- a/src/EFCore.Relational/Query/Internal/CollateTranslator.cs +++ b/src/EFCore.Relational/Query/Internal/CollateTranslator.cs @@ -29,8 +29,7 @@ private static readonly MethodInfo MethodInfo IDiagnosticsLogger logger) => method.IsGenericMethod && Equals(method.GetGenericMethodDefinition(), MethodInfo) - && arguments[2] is SqlConstantExpression constantExpression - && constantExpression.Value is string collation + && arguments[2] is SqlConstantExpression { Value: string collation } ? new CollateExpression(arguments[1], collation) : null; } diff --git a/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs b/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs index 43d562142cd..3406c8fd24a 100644 --- a/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs +++ b/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs @@ -83,8 +83,7 @@ private static bool ValidateValues(SqlExpression values) => values is SqlConstantExpression or SqlParameterExpression; private static SqlExpression RemoveObjectConvert(SqlExpression expression) - => expression is SqlUnaryExpression sqlUnaryExpression - && sqlUnaryExpression.OperatorType == ExpressionType.Convert + => expression is SqlUnaryExpression { OperatorType: ExpressionType.Convert } sqlUnaryExpression && sqlUnaryExpression.Type == typeof(object) ? sqlUnaryExpression.Operand : expression; diff --git a/src/EFCore.Relational/Query/Internal/FromSqlParameterExpandingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/FromSqlParameterExpandingExpressionVisitor.cs index f95c11ea530..182b1d54c55 100644 --- a/src/EFCore.Relational/Query/Internal/FromSqlParameterExpandingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/FromSqlParameterExpandingExpressionVisitor.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; using Microsoft.EntityFrameworkCore.Storage.Internal; diff --git a/src/EFCore.Relational/Query/Internal/GroupBySingleQueryingEnumerable.cs b/src/EFCore.Relational/Query/Internal/GroupBySingleQueryingEnumerable.cs index b28bc751315..9f3a5b593e3 100644 --- a/src/EFCore.Relational/Query/Internal/GroupBySingleQueryingEnumerable.cs +++ b/src/EFCore.Relational/Query/Internal/GroupBySingleQueryingEnumerable.cs @@ -201,7 +201,7 @@ public Enumerator(GroupBySingleQueryingEnumerable queryingEnumer public IGrouping Current { get; private set; } object IEnumerator.Current - => Current!; + => Current; public bool MoveNext() { diff --git a/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs index 8fc0de03231..4dd749c11e3 100644 --- a/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs @@ -140,7 +140,7 @@ public virtual Expression Translate(SelectExpression selectExpression, Expressio if (materializeCollectionNavigationExpression.Navigation.TargetEntityType.IsMappedToJson()) { var subquery = materializeCollectionNavigationExpression.Subquery; - if (subquery is MethodCallExpression methodCallSubquery && methodCallSubquery.Method.IsGenericMethod) + if (subquery is MethodCallExpression { Method.IsGenericMethod: true } methodCallSubquery) { // strip .Select(x => x) and .AsQueryable() from the JsonCollectionResultExpression if (methodCallSubquery.Method.GetGenericMethodDefinition() == QueryableMethods.Select @@ -507,9 +507,7 @@ protected override Expression VisitMemberInit(MemberInitExpression memberInitExp } newBindings[i] = VisitMemberBinding(memberInitExpression.Bindings[i]); - if (newBindings[i] is MemberAssignment memberAssignment - && memberAssignment.Expression is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Convert + if (newBindings[i] is MemberAssignment { Expression: UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression } && unaryExpression.Operand == QueryCompilationContext.NotTranslatedExpression) { return QueryCompilationContext.NotTranslatedExpression; diff --git a/src/EFCore.Relational/Query/Internal/SelectExpressionProjectionApplyingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/SelectExpressionProjectionApplyingExpressionVisitor.cs index fb9496b2867..540cd18cd05 100644 --- a/src/EFCore.Relational/Query/Internal/SelectExpressionProjectionApplyingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/SelectExpressionProjectionApplyingExpressionVisitor.cs @@ -35,12 +35,13 @@ public SelectExpressionProjectionApplyingExpressionVisitor(QuerySplittingBehavio protected override Expression VisitExtension(Expression extensionExpression) => extensionExpression switch { - ShapedQueryExpression shapedQueryExpression - when shapedQueryExpression.QueryExpression is SelectExpression selectExpression + ShapedQueryExpression { QueryExpression: SelectExpression selectExpression } shapedQueryExpression => shapedQueryExpression.UpdateShaperExpression( selectExpression.ApplyProjection( shapedQueryExpression.ShaperExpression, shapedQueryExpression.ResultCardinality, _querySplittingBehavior)), + NonQueryExpression nonQueryExpression => nonQueryExpression, + _ => base.VisitExtension(extensionExpression), }; } diff --git a/src/EFCore.Relational/Query/Internal/SqlExpressionSimplifyingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/SqlExpressionSimplifyingExpressionVisitor.cs index 619a42985f2..f9c20410d79 100644 --- a/src/EFCore.Relational/Query/Internal/SqlExpressionSimplifyingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/SqlExpressionSimplifyingExpressionVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections; using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; diff --git a/src/EFCore.Relational/Query/JsonQueryExpression.cs b/src/EFCore.Relational/Query/JsonQueryExpression.cs index 83ce3639f27..2e22dccab20 100644 --- a/src/EFCore.Relational/Query/JsonQueryExpression.cs +++ b/src/EFCore.Relational/Query/JsonQueryExpression.cs @@ -69,7 +69,7 @@ private JsonQueryExpression( public virtual IEntityType EntityType { get; } /// - /// The column containg JSON value. + /// The column containing JSON value. /// public virtual ColumnExpression JsonColumn { get; } diff --git a/src/EFCore.Relational/Query/QuerySqlGenerator.cs b/src/EFCore.Relational/Query/QuerySqlGenerator.cs index 80fdc22a2b5..839822be9dd 100644 --- a/src/EFCore.Relational/Query/QuerySqlGenerator.cs +++ b/src/EFCore.Relational/Query/QuerySqlGenerator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Runtime.CompilerServices; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; using Microsoft.EntityFrameworkCore.Storage.Internal; @@ -169,15 +168,17 @@ protected override Expression VisitSqlFragment(SqlFragmentExpression sqlFragment } private static bool IsNonComposedSetOperation(SelectExpression selectExpression) - => selectExpression.Offset == null - && selectExpression.Limit == null - && !selectExpression.IsDistinct - && selectExpression.Predicate == null - && selectExpression.Having == null - && selectExpression.Orderings.Count == 0 - && selectExpression.GroupBy.Count == 0 - && selectExpression.Tables.Count == 1 - && selectExpression.Tables[0] is SetOperationBase setOperation + => selectExpression is + { + Tables: [SetOperationBase setOperation], + Predicate: null, + Orderings: [], + Offset: null, + Limit: null, + IsDistinct: false, + Having: null, + GroupBy: [] + } && selectExpression.Projection.Count == setOperation.Source1.Projection.Count && selectExpression.Projection.Select( (pe, index) => pe.Expression is ColumnExpression column @@ -344,9 +345,7 @@ protected virtual void GeneratePseudoFromClause() /// /// SelectExpression for which the empty projection will be generated. protected virtual void GenerateEmptyProjection(SelectExpression selectExpression) - { - _relationalCommandBuilder.Append("1"); - } + => _relationalCommandBuilder.Append("1"); /// protected override Expression VisitProjection(ProjectionExpression projectionExpression) @@ -1554,7 +1553,7 @@ protected virtual bool RequiresParentheses(SqlExpression outerExpression, SqlExp // If both operators have the same precedence, add parentheses unless they're the same operator, and // that operator is associative (e.g. a + b + c) - 0 => outerExpression is not SqlBinaryExpression outerBinary + _ => outerExpression is not SqlBinaryExpression outerBinary || outerBinary.OperatorType != innerBinaryExpression.OperatorType || !isOuterAssociative // Arithmetic operators on floating points aren't associative, because of rounding errors. diff --git a/src/EFCore.Relational/Query/RelationalAggregateMethodCallTranslatorProvider.cs b/src/EFCore.Relational/Query/RelationalAggregateMethodCallTranslatorProvider.cs index 8d1af458b3e..dd57784fb91 100644 --- a/src/EFCore.Relational/Query/RelationalAggregateMethodCallTranslatorProvider.cs +++ b/src/EFCore.Relational/Query/RelationalAggregateMethodCallTranslatorProvider.cs @@ -11,7 +11,6 @@ public class RelationalAggregateMethodCallTranslatorProvider : IAggregateMethodC { private readonly List _plugins = new(); private readonly List _translators = new(); - private readonly ISqlExpressionFactory _sqlExpressionFactory; /// /// Creates a new instance of the class. @@ -23,10 +22,10 @@ public RelationalAggregateMethodCallTranslatorProvider(RelationalAggregateMethod _plugins.AddRange(dependencies.Plugins.SelectMany(p => p.Translators)); - _sqlExpressionFactory = dependencies.SqlExpressionFactory; + var sqlExpressionFactory = dependencies.SqlExpressionFactory; _translators.AddRange( - new IAggregateMethodCallTranslator[] { new QueryableAggregateMethodTranslator(_sqlExpressionFactory) }); + new IAggregateMethodCallTranslator[] { new QueryableAggregateMethodTranslator(sqlExpressionFactory) }); } /// diff --git a/src/EFCore.Relational/Query/RelationalEntityShaperExpression.cs b/src/EFCore.Relational/Query/RelationalEntityShaperExpression.cs index 34f4aa724c8..c65a5537345 100644 --- a/src/EFCore.Relational/Query/RelationalEntityShaperExpression.cs +++ b/src/EFCore.Relational/Query/RelationalEntityShaperExpression.cs @@ -111,7 +111,7 @@ protected override LambdaExpression GenerateMaterializationCondition(IEntityType p => NotEqual( valueBufferParameter.CreateValueBufferReadValueExpression(typeof(object), p.GetIndex(), p), Constant(null))) - .Aggregate((a, b) => AndAlso(a, b)); + .Aggregate(AndAlso); } var allNonPrincipalSharedNonPkProperties = entityType.GetNonPrincipalSharedNonPkProperties(table); @@ -124,7 +124,7 @@ protected override LambdaExpression GenerateMaterializationCondition(IEntityType p => NotEqual( valueBufferParameter.CreateValueBufferReadValueExpression(typeof(object), p.GetIndex(), p), Constant(null))) - .Aggregate((a, b) => OrElse(a, b)); + .Aggregate(OrElse); condition = condition == null ? atLeastOneNonNullValueInNullablePropertyCondition diff --git a/src/EFCore.Relational/Query/RelationalGroupByResultExpression.cs b/src/EFCore.Relational/Query/RelationalGroupByResultExpression.cs index b64ede9a714..d372d6ae175 100644 --- a/src/EFCore.Relational/Query/RelationalGroupByResultExpression.cs +++ b/src/EFCore.Relational/Query/RelationalGroupByResultExpression.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Metadata.Internal; - namespace Microsoft.EntityFrameworkCore.Query; /// @@ -67,11 +65,11 @@ public sealed override ExpressionType NodeType /// protected override Expression VisitChildren(ExpressionVisitor visitor) { - var keyIdentifer = visitor.Visit(KeyIdentifier); + var keyIdentifier = visitor.Visit(KeyIdentifier); var keyShaper = visitor.Visit(KeyShaper); var elementShaper = visitor.Visit(ElementShaper); - return Update(keyIdentifer, keyShaper, elementShaper); + return Update(keyIdentifier, keyShaper, elementShaper); } /// diff --git a/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessor.cs b/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessor.cs index 14f598e221f..dc0df133a80 100644 --- a/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessor.cs +++ b/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessor.cs @@ -8,7 +8,7 @@ namespace Microsoft.EntityFrameworkCore.Query; /// /// -/// A class that processes the query expression after parementer values are known. +/// A class that processes the query expression after parameter values are known. /// /// /// This type is typically used by database providers (and other extensions). It is generally @@ -53,8 +53,8 @@ public virtual Expression Optimize( out bool canCache) { canCache = true; - queryExpression = ProcessSqlNullability(queryExpression, parametersValues, out var sqlNullablityCanCache); - canCache &= sqlNullablityCanCache; + queryExpression = ProcessSqlNullability(queryExpression, parametersValues, out var sqlNullabilityCanCache); + canCache &= sqlNullabilityCanCache; queryExpression = ExpandFromSqlParameter(queryExpression, parametersValues, out var fromSqlParameterCanCache); canCache &= fromSqlParameterCanCache; diff --git a/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessorDependencies.cs b/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessorDependencies.cs index f166e9288f5..0e2bb22144c 100644 --- a/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessorDependencies.cs +++ b/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessorDependencies.cs @@ -63,7 +63,7 @@ public RelationalParameterBasedSqlProcessorDependencies( public ISqlExpressionFactory SqlExpressionFactory { get; init; } /// - /// Relational type mapping souce. + /// Relational type mapping source. /// public IRelationalTypeMappingSource TypeMappingSource { get; init; } diff --git a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs index 93793864ab6..bc8643d363d 100644 --- a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; -using System.Reflection.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; @@ -839,8 +838,7 @@ private SqlExpression CreateJoinPredicate( var outerKey = RemapLambdaBody(outer, outerKeySelector); var innerKey = RemapLambdaBody(inner, innerKeySelector); - if (outerKey is NewExpression outerNew - && outerNew.Arguments.Count > 0) + if (outerKey is NewExpression { Arguments.Count: > 0 } outerNew) { var innerNew = (NewExpression)innerKey; @@ -937,9 +935,7 @@ private SqlExpression CreateJoinPredicate(Expression outerKey, Expression innerK } var selectExpression = (SelectExpression)source.QueryExpression; - if (!(translation is SqlConstantExpression sqlConstantExpression - && sqlConstantExpression.Value is bool constantValue - && constantValue)) + if (translation is not SqlConstantExpression { Value: true }) { selectExpression.ApplyPredicate(translation); } @@ -1075,7 +1071,7 @@ private sealed class CorrelationFindingExpressionVisitor : ExpressionVisitor public (LambdaExpression, bool, bool) IsCorrelated(LambdaExpression lambdaExpression) { Check.DebugAssert( - lambdaExpression.Parameters.Count == 1, "Multiparameter lambda passed to CorrelationFindingExpressionVisitor"); + lambdaExpression.Parameters.Count == 1, "Multi-parameter lambda passed to CorrelationFindingExpressionVisitor"); _correlated = false; _defaultIfEmpty = false; @@ -1330,9 +1326,8 @@ static bool AreOtherNonOwnedEntityTypesInTheTable(IEntityType rootType, ITableBa var clrType = entityType.ClrType; var entityParameter = Expression.Parameter(clrType); - Expression predicateBody; var innerParameter = Expression.Parameter(clrType); - predicateBody = Expression.Call( + var predicateBody = Expression.Call( QueryableMethods.AnyWithPredicate.MakeGenericMethod(clrType), source, Expression.Quote( @@ -1690,15 +1685,17 @@ protected virtual bool IsValidSelectExpressionForExecuteDelete( EntityShaperExpression entityShaperExpression, [NotNullWhen(true)] out TableExpression? tableExpression) { - if (selectExpression.Offset == null - && selectExpression.Limit == null + if (selectExpression is + { + Tables: [TableExpression expression], + Orderings: [], + Offset: null, + Limit: null, + GroupBy: [], + Having: null + } // If entity type has primary key then Distinct is no-op - && (!selectExpression.IsDistinct || entityShaperExpression.EntityType.FindPrimaryKey() != null) - && selectExpression.GroupBy.Count == 0 - && selectExpression.Having == null - && selectExpression.Orderings.Count == 0 - && selectExpression.Tables.Count == 1 - && selectExpression.Tables[0] is TableExpression expression) + && (!selectExpression.IsDistinct || entityShaperExpression.EntityType.FindPrimaryKey() != null)) { tableExpression = expression; @@ -1714,7 +1711,7 @@ protected virtual bool IsValidSelectExpressionForExecuteDelete( /// /// /// - /// By default, only muli-table select expressions are supported, and optionally with a predicate. + /// By default, only multi-table select expressions are supported, and optionally with a predicate. /// /// /// Providers can override this to allow more select expression features to be supported without pushing down into a subquery. @@ -2183,7 +2180,7 @@ outerKey is NewArrayExpression newArrayExpression return Expression.NotEqual(left, Expression.Constant(null, left.Type)); }) - .Aggregate((l, r) => Expression.AndAlso(l, r)) + .Aggregate(Expression.AndAlso) : Expression.NotEqual(outerKey, Expression.Constant(null, outerKey.Type)), keyComparison) : keyComparison; @@ -2214,8 +2211,7 @@ static TableExpressionBase FindRootTableExpressionForColumn(ColumnExpression col if (table is SelectExpression selectExpression) { - var matchingProjection = - (ColumnExpression)selectExpression.Projection.Where(p => p.Alias == column.Name).Single().Expression; + var matchingProjection = (ColumnExpression)selectExpression.Projection.Single(p => p.Alias == column.Name).Expression; return FindRootTableExpressionForColumn(matchingProjection); } @@ -2426,8 +2422,7 @@ private static Expression MatchShaperNullabilityForSetOperation(Expression shape || selectorLambda.Body == selectorLambda.Parameters[0]) { var shaperExpression = source.ShaperExpression; - if (shaperExpression is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Convert) + if (shaperExpression is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression) { shaperExpression = unaryExpression.Operand; } @@ -2742,7 +2737,7 @@ protected class RelationalInferredTypeMappingApplier : ExpressionVisitor /// /// The inferred type mappings to be applied back on their query roots. /// - private IReadOnlyDictionary<(TableExpressionBase Table, string ColumnName), RelationalTypeMapping?> _inferredTypeMappings; + private readonly IReadOnlyDictionary<(TableExpressionBase Table, string ColumnName), RelationalTypeMapping?> _inferredTypeMappings; /// /// Creates a new instance of the class. diff --git a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitorDependencies.cs b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitorDependencies.cs index 13b5d846c06..8fe8614b0b8 100644 --- a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitorDependencies.cs +++ b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitorDependencies.cs @@ -68,7 +68,7 @@ public RelationalQueryableMethodTranslatingExpressionVisitorDependencies( public ISqlExpressionFactory SqlExpressionFactory { get; init; } /// - /// The relational type mapping souce. + /// The relational type mapping source. /// public IRelationalTypeMappingSource TypeMappingSource { get; init; } diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.ClientMethods.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.ClientMethods.cs index 61881d4773c..ae0d31e4760 100644 --- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.ClientMethods.cs +++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.ClientMethods.cs @@ -159,8 +159,7 @@ private static void IncludeReference if (relatedEntity != null) { fixup(includingEntity, relatedEntity); - if (inverseNavigation != null - && !inverseNavigation.IsCollection) + if (inverseNavigation is { IsCollection: false }) { inverseNavigation.SetIsLoadedWhenNoTracking(relatedEntity); } @@ -306,8 +305,7 @@ void ProcessCurrentElementRow() if (!trackingQuery) { fixup(entity, relatedEntity); - if (inverseNavigation != null - && !inverseNavigation.IsCollection) + if (inverseNavigation is { IsCollection: false }) { inverseNavigation.SetIsLoadedWhenNoTracking(relatedEntity); } diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs index beeeb9f2f9a..cf7b0db7750 100644 --- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using System.Text.Json; -using System.Text.Json.Nodes; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; @@ -128,13 +125,13 @@ private static readonly MethodInfo ArrayCopyMethodInfo /// Cache for the JsonElement values we have generated - storing variables that the JsonElements are assigned to /// private readonly Dictionary<(int JsonColumnIndex, (string? JsonPropertyName, int? ConstantArrayIndex, int? NonConstantArrayIndex)[] AdditionalPath), ParameterExpression> _existingJsonElementMap - = new(new ExisitingJsonElementMapKeyComparer()); + = new(new ExistingJsonElementMapKeyComparer()); /// /// Cache for the key values we have generated - storing variables that the keys are assigned to /// private readonly Dictionary<(int JsonColumnIndex, (int? ConstantArrayIndex, int? NonConstantArrayIndex)[] AdditionalPath), ParameterExpression> _existingKeyValuesMap - = new(new ExisitingJsonKeyValuesMapKeyComparer()); + = new(new ExistingJsonKeyValuesMapKeyComparer()); /// /// Map between index of the non-constant json array element access @@ -408,8 +405,7 @@ public LambdaExpression ProcessShaper( protected override Expression VisitBinary(BinaryExpression binaryExpression) { - if (binaryExpression.NodeType == ExpressionType.Assign - && binaryExpression.Left is ParameterExpression parameterExpression + if (binaryExpression is { NodeType: ExpressionType.Assign, Left: ParameterExpression parameterExpression } && parameterExpression.Type == typeof(MaterializationContext)) { var newExpression = (NewExpression)binaryExpression.Right; @@ -444,10 +440,11 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) } } - if (binaryExpression.NodeType == ExpressionType.Assign - && binaryExpression.Left is MemberExpression memberExpression - && memberExpression.Member is FieldInfo fieldInfo - && fieldInfo.IsInitOnly) + if (binaryExpression is + { + NodeType: ExpressionType.Assign, + Left: MemberExpression { Member: FieldInfo { IsInitOnly: true } } memberExpression + }) { return memberExpression.Assign(Visit(binaryExpression.Right)); } @@ -547,9 +544,8 @@ protected override Expression VisitExtension(Expression extensionExpression) return entityMaterializationExpression; } - case CollectionResultExpression collectionResultExpression - when collectionResultExpression.Navigation is INavigation navigation - && GetProjectionIndex(collectionResultExpression.ProjectionBindingExpression) + case CollectionResultExpression { Navigation: INavigation navigation } collectionResultExpression + when GetProjectionIndex(collectionResultExpression.ProjectionBindingExpression) is JsonProjectionInfo jsonProjectionInfo: { // json entity collection at the root @@ -1429,7 +1425,6 @@ private Expression CreateJsonShapers( // create JsonElement for the additional path segment var currentPath = jsonProjectionInfo.AdditionalPath[index - 1]; - Expression jsonElementAccessExpressionFragment; if (currentPath.JsonPropertyName is string stringPath) { // JsonElement? jsonElement = (...) <- this is the previous one @@ -1475,7 +1470,7 @@ private Expression CreateJsonShapers( ExtractAndCacheNonConstantJsonArrayElementAccessValue(currentPath.NonConstantArrayIndex!.Value), typeof(int)); - jsonElementAccessExpressionFragment = Expression.Call( + Expression jsonElementAccessExpressionFragment = Expression.Call( Expression.MakeMemberAccess( currentJsonElementVariable!, NullableJsonElementValuePropertyInfo), @@ -1893,7 +1888,7 @@ public bool ContainsCollectionMaterialization(Expression expression) } } - private sealed class ExisitingJsonElementMapKeyComparer + private sealed class ExistingJsonElementMapKeyComparer : IEqualityComparer<(int JsonColumnIndex, (string? JsonPropertyName, int? ConstantArrayIndex, int? NonConstantArrayIndex)[] AdditionalPath)> { public bool Equals( @@ -1907,7 +1902,7 @@ public int GetHashCode([DisallowNull] (int JsonColumnIndex, (string? JsonPropert => HashCode.Combine(obj.JsonColumnIndex, obj.AdditionalPath?.Length); } - private sealed class ExisitingJsonKeyValuesMapKeyComparer + private sealed class ExistingJsonKeyValuesMapKeyComparer : IEqualityComparer<(int JsonColumnIndex, (int? ConstantArrayIndex, int? NonConstantArrayIndex)[] AdditionalPath)> { public bool Equals( diff --git a/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs index eb1cea178f8..b59f8f1eae0 100644 --- a/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs @@ -3,7 +3,6 @@ using System.Collections; using System.Diagnostics.CodeAnalysis; -using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; @@ -294,8 +293,7 @@ protected virtual void AddTranslationErrorDetails(string details) protected override Expression VisitBinary(BinaryExpression binaryExpression) { if (binaryExpression.Left.Type == typeof(object[]) - && binaryExpression.Left is NewArrayExpression - && binaryExpression.NodeType == ExpressionType.Equal) + && binaryExpression is { Left: NewArrayExpression, NodeType: ExpressionType.Equal }) { return Visit(ConvertObjectArrayEqualityComparison(binaryExpression.Left, binaryExpression.Right)); } @@ -642,8 +640,7 @@ protected override Expression VisitExtension(Expression extensionExpression) var innerExpression = shaperExpression; Type? convertedType = null; - if (shaperExpression is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Convert) + if (shaperExpression is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression) { convertedType = unaryExpression.Type; innerExpression = unaryExpression.Operand; @@ -664,11 +661,10 @@ protected override Expression VisitExtension(Expression extensionExpression) } if (mappedProjectionBindingExpression == null - && shaperExpression is BlockExpression blockExpression - && blockExpression.Expressions.Count == 2 - && blockExpression.Expressions[0] is BinaryExpression binaryExpression - && binaryExpression.NodeType == ExpressionType.Assign - && binaryExpression.Right is ProjectionBindingExpression pbe2) + && shaperExpression is BlockExpression + { + Expressions: [BinaryExpression { NodeType: ExpressionType.Assign, Right: ProjectionBindingExpression pbe2 }, _] + }) { mappedProjectionBindingExpression = pbe2; } @@ -1407,9 +1403,7 @@ private bool TryTranslateAsEnumerableExpression( return true; } - if (expression is MethodCallExpression methodCallExpression - && methodCallExpression.Method.IsStatic - && methodCallExpression.Arguments.Count > 0 + if (expression is MethodCallExpression { Method.IsStatic: true, Arguments.Count: > 0 } methodCallExpression && methodCallExpression.Method.DeclaringType == typeof(Queryable)) { var genericMethod = methodCallExpression.Method.IsGenericMethod @@ -1577,7 +1571,7 @@ private static Expression ConvertObjectArrayEqualityComparison(Expression left, return leftExpressions.Zip( rightExpressions, (l, r) => Infrastructure.ExpressionExtensions.CreateEqualsExpression(l, r)) - .Aggregate((a, b) => Expression.AndAlso(a, b)); + .Aggregate(Expression.AndAlso); } private static bool TryEvaluateToConstant(Expression expression, [NotNullWhen(true)] out SqlConstantExpression? sqlConstantExpression) @@ -1891,7 +1885,7 @@ private static bool CanEvaluate(Expression expression) }; private static bool IsNullSqlConstantExpression(Expression expression) - => expression is SqlConstantExpression sqlConstant && sqlConstant.Value == null; + => expression is SqlConstantExpression { Value: null } sqlConstant; [DebuggerStepThrough] private static bool TranslationFailed(Expression? original, Expression? translation, out SqlExpression? castTranslation) diff --git a/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitorDependencies.cs b/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitorDependencies.cs index 79511964063..144881f451c 100644 --- a/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitorDependencies.cs +++ b/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitorDependencies.cs @@ -72,7 +72,7 @@ public RelationalSqlTranslatingExpressionVisitorDependencies( public IModel Model { get; init; } /// - /// The relational type mapping souce. + /// The relational type mapping source. /// public IRelationalTypeMappingSource TypeMappingSource { get; init; } diff --git a/src/EFCore.Relational/Query/SqlExpressionFactory.cs b/src/EFCore.Relational/Query/SqlExpressionFactory.cs index 552e17a99f6..ad8ff2f1f93 100644 --- a/src/EFCore.Relational/Query/SqlExpressionFactory.cs +++ b/src/EFCore.Relational/Query/SqlExpressionFactory.cs @@ -32,15 +32,13 @@ public SqlExpressionFactory(SqlExpressionFactoryDependencies dependencies) /// [return: NotNullIfNotNull("sqlExpression")] public virtual SqlExpression? ApplyDefaultTypeMapping(SqlExpression? sqlExpression) - => sqlExpression == null - || sqlExpression.TypeMapping != null - ? sqlExpression - : sqlExpression is SqlUnaryExpression sqlUnaryExpression - && sqlUnaryExpression.OperatorType == ExpressionType.Convert - && sqlUnaryExpression.Type == typeof(object) - ? sqlUnaryExpression.Operand - : ApplyTypeMapping( - sqlExpression, _typeMappingSource.FindMapping(sqlExpression.Type, Dependencies.Model)); + => sqlExpression is not { TypeMapping: null } + ? sqlExpression + : sqlExpression is SqlUnaryExpression { OperatorType: ExpressionType.Convert } sqlUnaryExpression + && sqlUnaryExpression.Type == typeof(object) + ? sqlUnaryExpression.Operand + : ApplyTypeMapping( + sqlExpression, _typeMappingSource.FindMapping(sqlExpression.Type, Dependencies.Model)); /// [return: NotNullIfNotNull("sqlExpression")] @@ -740,7 +738,7 @@ private void AddConditions(SelectExpression selectExpression, IEntityType entity if (requiredNonPkProperties.Count > 0) { predicate = requiredNonPkProperties.Select(e => IsNotNull(e, entityProjectionExpression)) - .Aggregate((l, r) => AndAlso(l, r)); + .Aggregate(AndAlso); } var allNonSharedNonPkProperties = entityType.GetNonPrincipalSharedNonPkProperties(table); @@ -750,7 +748,7 @@ private void AddConditions(SelectExpression selectExpression, IEntityType entity { var atLeastOneNonNullValueInNullablePropertyCondition = allNonSharedNonPkProperties .Select(e => IsNotNull(e, entityProjectionExpression)) - .Aggregate((a, b) => OrElse(a, b)); + .Aggregate(OrElse); predicate = predicate == null ? atLeastOneNonNullValueInNullablePropertyCondition diff --git a/src/EFCore.Relational/Query/SqlExpressions/RowValueExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/RowValueExpression.cs index 5d9edb92792..083e2d7bfa9 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/RowValueExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/RowValueExpression.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Data; -using System.Runtime.CompilerServices; - namespace Microsoft.EntityFrameworkCore.Query.SqlExpressions; /// diff --git a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.Helper.cs b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.Helper.cs index b0c22b4214d..74870389a66 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.Helper.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.Helper.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; -using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.Query.SqlExpressions; @@ -407,7 +406,7 @@ public AliasUniquifier(HashSet usedAliases) // SELECT * FROM EntityOne as e // OUTER APPLY ( // SELECT * FROM EntityTwo as e1 - // LEFT JOIN EntityThree as e ON (...) -- reuse alias e, since we use e1 after uniqification + // LEFT JOIN EntityThree as e ON (...) -- reuse alias e, since we use e1 after uniquification // WHERE e.Foo == e1.Bar -- ambiguity! e could refer to EntityOne or EntityThree // ) as t innerSelectExpression._usedAliases.Add(newAlias); @@ -917,7 +916,7 @@ public SelectExpressionVerifyingExpressionVisitor(IEnumerable tableReferencesInScope) + private static void Verify(Expression expression, IEnumerable tableReferencesInScope) => new SelectExpressionVerifyingExpressionVisitor(tableReferencesInScope) .Visit(expression); } @@ -950,12 +949,12 @@ private sealed class CloningExpressionVisitor : ExpressionVisitor var newTableReferences = selectExpression._tableReferences .Select(e => new TableReferenceExpression(selectExpression, e.Alias)).ToList(); Check.DebugAssert( - newTables.Select(e => GetAliasFromTableExpressionBase(e)).SequenceEqual(newTableReferences.Select(e => e.Alias)), + newTables.Select(GetAliasFromTableExpressionBase).SequenceEqual(newTableReferences.Select(e => e.Alias)), "Alias of updated tables must match the old tables."); var predicate = (SqlExpression?)Visit(selectExpression.Predicate); var newGroupBy = selectExpression._groupBy.Select(Visit) - .Where(e => !(e is SqlConstantExpression || e is SqlParameterExpression)) + .Where(e => e is not (SqlConstantExpression or SqlParameterExpression)) .ToList(); var havingExpression = (SqlExpression?)Visit(selectExpression.Having); var newOrderings = selectExpression._orderings.Select(Visit).ToList(); @@ -974,8 +973,8 @@ private sealed class CloningExpressionVisitor : ExpressionVisitor Tags = selectExpression.Tags, _usedAliases = selectExpression._usedAliases.ToHashSet(), _projectionMapping = newProjectionMappings, + _mutable = selectExpression._mutable }; - newSelectExpression._mutable = selectExpression._mutable; newSelectExpression._removableJoinTables.AddRange(selectExpression._removableJoinTables); @@ -1098,20 +1097,22 @@ public TpcTableExpressionRemovingExpressionVisitor(HashSet usedAliases) [return: NotNullIfNotNull("expression")] public override Expression? Visit(Expression? expression) { - if (expression is SelectExpression selectExpression - && selectExpression._tpcDiscriminatorValues.Count > 0) + if (expression is SelectExpression { _tpcDiscriminatorValues.Count: > 0 } selectExpression) { // If selectExpression doesn't have any other component and only TPC tables then we can lift it // We ignore projection here because if this selectExpression has projection from inner TPC // Then TPC will have superset of projection - var identitySelect = selectExpression.Offset == null - && selectExpression.Limit == null - && !selectExpression.IsDistinct - && selectExpression.Predicate == null - && selectExpression.Having == null - && selectExpression.Orderings.Count == 0 - && selectExpression.GroupBy.Count == 0 - && selectExpression.Tables.Count == 1 + var identitySelect = selectExpression is + { + Tables.Count: 1, + Predicate: null, + Orderings: [], + Limit: null, + Offset: null, + IsDistinct: false, + GroupBy: [], + Having: null + } // Any non-column projection means some composition which cannot be removed && selectExpression.Projection.All(e => e.Expression is ColumnExpression); @@ -1119,7 +1120,7 @@ public TpcTableExpressionRemovingExpressionVisitor(HashSet usedAliases) { var tpcTablesExpression = kvp.Key; var subSelectExpressions = tpcTablesExpression.Prune(kvp.Value.Item2).SelectExpressions - .Select(e => AssignUniqueAliasToTable(e)).ToList(); + .Select(AssignUniqueAliasToTable).ToList(); var firstSelectExpression = subSelectExpressions[0]; // There will be at least one. int[]? reindexingMap = null; diff --git a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs index 6d8fa3e72ad..b5e0b717286 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using System.Runtime.CompilerServices; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Query.Internal; @@ -60,7 +59,7 @@ public sealed partial class SelectExpression : TableExpressionBase private SortedDictionary? _annotations; - // We need to remember identfiers before GroupBy in case it is final GroupBy and element selector has a colection + // We need to remember identifiers before GroupBy in case it is final GroupBy and element selector has a collection // This state doesn't need to propagate // It should be only at top-level otherwise GroupBy won't be final operator. // Cloning skips it altogether (we don't clone top level with GroupBy) @@ -180,8 +179,9 @@ internal SelectExpression(IEntityType entityType, ISqlExpressionFactory sqlExpre var innerColumns = keyProperties.Select( p => CreateColumnExpression(p, table, tableReferenceExpression, nullable: false)); - var joinPredicate = joinColumns.Zip(innerColumns, (l, r) => sqlExpressionFactory.Equal(l, r)) - .Aggregate((l, r) => sqlExpressionFactory.AndAlso(l, r)); + var joinPredicate = joinColumns + .Zip(innerColumns, sqlExpressionFactory.Equal) + .Aggregate(sqlExpressionFactory.AndAlso); var joinExpression = new InnerJoinExpression(tableExpression, joinPredicate); AddTable(joinExpression, tableReferenceExpression); @@ -211,8 +211,9 @@ internal SelectExpression(IEntityType entityType, ISqlExpressionFactory sqlExpre sqlExpressionFactory.Constant(derivedType.ShortName()))); } - var joinPredicate = joinColumns.Zip(keyColumns, (l, r) => sqlExpressionFactory.Equal(l, r)) - .Aggregate((l, r) => sqlExpressionFactory.AndAlso(l, r)); + var joinPredicate = joinColumns + .Zip(keyColumns, sqlExpressionFactory.Equal) + .Aggregate(sqlExpressionFactory.AndAlso); var joinExpression = new LeftJoinExpression(tableExpression, joinPredicate); _removableJoinTables.Add(_tables.Count); @@ -240,7 +241,7 @@ internal SelectExpression(IEntityType entityType, ISqlExpressionFactory sqlExpre var table = entityTypes[0].GetViewOrTableMappings().Single().Table; var tableExpression = new TableExpression(table); - var tableReferenceExpression = new TableReferenceExpression(this, tableExpression.Alias!); + var tableReferenceExpression = new TableReferenceExpression(this, tableExpression.Alias); AddTable(tableExpression, tableReferenceExpression); var propertyExpressions = new Dictionary(); @@ -415,8 +416,9 @@ internal SelectExpression(IEntityType entityType, ISqlExpressionFactory sqlExpre var innerColumns = keyProperties.Select( p => CreateColumnExpression(p, table, tableReferenceExpression, nullable: false)); - var joinPredicate = joinColumns.Zip(innerColumns, (l, r) => sqlExpressionFactory.Equal(l, r)) - .Aggregate((l, r) => sqlExpressionFactory.AndAlso(l, r)); + var joinPredicate = joinColumns + .Zip(innerColumns, sqlExpressionFactory.Equal) + .Aggregate(sqlExpressionFactory.AndAlso); var joinExpression = new InnerJoinExpression(tableExpression, joinPredicate); _removableJoinTables.Add(_tables.Count); @@ -630,7 +632,7 @@ public void ApplyTags(ISet tags) public void ApplyDistinct() { if (_clientProjections.Count > 0 - && _clientProjections.Any(e => e is ShapedQueryExpression sqe && sqe.ResultCardinality == ResultCardinality.Enumerable)) + && _clientProjections.Any(e => e is ShapedQueryExpression { ResultCardinality: ResultCardinality.Enumerable } sqe)) { throw new InvalidOperationException(RelationalStrings.DistinctOnCollectionNotSupported); } @@ -867,7 +869,7 @@ public Expression ApplyProjection( || (querySplittingBehavior == QuerySplittingBehavior.SingleQuery && containsCollection)) { // Pushdown outer since we will be adding join to this - // For grouping query pushown will not occur since we don't allow this terms to compose (yet!). + // For grouping query pushdown will not occur since we don't allow this terms to compose (yet!). if (Limit != null || Offset != null || IsDistinct @@ -971,8 +973,10 @@ Expression AddGroupByKeySelectorToProjection( AddGroupByKeySelectorToProjection( selectExpression, clientProjectionList, projectionBindingMap, unaryExpression.Operand)); - case EntityShaperExpression entityShaperExpression - when entityShaperExpression.ValueBufferExpression is EntityProjectionExpression entityProjectionExpression: + case EntityShaperExpression + { + ValueBufferExpression: EntityProjectionExpression entityProjectionExpression + } entityShaperExpression: { var clientProjectionToAdd = AddEntityProjection(entityProjectionExpression); var existingIndex = clientProjectionList.FindIndex( @@ -1003,7 +1007,7 @@ Expression AddGroupByKeySelectorToProjection( var comparers = new List(); foreach (var (column, comparer) in identifyingProjection) { - if (!projectionBindingMap.TryGetValue(column, out var mappedExpresssion)) + if (!projectionBindingMap.TryGetValue(column, out var mappedExpression)) { var index = selectExpression.AddToProjection(column); var clientProjectionToAdd = Constant(index); @@ -1015,13 +1019,13 @@ Expression AddGroupByKeySelectorToProjection( existingIndex = clientProjectionList.Count - 1; } - mappedExpresssion = new ProjectionBindingExpression(selectExpression, existingIndex, column.Type.MakeNullable()); + mappedExpression = new ProjectionBindingExpression(selectExpression, existingIndex, column.Type.MakeNullable()); } updatedExpressions.Add( - mappedExpresssion.Type.IsValueType - ? Convert(mappedExpresssion, typeof(object)) - : mappedExpresssion); + mappedExpression.Type.IsValueType + ? Convert(mappedExpression, typeof(object)) + : mappedExpression); comparers.Add(comparer); } @@ -1054,9 +1058,7 @@ Expression AddGroupByKeySelectorToProjection( static void UpdateLimit(SelectExpression selectExpression) { - if (selectExpression.Limit is SqlConstantExpression limitConstantExpression - && limitConstantExpression.Value is int limitValue - && limitValue == 2) + if (selectExpression.Limit is SqlConstantExpression { Value: 2 } limitConstantExpression) { selectExpression.Limit = new SqlConstantExpression(Constant(1), limitConstantExpression.TypeMapping); } @@ -1132,8 +1134,7 @@ static void UpdateLimit(SelectExpression selectExpression) } var innerExpression = RemoveConvert(innerShaperExpression); - if (!(innerExpression is EntityShaperExpression - || innerExpression is IncludeExpression)) + if (innerExpression is not (EntityShaperExpression or IncludeExpression)) { var sentinelExpression = innerSelectExpression.Limit!; var sentinelNullableType = sentinelExpression.Type.MakeNullable(); @@ -1183,14 +1184,12 @@ static void UpdateLimit(SelectExpression selectExpression) break; static Expression RemoveConvert(Expression expression) - => expression is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Convert - ? RemoveConvert(unaryExpression.Operand) - : expression; + => expression is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression + ? RemoveConvert(unaryExpression.Operand) + : expression; } - case ShapedQueryExpression shapedQueryExpression - when shapedQueryExpression.ResultCardinality == ResultCardinality.Enumerable: + case ShapedQueryExpression { ResultCardinality: ResultCardinality.Enumerable } shapedQueryExpression: { var innerSelectExpression = (SelectExpression)shapedQueryExpression.QueryExpression; if (_identifier.Count == 0 @@ -1481,12 +1480,12 @@ void GetOrderingsFromInnerTable( TableReferenceExpression tableReferenceExpression, List orderings) { - // If operation was converted to predicate join (inner/left join), - // then ordering will be in rownumber expression - if (tableExpressionBase is SelectExpression joinedSubquery - && joinedSubquery.Predicate != null - && joinedSubquery.Tables.Count == 1 - && joinedSubquery.Tables[0] is SelectExpression rowNumberSubquery + // If operation was converted to predicate join (inner/left join), then ordering will be in a RowNumberExpression + if (tableExpressionBase is SelectExpression + { + Tables: [SelectExpression rowNumberSubquery], + Predicate: not null + } joinedSubquery && rowNumberSubquery.Projection.Select(pe => pe.Expression) .OfType().SingleOrDefault() is RowNumberExpression rowNumberExpression) { @@ -1512,8 +1511,7 @@ void GetOrderingsFromInnerTable( } } // If operation remained apply then ordering will be in the subquery - else if (tableExpressionBase is SelectExpression collectionSelectExpression - && collectionSelectExpression.Orderings.Count > 0) + else if (tableExpressionBase is SelectExpression { Orderings.Count: > 0 } collectionSelectExpression) { foreach (var ordering in collectionSelectExpression.Orderings) { @@ -1855,9 +1853,7 @@ private int AddToProjection(SqlExpression sqlExpression, string? alias, bool ass /// An expression to use for filtering. public void ApplyPredicate(SqlExpression sqlExpression) { - if (sqlExpression is SqlConstantExpression sqlConstant - && sqlConstant.Value is bool boolValue - && boolValue) + if (sqlExpression is SqlConstantExpression { Value: true }) { return; } @@ -1874,12 +1870,10 @@ public void ApplyPredicate(SqlExpression sqlExpression) // If the intersection is empty then we don't remove predicate so that the filter empty out all results. if (sqlExpression is SqlBinaryExpression sqlBinaryExpression) { - if (sqlBinaryExpression.Left is ColumnExpression leftColumn - && leftColumn.Table is TpcTablesExpression leftTpc + if (sqlBinaryExpression.Left is ColumnExpression { Table: TpcTablesExpression leftTpc } leftColumn && _tpcDiscriminatorValues.TryGetValue(leftTpc, out var leftTuple) && leftTuple.Item1.Equals(leftColumn) - && sqlBinaryExpression.Right is SqlConstantExpression rightConstant - && rightConstant.Value is string s1) + && sqlBinaryExpression.Right is SqlConstantExpression { Value: string s1 }) { var newList = leftTuple.Item2.Intersect(new List { s1 }).ToList(); if (newList.Count > 0) @@ -1888,12 +1882,10 @@ public void ApplyPredicate(SqlExpression sqlExpression) return; } } - else if (sqlBinaryExpression.Right is ColumnExpression rightColumn - && rightColumn.Table is TpcTablesExpression rightTpc + else if (sqlBinaryExpression.Right is ColumnExpression { Table: TpcTablesExpression rightTpc } rightColumn && _tpcDiscriminatorValues.TryGetValue(rightTpc, out var rightTuple) && rightTuple.Item1.Equals(rightColumn) - && sqlBinaryExpression.Left is SqlConstantExpression leftConstant - && leftConstant.Value is string s2) + && sqlBinaryExpression.Left is SqlConstantExpression { Value: string s2 }) { var newList = rightTuple.Item2.Intersect(new List { s2 }).ToList(); if (newList.Count > 0) @@ -2020,8 +2012,7 @@ public RelationalGroupByShaperExpression ApplyGrouping( ClearOrdering(); var keySelectorToAdd = keySelector; - var emptyKey = keySelector is NewExpression newExpression - && newExpression.Arguments.Count == 0; + var emptyKey = keySelector is NewExpression { Arguments.Count: 0 }; if (emptyKey) { keySelectorToAdd = sqlExpressionFactory.ApplyDefaultTypeMapping(sqlExpressionFactory.Constant(1)); @@ -2061,7 +2052,7 @@ public RelationalGroupByShaperExpression ApplyGrouping( var clonedSelectExpression = Clone(); var correlationPredicate = groupByTerms.Zip(clonedSelectExpression._groupBy) .Select(e => sqlExpressionFactory.Equal(e.First, e.Second)) - .Aggregate((l, r) => sqlExpressionFactory.AndAlso(l, r)); + .Aggregate(sqlExpressionFactory.AndAlso); clonedSelectExpression._groupBy.Clear(); clonedSelectExpression.ApplyPredicate(correlationPredicate); @@ -2120,8 +2111,7 @@ private static void PopulateGroupByTerms( PopulateGroupByTerms(unaryExpression.Operand, groupByTerms, groupByAliases, name); break; - case EntityShaperExpression entityShaperExpression - when entityShaperExpression.ValueBufferExpression is EntityProjectionExpression entityProjectionExpression: + case EntityShaperExpression { ValueBufferExpression: EntityProjectionExpression entityProjectionExpression }: foreach (var property in GetAllPropertiesInHierarchy(entityProjectionExpression.EntityType)) { PopulateGroupByTerms(entityProjectionExpression.BindProperty(property), groupByTerms, groupByAliases, name: null); @@ -2767,8 +2757,9 @@ static IReadOnlyDictionary GetPropertyExpressions( var innerColumns = keyProperties.Select( p => CreateColumnExpression(p, table, tableReferenceExpression, nullable: false)); - var joinPredicate = joinColumns.Zip(innerColumns, (l, r) => sqlExpressionFactory.Equal(l, r)) - .Aggregate((l, r) => sqlExpressionFactory.AndAlso(l, r)); + var joinPredicate = joinColumns + .Zip(innerColumns, sqlExpressionFactory.Equal) + .Aggregate(sqlExpressionFactory.AndAlso); var joinExpression = new LeftJoinExpression(tableExpression, joinPredicate); selectExpression._removableJoinTables.Add(selectExpression._tables.Count); @@ -2818,7 +2809,7 @@ static IReadOnlyDictionary GetPropertyExpressions( .Zip(navigation.ForeignKey.Properties .Select(p => CreateColumnExpression(p, dependentMainTable, mainTableReferenceExpression, nullable: false))) .Select(i => sqlExpressionFactory.Equal(i.First, i.Second)) - .Aggregate((l, r) => sqlExpressionFactory.AndAlso(l, r)); + .Aggregate(sqlExpressionFactory.AndAlso); var joinedTable = new LeftJoinExpression(ownedTable, outerJoinPredicate); tableReferenceExpressionMap[dependentMainTable] = mainTableReferenceExpression; selectExpression.AddTable(joinedTable, mainTableReferenceExpression); @@ -2846,8 +2837,9 @@ static IReadOnlyDictionary GetPropertyExpressions( var innerColumns = keyProperties.Select( p => CreateColumnExpression(p, table, tableReferenceExpression, nullable: false)); - var joinPredicate = joinColumns.Zip(innerColumns, (l, r) => sqlExpressionFactory.Equal(l, r)) - .Aggregate((l, r) => sqlExpressionFactory.AndAlso(l, r)); + var joinPredicate = joinColumns + .Zip(innerColumns, sqlExpressionFactory.Equal) + .Aggregate(sqlExpressionFactory.AndAlso); var joinExpression = new LeftJoinExpression(tableExpression, joinPredicate); selectExpression._removableJoinTables.Add(selectExpression._tables.Count); @@ -2892,8 +2884,7 @@ static TableExpressionBase FindRootTableExpressionForColumn(TableExpressionBase if (table is SelectExpression selectExpression) { - var matchingProjection = - (ColumnExpression)selectExpression.Projection.Where(p => p.Alias == columnName).Single().Expression; + var matchingProjection = (ColumnExpression)selectExpression.Projection.Single(p => p.Alias == columnName).Expression; return FindRootTableExpressionForColumn(matchingProjection.Table, matchingProjection.Name); } @@ -3254,7 +3245,7 @@ static void GetPartitions(SelectExpression selectExpression, SqlExpression sqlEx joinPredicate = RemoveRedundantNullChecks(joinPredicate, outerColumnExpressions); } - // we can't convert apply to join in case of distinct and groupby, if the projection doesn't already contain the join keys + // we can't convert apply to join in case of distinct and group by, if the projection doesn't already contain the join keys // since we can't add the missing keys to the projection - only convert to join if all the keys are already there if (joinPredicate != null && (inner.IsDistinct @@ -3368,15 +3359,13 @@ static void GetPartitions(SelectExpression selectExpression, SqlExpression sqlEx if (sqlBinaryExpression.OperatorType == ExpressionType.NotEqual) { if (IsContainedSql(outer, sqlBinaryExpression.Left) - && sqlBinaryExpression.Right is SqlConstantExpression rightConstant - && rightConstant.Value == null) + && sqlBinaryExpression.Right is SqlConstantExpression { Value: null }) { return sqlBinaryExpression; } if (IsContainedSql(outer, sqlBinaryExpression.Right) - && sqlBinaryExpression.Left is SqlConstantExpression leftConstant - && leftConstant.Value == null) + && sqlBinaryExpression.Left is SqlConstantExpression { Value: null }) { return sqlBinaryExpression.Update( sqlBinaryExpression.Right, @@ -3388,25 +3377,22 @@ static void GetPartitions(SelectExpression selectExpression, SqlExpression sqlEx } static bool IsContainedSql(SelectExpression selectExpression, SqlExpression sqlExpression) - { - switch (sqlExpression) + => sqlExpression switch { - case ColumnExpression columnExpression: - return selectExpression.ContainsTableReference(columnExpression); - - case CaseExpression caseExpression - when caseExpression.ElseResult == null - && caseExpression.Operand == null - && caseExpression.WhenClauses.Count == 1 - && caseExpression.WhenClauses[0].Result is ColumnExpression resultColumn: - // We check condition in a separate function to avoid matching structure of condition outside of case block - return IsContainedCondition(selectExpression, caseExpression.WhenClauses[0].Test) - && selectExpression.ContainsTableReference(resultColumn); + ColumnExpression columnExpression => selectExpression.ContainsTableReference(columnExpression), - default: - return false; - } - } + // We check condition in a separate function to avoid matching structure of condition outside of case block + CaseExpression + { + Operand: null, + WhenClauses: [{ Result: ColumnExpression resultColumn }], + ElseResult: null + } caseExpression + => IsContainedCondition(selectExpression, caseExpression.WhenClauses[0].Test) + && selectExpression.ContainsTableReference(resultColumn), + + _ => false + }; static bool IsContainedCondition(SelectExpression selectExpression, SqlExpression condition) { @@ -3421,8 +3407,7 @@ static bool IsContainedCondition(SelectExpression selectExpression, SqlExpressio if (sqlBinaryExpression.OperatorType == ExpressionType.NotEqual) { // We don't check left/right inverted because we generate this. - return sqlBinaryExpression.Right is SqlConstantExpression { Value: null } - && sqlBinaryExpression.Left is ColumnExpression column + return sqlBinaryExpression is { Left: ColumnExpression column, Right: SqlConstantExpression { Value: null } } && selectExpression.ContainsTableReference(column); } @@ -3460,8 +3445,7 @@ static List ExtractColumnsFromProjectionMapping( result.Add(entityProjection.BindProperty(property)); } - if (entityProjection.DiscriminatorExpression != null - && entityProjection.DiscriminatorExpression is ColumnExpression discriminatorColumn) + if (entityProjection.DiscriminatorExpression is ColumnExpression discriminatorColumn) { result.Add(discriminatorColumn); } @@ -3488,8 +3472,7 @@ static List ExtractColumnsFromProjectionMapping( { if (sqlBinaryExpression.OperatorType == ExpressionType.NotEqual && outerColumnExpressions.Contains(sqlBinaryExpression.Left) - && sqlBinaryExpression.Right is SqlConstantExpression sqlConstantExpression - && sqlConstantExpression.Value == null) + && sqlBinaryExpression.Right is SqlConstantExpression { Value: null }) { return null; } @@ -3629,9 +3612,9 @@ private SqlRemappingVisitor PushdownIntoSubqueryInternal(bool liftOrderings = tr Having = Having, Offset = Offset, Limit = Limit, + _usedAliases = _usedAliases, + _mutable = false }; - subquery._usedAliases = _usedAliases; - subquery._mutable = false; _tables.Clear(); _tableReferences.Clear(); _groupBy.Clear(); @@ -3924,8 +3907,7 @@ public bool IsNonComposedFromSql() && GroupBy.Count == 0 && Having == null && Orderings.Count == 0 - && Tables.Count == 1 - && Tables[0] is FromSqlExpression fromSql + && Tables is [FromSqlExpression fromSql] && Projection.All( pe => pe.Expression is ColumnExpression column && string.Equals(fromSql.Alias, column.TableAlias, StringComparison.OrdinalIgnoreCase)) @@ -4262,7 +4244,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) var newTables = VisitList(_tables, inPlace: true, out var tablesChanged); Check.DebugAssert( !tablesChanged - || newTables.Select(e => GetAliasFromTableExpressionBase(e)).SequenceEqual(_tableReferences.Select(e => e.Alias)), + || newTables.Select(GetAliasFromTableExpressionBase).SequenceEqual(_tableReferences.Select(e => e.Alias)), "Alias of updated tables must match the old tables."); Predicate = (SqlExpression?)visitor.Visit(Predicate); @@ -4286,8 +4268,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) } if (newGroupBy != _groupBy - && !(newGroupingKey is SqlConstantExpression - || newGroupingKey is SqlParameterExpression)) + && newGroupingKey is not (SqlConstantExpression or SqlParameterExpression)) { newGroupBy.Add(newGroupingKey); } @@ -4340,7 +4321,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) Check.DebugAssert( !tablesChanged - || newTables.Select(e => GetAliasFromTableExpressionBase(e)).SequenceEqual(_tableReferences.Select(e => e.Alias)), + || newTables.Select(GetAliasFromTableExpressionBase).SequenceEqual(_tableReferences.Select(e => e.Alias)), "Alias of updated tables must match the old tables."); var predicate = (SqlExpression?)visitor.Visit(Predicate); @@ -4368,8 +4349,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) } if (newGroupBy != _groupBy - && !(newGroupingKey is SqlConstantExpression - || newGroupingKey is SqlParameterExpression)) + && newGroupingKey is not (SqlConstantExpression or SqlParameterExpression)) { newGroupBy.Add(newGroupingKey); } @@ -4416,8 +4396,8 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) IsDistinct = IsDistinct, Tags = Tags, _usedAliases = _usedAliases, + _mutable = false }; - newSelectExpression._mutable = false; newSelectExpression._removableJoinTables.AddRange(_removableJoinTables); foreach (var kvp in newTpcDiscriminatorValues) { @@ -4528,11 +4508,10 @@ public SelectExpression Update( Offset = offset, Limit = limit, IsDistinct = IsDistinct, - Tags = Tags + Tags = Tags, + _mutable = false }; - newSelectExpression._mutable = false; - // We don't copy identifiers because when we are doing reconstruction so projection is already applied. // Update method should not be used pre-projection application. There are other methods to change SelectExpression. diff --git a/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs b/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs index 3e14e44e7e8..92f29da4d75 100644 --- a/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs +++ b/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs @@ -3,7 +3,6 @@ using System.Collections; using System.Diagnostics.CodeAnalysis; -using System.Net.Http.Headers; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; namespace Microsoft.EntityFrameworkCore.Query; @@ -1168,8 +1167,7 @@ protected virtual SqlExpression VisitSqlBinary( rightNullable, out nullable); - if (optimized is SqlUnaryExpression optimizedUnary - && optimizedUnary.Operand is ColumnExpression optimizedUnaryColumnOperand) + if (optimized is SqlUnaryExpression { Operand: ColumnExpression optimizedUnaryColumnOperand } optimizedUnary) { if (optimizedUnary.OperatorType == ExpressionType.NotEqual) { @@ -1270,8 +1268,7 @@ protected virtual SqlExpression VisitSqlFunction( bool allowOptimizedExpansion, out bool nullable) { - if (sqlFunctionExpression.IsBuiltIn - && sqlFunctionExpression.Arguments != null + if (sqlFunctionExpression is { IsBuiltIn: true, Arguments: not null } && string.Equals(sqlFunctionExpression.Name, "COALESCE", StringComparison.OrdinalIgnoreCase)) { var coalesceArguments = new List(); @@ -1357,8 +1354,7 @@ protected virtual SqlExpression VisitSqlUnary( // result of IsNull/IsNotNull can never be null nullable = false; - if (result is SqlUnaryExpression resultUnary - && resultUnary.Operand is ColumnExpression resultColumnOperand) + if (result is SqlUnaryExpression { Operand: ColumnExpression resultColumnOperand } resultUnary) { if (resultUnary.OperatorType == ExpressionType.NotEqual) { @@ -1703,10 +1699,9 @@ private SqlExpression RewriteNullSemantics( private SqlExpression SimplifyLogicalSqlBinaryExpression(SqlBinaryExpression sqlBinaryExpression) { - if (sqlBinaryExpression.Left is SqlUnaryExpression leftUnary - && sqlBinaryExpression.Right is SqlUnaryExpression rightUnary - && (leftUnary.OperatorType == ExpressionType.Equal || leftUnary.OperatorType == ExpressionType.NotEqual) - && (rightUnary.OperatorType == ExpressionType.Equal || rightUnary.OperatorType == ExpressionType.NotEqual) + if (sqlBinaryExpression is { + Left: SqlUnaryExpression { OperatorType: ExpressionType.Equal or ExpressionType.NotEqual } leftUnary, + Right: SqlUnaryExpression { OperatorType: ExpressionType.Equal or ExpressionType.NotEqual } rightUnary } && leftUnary.Operand.Equals(rightUnary.Operand)) { // a is null || a is null -> a is null @@ -1725,8 +1720,7 @@ private SqlExpression SimplifyLogicalSqlBinaryExpression(SqlBinaryExpression sql // true || a -> true // false && a -> false // false || a -> a - if (sqlBinaryExpression.Left is SqlConstantExpression newLeftConstant - && newLeftConstant.Value is bool leftBoolValue) + if (sqlBinaryExpression.Left is SqlConstantExpression { Value: bool leftBoolValue } newLeftConstant) { return sqlBinaryExpression.OperatorType == ExpressionType.AndAlso ? leftBoolValue @@ -1737,8 +1731,7 @@ private SqlExpression SimplifyLogicalSqlBinaryExpression(SqlBinaryExpression sql : sqlBinaryExpression.Right; } - if (sqlBinaryExpression.Right is SqlConstantExpression newRightConstant - && newRightConstant.Value is bool rightBoolValue) + if (sqlBinaryExpression.Right is SqlConstantExpression { Value: bool rightBoolValue } newRightConstant) { // a && true -> a // a || true -> true @@ -2033,8 +2026,7 @@ private SqlExpression ProcessNullNotNull(SqlUnaryExpression sqlUnaryExpression, // see if we can derive function nullability from it's instance and/or arguments // rather than evaluating nullability of the entire function var nullabilityPropagationElements = new List(); - if (sqlFunctionExpression.Instance != null - && sqlFunctionExpression.InstancePropagatesNullability == true) + if (sqlFunctionExpression is { Instance: not null, InstancePropagatesNullability: true }) { nullabilityPropagationElements.Add(sqlFunctionExpression.Instance); } @@ -2079,9 +2071,7 @@ private SqlExpression ProcessNullNotNull(SqlUnaryExpression sqlUnaryExpression, } private static bool IsLogicalNot(SqlUnaryExpression? sqlUnaryExpression) - => sqlUnaryExpression != null - && sqlUnaryExpression.OperatorType == ExpressionType.Not - && sqlUnaryExpression.Type == typeof(bool); + => sqlUnaryExpression is { OperatorType: ExpressionType.Not } && sqlUnaryExpression.Type == typeof(bool); private bool IsNull(SqlExpression expression) => expression is SqlConstantExpression { Value: null } diff --git a/src/EFCore.Relational/Storage/DbContextTransactionExtensions.cs b/src/EFCore.Relational/Storage/DbContextTransactionExtensions.cs index 880e51c9534..fe279e6d772 100644 --- a/src/EFCore.Relational/Storage/DbContextTransactionExtensions.cs +++ b/src/EFCore.Relational/Storage/DbContextTransactionExtensions.cs @@ -22,7 +22,7 @@ public static class DbContextTransactionExtensions /// The underlying . public static DbTransaction GetDbTransaction(this IDbContextTransaction dbContextTransaction) { - if (!(dbContextTransaction is IInfrastructure accessor)) + if (dbContextTransaction is not IInfrastructure accessor) { throw new InvalidOperationException(RelationalStrings.RelationalNotInUse); } diff --git a/src/EFCore.Relational/Storage/Internal/DbParameterCollectionExtensions.cs b/src/EFCore.Relational/Storage/Internal/DbParameterCollectionExtensions.cs index e0abddc25e1..de91242f233 100644 --- a/src/EFCore.Relational/Storage/Internal/DbParameterCollectionExtensions.cs +++ b/src/EFCore.Relational/Storage/Internal/DbParameterCollectionExtensions.cs @@ -196,8 +196,7 @@ private static void FormatParameterValue(StringBuilder builder, object? paramete { var isNullProperty = type.GetRuntimeProperty("IsNull"); if (isNullProperty != null - && isNullProperty.GetValue(parameterValue) is bool isNull - && isNull) + && isNullProperty.GetValue(parameterValue) is true) { builder.Append("''"); } diff --git a/src/EFCore.Relational/Storage/RelationalConnection.cs b/src/EFCore.Relational/Storage/RelationalConnection.cs index 446dd23667f..b0aadea1a5a 100644 --- a/src/EFCore.Relational/Storage/RelationalConnection.cs +++ b/src/EFCore.Relational/Storage/RelationalConnection.cs @@ -276,8 +276,7 @@ public virtual int? CommandTimeout get => _commandTimeout; set { - if (value.HasValue - && value < 0) + if (value is < 0) { throw new ArgumentException(RelationalStrings.InvalidCommandTimeout(value)); } diff --git a/src/EFCore.Relational/Storage/TypeMaterializationInfo.cs b/src/EFCore.Relational/Storage/TypeMaterializationInfo.cs index efb399119c0..1d32ca97a46 100644 --- a/src/EFCore.Relational/Storage/TypeMaterializationInfo.cs +++ b/src/EFCore.Relational/Storage/TypeMaterializationInfo.cs @@ -76,7 +76,7 @@ protected virtual bool Equals(TypeMaterializationInfo other) /// The object to compare with the current object. /// if the specified object is equal to the current object; otherwise, . public override bool Equals(object? obj) - => !(obj is null) + => obj is not null && (ReferenceEquals(this, obj) || obj.GetType() == GetType() && Equals((TypeMaterializationInfo)obj)); diff --git a/src/EFCore.Relational/Update/Internal/CommandBatchPreparer.cs b/src/EFCore.Relational/Update/Internal/CommandBatchPreparer.cs index e832d0f52e2..4b2f86e7288 100644 --- a/src/EFCore.Relational/Update/Internal/CommandBatchPreparer.cs +++ b/src/EFCore.Relational/Update/Internal/CommandBatchPreparer.cs @@ -209,8 +209,7 @@ protected virtual IEnumerable CreateModificationCo Dictionary<(string Name, string? Schema), SharedTableEntryMap>? sharedTablesCommandsMap = null; foreach (var entry in entries) { - if (entry.SharedIdentityEntry != null - && entry.EntityState == EntityState.Deleted) + if (entry is { SharedIdentityEntry: not null, EntityState: EntityState.Deleted }) { continue; } diff --git a/src/EFCore.Relational/Update/Internal/CompositeRowIndexValueFactory.cs b/src/EFCore.Relational/Update/Internal/CompositeRowIndexValueFactory.cs index fedeec8cf44..aca7d598e19 100644 --- a/src/EFCore.Relational/Update/Internal/CompositeRowIndexValueFactory.cs +++ b/src/EFCore.Relational/Update/Internal/CompositeRowIndexValueFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Diagnostics.CodeAnalysis; - namespace Microsoft.EntityFrameworkCore.Update.Internal; /// diff --git a/src/EFCore.Relational/Update/Internal/IRowIndexValueFactory`.cs b/src/EFCore.Relational/Update/Internal/IRowIndexValueFactory`.cs index 873b1353372..9b3296b1161 100644 --- a/src/EFCore.Relational/Update/Internal/IRowIndexValueFactory`.cs +++ b/src/EFCore.Relational/Update/Internal/IRowIndexValueFactory`.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Diagnostics.CodeAnalysis; - namespace Microsoft.EntityFrameworkCore.Update.Internal; /// diff --git a/src/EFCore.Relational/Update/Internal/SimpleRowIndexValueFactory.cs b/src/EFCore.Relational/Update/Internal/SimpleRowIndexValueFactory.cs index b9812222688..dbc8d1ef1af 100644 --- a/src/EFCore.Relational/Update/Internal/SimpleRowIndexValueFactory.cs +++ b/src/EFCore.Relational/Update/Internal/SimpleRowIndexValueFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; diff --git a/src/EFCore.Relational/Update/ModificationCommand.cs b/src/EFCore.Relational/Update/ModificationCommand.cs index 5c7b5078965..631310a3727 100644 --- a/src/EFCore.Relational/Update/ModificationCommand.cs +++ b/src/EFCore.Relational/Update/ModificationCommand.cs @@ -253,7 +253,7 @@ private List GenerateColumnModifications() var jsonEntry = false; if (_entries.Count > 1 - || (_entries.Count == 1 && _entries[0].SharedIdentityEntry != null)) + || _entries is [{ SharedIdentityEntry: not null }]) { Check.DebugAssert(StoreStoredProcedure is null, "Multiple entries/shared identity not supported with stored procedures"); diff --git a/src/EFCore.Relational/Update/UpdateAndSelectSqlGenerator.cs b/src/EFCore.Relational/Update/UpdateAndSelectSqlGenerator.cs index 34ac1dc0c7a..727b7df15e1 100644 --- a/src/EFCore.Relational/Update/UpdateAndSelectSqlGenerator.cs +++ b/src/EFCore.Relational/Update/UpdateAndSelectSqlGenerator.cs @@ -246,13 +246,10 @@ protected virtual void AppendWhereAffectedClause( .AppendJoin( operations, (sb, v) => { - if (v.IsKey) + if (v is { IsKey: true, IsRead: false }) { - if (!v.IsRead) - { - AppendWhereCondition(sb, v, v.UseOriginalValueParameter); - return true; - } + AppendWhereCondition(sb, v, v.UseOriginalValueParameter); + return true; } if (IsIdentityOperation(v)) @@ -272,7 +269,7 @@ protected virtual void AppendWhereAffectedClause( /// The column modification. /// if the given modification represents an auto-incrementing column. protected virtual bool IsIdentityOperation(IColumnModification modification) - => modification.IsKey && modification.IsRead; + => modification is { IsKey: true, IsRead: true }; /// /// Appends a WHERE condition checking rows affected. diff --git a/src/EFCore.SqlServer.HierarchyId/Infrastructure/Internal/SqlServerHierarchyIdOptionsExtension.cs b/src/EFCore.SqlServer.HierarchyId/Infrastructure/Internal/SqlServerHierarchyIdOptionsExtension.cs index 59ab22b3b21..df7376c8a46 100644 --- a/src/EFCore.SqlServer.HierarchyId/Infrastructure/Internal/SqlServerHierarchyIdOptionsExtension.cs +++ b/src/EFCore.SqlServer.HierarchyId/Infrastructure/Internal/SqlServerHierarchyIdOptionsExtension.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.SqlServer.Internal; diff --git a/src/EFCore.SqlServer.HierarchyId/Query/Internal/SqlServerHierarchyIdMethodTranslator.cs b/src/EFCore.SqlServer.HierarchyId/Query/Internal/SqlServerHierarchyIdMethodTranslator.cs index cb2a8f909c0..d4dbf9d638c 100644 --- a/src/EFCore.SqlServer.HierarchyId/Query/Internal/SqlServerHierarchyIdMethodTranslator.cs +++ b/src/EFCore.SqlServer.HierarchyId/Query/Internal/SqlServerHierarchyIdMethodTranslator.cs @@ -79,8 +79,7 @@ public SqlServerHierarchyIdMethodTranslator( if (argument.Type == typeof(HierarchyId)) { - if (argument is SqlConstantExpression constant - && constant.Value is HierarchyId hierarchyId) + if (argument is SqlConstantExpression { Value: HierarchyId hierarchyId }) { argument = _sqlExpressionFactory.Fragment($"'{hierarchyId}'"); } diff --git a/src/EFCore.SqlServer.HierarchyId/Scaffolding/Internal/SqlServerHierarchyIdCodeGeneratorPlugin.cs b/src/EFCore.SqlServer.HierarchyId/Scaffolding/Internal/SqlServerHierarchyIdCodeGeneratorPlugin.cs index 4d4667064d5..da4fcceef98 100644 --- a/src/EFCore.SqlServer.HierarchyId/Scaffolding/Internal/SqlServerHierarchyIdCodeGeneratorPlugin.cs +++ b/src/EFCore.SqlServer.HierarchyId/Scaffolding/Internal/SqlServerHierarchyIdCodeGeneratorPlugin.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Scaffolding; diff --git a/src/EFCore.SqlServer.NTS/Query/Internal/SqlServerGeometryMethodTranslator.cs b/src/EFCore.SqlServer.NTS/Query/Internal/SqlServerGeometryMethodTranslator.cs index d99347b95e0..a70421eb8db 100644 --- a/src/EFCore.SqlServer.NTS/Query/Internal/SqlServerGeometryMethodTranslator.cs +++ b/src/EFCore.SqlServer.NTS/Query/Internal/SqlServerGeometryMethodTranslator.cs @@ -190,8 +190,7 @@ private IEnumerable Simplify(IEnumerable arguments { foreach (var argument in arguments) { - if (argument is SqlConstantExpression constant - && constant.Value is Geometry geometry + if (argument is SqlConstantExpression { Value: Geometry geometry } && geometry.SRID == (isGeography ? 4326 : 0)) { yield return _sqlExpressionFactory.Fragment("'" + geometry.AsText() + "'"); diff --git a/src/EFCore.SqlServer/Metadata/Conventions/SqlServerOutputClauseConvention.cs b/src/EFCore.SqlServer/Metadata/Conventions/SqlServerOutputClauseConvention.cs index ba21e538459..9d92096a7aa 100644 --- a/src/EFCore.SqlServer/Metadata/Conventions/SqlServerOutputClauseConvention.cs +++ b/src/EFCore.SqlServer/Metadata/Conventions/SqlServerOutputClauseConvention.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.SqlServer.Internal; + // ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore.Metadata.Conventions; diff --git a/src/EFCore.SqlServer/Metadata/Conventions/SqlServerTemporalConvention.cs b/src/EFCore.SqlServer/Metadata/Conventions/SqlServerTemporalConvention.cs index 7ec0bccbf1b..3ac9a323cf4 100644 --- a/src/EFCore.SqlServer/Metadata/Conventions/SqlServerTemporalConvention.cs +++ b/src/EFCore.SqlServer/Metadata/Conventions/SqlServerTemporalConvention.cs @@ -70,8 +70,7 @@ public virtual void ProcessEntityTypeAnnotationChanged( if (skipLevelNavigation.DeclaringEntityType.IsTemporal() && skipLevelNavigation.Inverse is IConventionSkipNavigation inverse && inverse.DeclaringEntityType.IsTemporal() - && skipLevelNavigation.JoinEntityType is IConventionEntityType joinEntityType - && joinEntityType.HasSharedClrType + && skipLevelNavigation.JoinEntityType is IConventionEntityType { HasSharedClrType: true } joinEntityType && !joinEntityType.IsTemporal() && joinEntityType.GetConfigurationSource() == ConfigurationSource.Convention) { @@ -128,8 +127,7 @@ public virtual void ProcessSkipNavigationForeignKeyChanged( IConventionForeignKey? oldForeignKey, IConventionContext context) { - if (skipNavigationBuilder.Metadata.JoinEntityType is IConventionEntityType joinEntityType - && joinEntityType.HasSharedClrType + if (skipNavigationBuilder.Metadata.JoinEntityType is { HasSharedClrType: true } joinEntityType && !joinEntityType.IsTemporal() && joinEntityType.GetConfigurationSource() == ConfigurationSource.Convention && skipNavigationBuilder.Metadata.DeclaringEntityType.IsTemporal() diff --git a/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs b/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs index 30b6458ec2c..9b8199c32f5 100644 --- a/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs +++ b/src/EFCore.SqlServer/Migrations/SqlServerMigrationsSqlGenerator.cs @@ -312,7 +312,7 @@ protected override void Generate( model); narrowed = columnType != oldType || operation.Collation != operation.OldColumn.Collation - || !operation.IsNullable && operation.OldColumn.IsNullable; + || operation is { IsNullable: false, OldColumn.IsNullable: true }; } if (narrowed) @@ -347,8 +347,7 @@ protected override void Generate( // The column is being made non-nullable. Generate an update statement before doing that, to convert any existing null values to // the default value (otherwise SQL Server fails). - if (!operation.IsNullable - && operation.OldColumn.IsNullable + if (operation is { IsNullable: false, OldColumn.IsNullable: true } && (operation.DefaultValueSql is not null || operation.DefaultValue is not null)) { string defaultValueSql; diff --git a/src/EFCore.SqlServer/Query/Internal/SearchConditionConvertingExpressionVisitor.cs b/src/EFCore.SqlServer/Query/Internal/SearchConditionConvertingExpressionVisitor.cs index 150640dbe0c..32da0a2ef15 100644 --- a/src/EFCore.SqlServer/Query/Internal/SearchConditionConvertingExpressionVisitor.cs +++ b/src/EFCore.SqlServer/Query/Internal/SearchConditionConvertingExpressionVisitor.cs @@ -51,24 +51,24 @@ private SqlExpression ConvertToValue(SqlExpression sqlExpression, bool condition : sqlExpression; private SqlExpression BuildCompareToExpression(SqlExpression sqlExpression) - => sqlExpression is SqlConstantExpression sqlConstantExpression - && sqlConstantExpression.Value is bool boolValue - ? _sqlExpressionFactory.Equal( - boolValue - ? _sqlExpressionFactory.Constant(1) - : _sqlExpressionFactory.Constant(0), - _sqlExpressionFactory.Constant(1)) - : _sqlExpressionFactory.Equal( - sqlExpression, - _sqlExpressionFactory.Constant(true)); + => sqlExpression is SqlConstantExpression { Value: bool boolValue } + ? _sqlExpressionFactory.Equal( + boolValue + ? _sqlExpressionFactory.Constant(1) + : _sqlExpressionFactory.Constant(0), + _sqlExpressionFactory.Constant(1)) + : _sqlExpressionFactory.Equal( + sqlExpression, + _sqlExpressionFactory.Constant(true)); private SqlExpression SimplifyNegatedBinary(SqlExpression sqlExpression) { - if (sqlExpression is SqlUnaryExpression sqlUnaryExpression - && sqlUnaryExpression.OperatorType == ExpressionType.Not + if (sqlExpression is SqlUnaryExpression { OperatorType: ExpressionType.Not } sqlUnaryExpression && sqlUnaryExpression.Type == typeof(bool) - && sqlUnaryExpression.Operand is SqlBinaryExpression sqlBinaryOperand - && (sqlBinaryOperand.OperatorType == ExpressionType.Equal || sqlBinaryOperand.OperatorType == ExpressionType.NotEqual)) + && sqlUnaryExpression.Operand is SqlBinaryExpression + { + OperatorType: ExpressionType.Equal or ExpressionType.NotEqual + } sqlBinaryOperand) { if (sqlBinaryOperand.Left.Type == typeof(bool) && sqlBinaryOperand.Right.Type == typeof(bool) diff --git a/src/EFCore.SqlServer/Query/Internal/SkipTakeCollapsingExpressionVisitor.cs b/src/EFCore.SqlServer/Query/Internal/SkipTakeCollapsingExpressionVisitor.cs index 6d4219c78e3..c8f6db92698 100644 --- a/src/EFCore.SqlServer/Query/Internal/SkipTakeCollapsingExpressionVisitor.cs +++ b/src/EFCore.SqlServer/Query/Internal/SkipTakeCollapsingExpressionVisitor.cs @@ -79,12 +79,11 @@ bool IsZero(SqlExpression? sqlExpression) { switch (sqlExpression) { - case SqlConstantExpression constant - when constant.Value is int intValue: + case SqlConstantExpression { Value: int intValue }: return intValue == 0; case SqlParameterExpression parameter: _canCache = false; - return _parameterValues[parameter.Name] is int value && value == 0; + return _parameterValues[parameter.Name] is 0; default: return false; diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerFullTextSearchFunctionsTranslator.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerFullTextSearchFunctionsTranslator.cs index 5854b7ab1af..03a87e4b9f9 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerFullTextSearchFunctionsTranslator.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerFullTextSearchFunctionsTranslator.cs @@ -72,7 +72,7 @@ public SqlServerFullTextSearchFunctionsTranslator(ISqlExpressionFactory sqlExpre if (FunctionMapping.TryGetValue(method, out var functionName)) { var propertyReference = arguments[1]; - if (!(propertyReference is ColumnExpression)) + if (propertyReference is not ColumnExpression) { throw new InvalidOperationException(SqlServerStrings.InvalidColumnNameForFreeText); } diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerObjectToStringTranslator.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerObjectToStringTranslator.cs index bb620154f54..eafc43b230c 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerObjectToStringTranslator.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerObjectToStringTranslator.cs @@ -74,7 +74,7 @@ public SqlServerObjectToStringTranslator(ISqlExpressionFactory sqlExpressionFact if (instance.Type == typeof(bool)) { - if (instance is ColumnExpression columnExpression && columnExpression.IsNullable) + if (instance is ColumnExpression { IsNullable: true }) { return _sqlExpressionFactory.Case( new[] diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs index bd01b509952..8a32db8ccda 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerQuerySqlGenerator.cs @@ -225,8 +225,7 @@ protected override void GenerateValues(ValuesExpression valuesExpression) /// protected override void GenerateTop(SelectExpression selectExpression) { - if (selectExpression.Limit != null - && selectExpression.Offset == null) + if (selectExpression is { Limit: not null, Offset: null }) { Sql.Append("TOP("); diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerQueryStringFactory.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerQueryStringFactory.cs index d379265dfe4..cd3c0f3fdd6 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerQueryStringFactory.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerQueryStringFactory.cs @@ -139,8 +139,7 @@ private static StringBuilder AppendScale(this StringBuilder builder, DbParameter private static StringBuilder AppendPrecisionAndScale(this StringBuilder builder, DbParameter parameter) { - if (parameter.Precision > 0 - && parameter.Scale > 0) + if (parameter is { Precision: > 0, Scale: > 0 }) { return builder .Append('(') diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerSqlTranslatingExpressionVisitor.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerSqlTranslatingExpressionVisitor.cs index 9a96f61066b..c660f7d2600 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerSqlTranslatingExpressionVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Internal; diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerStringAggregateMethodTranslator.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerStringAggregateMethodTranslator.cs index fb6041dbb82..51e09076c60 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerStringAggregateMethodTranslator.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerStringAggregateMethodTranslator.cs @@ -61,7 +61,7 @@ public SqlServerStringAggregateMethodTranslator( var resultTypeMapping = sqlExpression.TypeMapping; if (resultTypeMapping?.Size != null) { - if (resultTypeMapping.IsUnicode && resultTypeMapping.Size < 4000) + if (resultTypeMapping is { IsUnicode: true, Size: < 4000 }) { resultTypeMapping = _typeMappingSource.FindMapping( typeof(string), @@ -69,7 +69,7 @@ public SqlServerStringAggregateMethodTranslator( unicode: true, size: 4000); } - else if (!resultTypeMapping.IsUnicode && resultTypeMapping.Size < 8000) + else if (resultTypeMapping is { IsUnicode: false, Size: < 8000 }) { resultTypeMapping = _typeMappingSource.FindMapping( typeof(string), diff --git a/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs b/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs index a7f34b2d071..a7e4ca29d43 100644 --- a/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs +++ b/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs @@ -1211,7 +1211,7 @@ bool TryGetIndex( index[SqlServerAnnotationNames.Clustered] = true; } - if (indexGroup.Key.FillFactor > 0 && indexGroup.Key.FillFactor <= 100) + if (indexGroup.Key.FillFactor is > 0 and <= 100) { index[SqlServerAnnotationNames.FillFactor] = (int)indexGroup.Key.FillFactor; } diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerByteArrayTypeMapping.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerByteArrayTypeMapping.cs index 3e6fe74b0dc..4a8c02d7e0a 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerByteArrayTypeMapping.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerByteArrayTypeMapping.cs @@ -100,8 +100,7 @@ protected override void ConfigureParameter(DbParameter parameter) // Fixed-sized parameters get exact length to avoid padding/truncation. parameter.Size = IsFixedLength ? length.Value : maxSpecificSize; } - else if (length != null - && length <= MaxSize) + else if (length is <= MaxSize) { parameter.Size = IsFixedLength ? length.Value : MaxSize; } diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerDateTimeOffsetTypeMapping.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerDateTimeOffsetTypeMapping.cs index 59fb13e6ab0..80e248b4bca 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerDateTimeOffsetTypeMapping.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerDateTimeOffsetTypeMapping.cs @@ -79,8 +79,7 @@ protected override string SqlLiteralFormatString if (Precision.HasValue) { var precision = Precision.Value; - if (precision <= 7 - && precision >= 0) + if (precision is <= 7 and >= 0) { return _dateTimeOffsetFormats[precision]; } diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerTransaction.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerTransaction.cs index d3ac9713973..03b61af847a 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerTransaction.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerTransaction.cs @@ -35,7 +35,7 @@ public override bool SupportsSavepoints { get { - if (Connection is ISqlServerConnection sqlServerConnection && sqlServerConnection.IsMultipleActiveResultSetsEnabled) + if (Connection is ISqlServerConnection { IsMultipleActiveResultSetsEnabled: true }) { Logger.SavepointsDisabledBecauseOfMARS(); diff --git a/src/EFCore.SqlServer/Update/Internal/SqlServerModificationCommandBatch.cs b/src/EFCore.SqlServer/Update/Internal/SqlServerModificationCommandBatch.cs index a61a7a7b27f..4f857a6af38 100644 --- a/src/EFCore.SqlServer/Update/Internal/SqlServerModificationCommandBatch.cs +++ b/src/EFCore.SqlServer/Update/Internal/SqlServerModificationCommandBatch.cs @@ -156,7 +156,7 @@ protected override void AddCommand(IReadOnlyModificationCommand modificationComm { // TryAddCommand above already applied any pending commands if the new command is incompatible with them. // So if the new command is an insert, just append it to pending, otherwise do the regular add logic. - if (modificationCommand.EntityState == EntityState.Added && modificationCommand.StoreStoredProcedure is null) + if (modificationCommand is { EntityState: EntityState.Added, StoreStoredProcedure: null }) { _pendingBulkInsertCommands.Add(modificationCommand); AddParameters(modificationCommand); diff --git a/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs b/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs index 2d14fa51cf6..ad5a9d6b3e4 100644 --- a/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs +++ b/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs @@ -305,7 +305,7 @@ public virtual ResultSetMapping AppendBulkInsertOperation( { requiresTransaction = modificationCommands.Count > 1; - if (!writableOperations.Any(o => o.IsRead && o.IsKey)) + if (!writableOperations.Any(o => o is { IsRead: true, IsKey: true })) { foreach (var modification in modificationCommands) { diff --git a/src/EFCore.Sqlite.Core/Extensions/SqliteServiceCollectionExtensions.cs b/src/EFCore.Sqlite.Core/Extensions/SqliteServiceCollectionExtensions.cs index f88ec4741b3..2e5e0301880 100644 --- a/src/EFCore.Sqlite.Core/Extensions/SqliteServiceCollectionExtensions.cs +++ b/src/EFCore.Sqlite.Core/Extensions/SqliteServiceCollectionExtensions.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; -using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore.Sqlite.Diagnostics.Internal; using Microsoft.EntityFrameworkCore.Sqlite.Infrastructure.Internal; using Microsoft.EntityFrameworkCore.Sqlite.Metadata.Internal; diff --git a/src/EFCore.Sqlite.Core/Infrastructure/Internal/SqliteModelValidator.cs b/src/EFCore.Sqlite.Core/Infrastructure/Internal/SqliteModelValidator.cs index ecad54a2c34..e2c12d98d82 100644 --- a/src/EFCore.Sqlite.Core/Infrastructure/Internal/SqliteModelValidator.cs +++ b/src/EFCore.Sqlite.Core/Infrastructure/Internal/SqliteModelValidator.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.EntityFrameworkCore.Sqlite.Internal; -using Microsoft.EntityFrameworkCore.Sqlite.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.Sqlite.Infrastructure.Internal; diff --git a/src/EFCore.Sqlite.Core/Metadata/Internal/SqliteAnnotationProvider.cs b/src/EFCore.Sqlite.Core/Metadata/Internal/SqliteAnnotationProvider.cs index 227abd980ad..fdb63ec6830 100644 --- a/src/EFCore.Sqlite.Core/Metadata/Internal/SqliteAnnotationProvider.cs +++ b/src/EFCore.Sqlite.Core/Metadata/Internal/SqliteAnnotationProvider.cs @@ -68,8 +68,7 @@ public override IEnumerable For(IColumn column, bool designTime) var property = column.PropertyMappings.First().Property; // Only return auto increment for integer single column primary key var primaryKey = property.DeclaringEntityType.FindPrimaryKey(); - if (primaryKey != null - && primaryKey.Properties.Count == 1 + if (primaryKey is { Properties.Count: 1 } && primaryKey.Properties[0] == property && property.ValueGenerated == ValueGenerated.OnAdd && property.ClrType.UnwrapNullableType().IsInteger() diff --git a/src/EFCore.Sqlite.Core/Migrations/SqliteMigrationsSqlGenerator.cs b/src/EFCore.Sqlite.Core/Migrations/SqliteMigrationsSqlGenerator.cs index 5600027aeda..d1d6e7e23ff 100644 --- a/src/EFCore.Sqlite.Core/Migrations/SqliteMigrationsSqlGenerator.cs +++ b/src/EFCore.Sqlite.Core/Migrations/SqliteMigrationsSqlGenerator.cs @@ -386,8 +386,7 @@ private IReadOnlyList RewriteOperations( intoBuilder.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(column.Name)); var defaultValue = rebuildContext.AlterColumnsDeferred.TryGetValue(column.Name, out var alterColumnOperation) - && !alterColumnOperation.IsNullable - && alterColumnOperation.OldColumn.IsNullable + && alterColumnOperation is { IsNullable: false, OldColumn.IsNullable: true } ? alterColumnOperation.DefaultValue : null; if (defaultValue != null) diff --git a/src/EFCore.Sqlite.Core/Query/Internal/SqliteObjectToStringTranslator.cs b/src/EFCore.Sqlite.Core/Query/Internal/SqliteObjectToStringTranslator.cs index 44e1cc2ac2a..2cd849f420d 100644 --- a/src/EFCore.Sqlite.Core/Query/Internal/SqliteObjectToStringTranslator.cs +++ b/src/EFCore.Sqlite.Core/Query/Internal/SqliteObjectToStringTranslator.cs @@ -73,7 +73,7 @@ public SqliteObjectToStringTranslator(ISqlExpressionFactory sqlExpressionFactory if (instance.Type == typeof(bool)) { - if (instance is ColumnExpression columnExpression && columnExpression.IsNullable) + if (instance is ColumnExpression { IsNullable: true }) { return _sqlExpressionFactory.Case( new[] diff --git a/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryableMethodTranslatingExpressionVisitor.cs index 045bce96c57..f0eec83f85d 100644 --- a/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryableMethodTranslatingExpressionVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; using Microsoft.EntityFrameworkCore.Sqlite.Internal; using Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal; diff --git a/src/EFCore.Sqlite.Core/Query/Internal/SqliteSqlExpressionFactory.cs b/src/EFCore.Sqlite.Core/Query/Internal/SqliteSqlExpressionFactory.cs index c58f11be60b..107da3054a1 100644 --- a/src/EFCore.Sqlite.Core/Query/Internal/SqliteSqlExpressionFactory.cs +++ b/src/EFCore.Sqlite.Core/Query/Internal/SqliteSqlExpressionFactory.cs @@ -44,14 +44,11 @@ public virtual SqlFunctionExpression Strftime( modifiers ??= Enumerable.Empty(); // If the inner call is another strftime then shortcut a double call - if (timestring is SqlFunctionExpression rtrimFunction - && rtrimFunction.Name == "rtrim" + if (timestring is SqlFunctionExpression { Name: "rtrim" } rtrimFunction && rtrimFunction.Arguments!.Count == 2 - && rtrimFunction.Arguments[0] is SqlFunctionExpression rtrimFunction2 - && rtrimFunction2.Name == "rtrim" + && rtrimFunction.Arguments[0] is SqlFunctionExpression { Name: "rtrim" } rtrimFunction2 && rtrimFunction2.Arguments!.Count == 2 - && rtrimFunction2.Arguments[0] is SqlFunctionExpression strftimeFunction - && strftimeFunction.Name == "strftime" + && rtrimFunction2.Arguments[0] is SqlFunctionExpression { Name: "strftime" } strftimeFunction && strftimeFunction.Arguments!.Count > 1) { // Use its timestring parameter directly in place of ours @@ -61,8 +58,7 @@ public virtual SqlFunctionExpression Strftime( modifiers = strftimeFunction.Arguments.Skip(2).Concat(modifiers); } - if (timestring is SqlFunctionExpression dateFunction - && dateFunction.Name == "date") + if (timestring is SqlFunctionExpression { Name: "date" } dateFunction) { timestring = dateFunction.Arguments![0]; modifiers = dateFunction.Arguments.Skip(1).Concat(modifiers); @@ -93,8 +89,7 @@ public virtual SqlFunctionExpression Date( { modifiers ??= Enumerable.Empty(); - if (timestring is SqlFunctionExpression dateFunction - && dateFunction.Name == "date") + if (timestring is SqlFunctionExpression { Name: "date" } dateFunction) { timestring = dateFunction.Arguments![0]; modifiers = dateFunction.Arguments.Skip(1).Concat(modifiers); diff --git a/src/EFCore.Sqlite.Core/Query/Internal/SqliteSqlTranslatingExpressionVisitor.cs b/src/EFCore.Sqlite.Core/Query/Internal/SqliteSqlTranslatingExpressionVisitor.cs index 3922b27e64f..a124b5213c1 100644 --- a/src/EFCore.Sqlite.Core/Query/Internal/SqliteSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.Sqlite.Core/Query/Internal/SqliteSqlTranslatingExpressionVisitor.cs @@ -119,8 +119,7 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) return QueryCompilationContext.NotTranslatedExpression; } - if (visitedExpression is SqlUnaryExpression sqlUnary - && sqlUnary.OperatorType == ExpressionType.Negate) + if (visitedExpression is SqlUnaryExpression { OperatorType: ExpressionType.Negate } sqlUnary) { var operandType = GetProviderType(sqlUnary.Operand); if (operandType == typeof(decimal)) diff --git a/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs b/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs index 7b8e61dc4ce..7a4fc2c378f 100644 --- a/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs +++ b/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs @@ -342,7 +342,7 @@ ORDER BY "cid" string? collation = null; var autoIncrement = 0; if (connection is SqliteConnection sqliteConnection - && !(table is DatabaseView)) + && table is not DatabaseView) { var db = sqliteConnection.Handle; var rc = sqlite3_table_column_metadata( diff --git a/src/EFCore.Sqlite.Core/Storage/Internal/SqliteJsonTypeMapping.cs b/src/EFCore.Sqlite.Core/Storage/Internal/SqliteJsonTypeMapping.cs index 61bdeea495f..372e1e06fed 100644 --- a/src/EFCore.Sqlite.Core/Storage/Internal/SqliteJsonTypeMapping.cs +++ b/src/EFCore.Sqlite.Core/Storage/Internal/SqliteJsonTypeMapping.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Data; using System.Text.Json; namespace Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal; diff --git a/src/EFCore/ChangeTracking/Internal/ChangeDetector.cs b/src/EFCore/ChangeTracking/Internal/ChangeDetector.cs index fd80af87197..79f7abdbf8d 100644 --- a/src/EFCore/ChangeTracking/Internal/ChangeDetector.cs +++ b/src/EFCore/ChangeTracking/Internal/ChangeDetector.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.ChangeTracking.Internal; diff --git a/src/EFCore/ChangeTracking/Internal/EntityGraphAttacher.cs b/src/EFCore/ChangeTracking/Internal/EntityGraphAttacher.cs index ba10d87d7d9..831f336cfd2 100644 --- a/src/EFCore/ChangeTracking/Internal/EntityGraphAttacher.cs +++ b/src/EFCore/ChangeTracking/Internal/EntityGraphAttacher.cs @@ -176,8 +176,7 @@ private static void SetReferenceLoaded( EntityEntryGraphNode<(EntityState TargetState, EntityState StoreGenTargetState, bool Force)> node) { var inboundNavigation = node.InboundNavigation; - if (inboundNavigation != null - && !inboundNavigation.IsCollection) + if (inboundNavigation is { IsCollection: false }) { node.SourceEntry!.GetInfrastructure().SetIsLoaded(inboundNavigation); } diff --git a/src/EFCore/ChangeTracking/Internal/EntityReferenceMap.cs b/src/EFCore/ChangeTracking/Internal/EntityReferenceMap.cs index 804b1cd9ec0..a77de1f1f43 100644 --- a/src/EFCore/ChangeTracking/Internal/EntityReferenceMap.cs +++ b/src/EFCore/ChangeTracking/Internal/EntityReferenceMap.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; -using Microsoft.EntityFrameworkCore.Internal; namespace Microsoft.EntityFrameworkCore.ChangeTracking.Internal; @@ -385,8 +384,7 @@ public virtual IEnumerable GetNonDeletedEntities() { // Perf sensitive - if (_addedReferenceMap != null - && _addedReferenceMap.Count > 0) + if (_addedReferenceMap is { Count: > 0 }) { foreach (var entry in _addedReferenceMap.Values) { @@ -397,8 +395,7 @@ public virtual IEnumerable GetNonDeletedEntities() } } - if (_modifiedReferenceMap != null - && _modifiedReferenceMap.Count > 0) + if (_modifiedReferenceMap is { Count: > 0 }) { foreach (var entry in _modifiedReferenceMap.Values) { @@ -409,8 +406,7 @@ public virtual IEnumerable GetNonDeletedEntities() } } - if (_unchangedReferenceMap != null - && _unchangedReferenceMap.Count > 0) + if (_unchangedReferenceMap is { Count: > 0 }) { foreach (var entry in _unchangedReferenceMap.Values) { @@ -421,8 +417,7 @@ public virtual IEnumerable GetNonDeletedEntities() } } - if (_sharedTypeReferenceMap != null - && _sharedTypeReferenceMap.Count > 0) + if (_sharedTypeReferenceMap is { Count: > 0 }) { foreach (var subMap in _sharedTypeReferenceMap.Values) { diff --git a/src/EFCore/ChangeTracking/Internal/IdentityMap.cs b/src/EFCore/ChangeTracking/Internal/IdentityMap.cs index 1e4af44a629..660a0d7d36a 100644 --- a/src/EFCore/ChangeTracking/Internal/IdentityMap.cs +++ b/src/EFCore/ChangeTracking/Internal/IdentityMap.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.ChangeTracking.Internal; diff --git a/src/EFCore/ChangeTracking/Internal/InternalEntityEntry.cs b/src/EFCore/ChangeTracking/Internal/InternalEntityEntry.cs index 6a8b8c98b5b..9fa4eccb2ba 100644 --- a/src/EFCore/ChangeTracking/Internal/InternalEntityEntry.cs +++ b/src/EFCore/ChangeTracking/Internal/InternalEntityEntry.cs @@ -1035,7 +1035,7 @@ public bool RemoveFromCollection(INavigationBase navigationBase, object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public object? GetCurrentValue(IPropertyBase propertyBase) - => !(propertyBase is IProperty property) || !IsConceptualNull(property) + => propertyBase is not IProperty property || !IsConceptualNull(property) ? this[propertyBase] : null; @@ -1046,7 +1046,7 @@ public bool RemoveFromCollection(INavigationBase navigationBase, object value) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public object? GetPreStoreGeneratedCurrentValue(IPropertyBase propertyBase) - => !(propertyBase is IProperty property) || !IsConceptualNull(property) + => propertyBase is not IProperty property || !IsConceptualNull(property) ? ReadPropertyValue(propertyBase) : null; @@ -1401,12 +1401,9 @@ private void SetProperty( } } - if (propertyBase is INavigationBase navigation) + if (propertyBase is INavigationBase { IsCollection: false } navigation) { - if (!navigation.IsCollection) - { - SetIsLoaded(navigation, value != null); - } + SetIsLoaded(navigation, value != null); } StateManager.InternalEntityEntryNotifier.PropertyChanged(this, propertyBase, setModified); @@ -1822,8 +1819,7 @@ public void HandleINotifyPropertyChanging( { StateManager.InternalEntityEntryNotifier.PropertyChanging(this, propertyBase); - if (propertyBase is INavigationBase navigation - && navigation.IsCollection + if (propertyBase is INavigationBase { IsCollection: true } navigation && GetCurrentValue(propertyBase) != null) { StateManager.Dependencies.InternalEntityEntrySubscriber.UnsubscribeCollectionChanged(this, navigation); @@ -1845,8 +1841,7 @@ public void HandleINotifyPropertyChanged( { StateManager.InternalEntityEntryNotifier.PropertyChanged(this, propertyBase, setModified: true); - if (propertyBase is INavigationBase navigation - && navigation.IsCollection + if (propertyBase is INavigationBase { IsCollection: true } navigation && GetCurrentValue(propertyBase) != null) { StateManager.Dependencies.InternalEntityEntrySubscriber.SubscribeCollectionChanged(this, navigation); diff --git a/src/EFCore/ChangeTracking/Internal/KeyPropagator.cs b/src/EFCore/ChangeTracking/Internal/KeyPropagator.cs index 7cedc30df75..5069c7bc6e5 100644 --- a/src/EFCore/ChangeTracking/Internal/KeyPropagator.cs +++ b/src/EFCore/ChangeTracking/Internal/KeyPropagator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.ChangeTracking.Internal; diff --git a/src/EFCore/ChangeTracking/Internal/RelationshipsSnapshot.cs b/src/EFCore/ChangeTracking/Internal/RelationshipsSnapshot.cs index 0808c76618d..257c447fe90 100644 --- a/src/EFCore/ChangeTracking/Internal/RelationshipsSnapshot.cs +++ b/src/EFCore/ChangeTracking/Internal/RelationshipsSnapshot.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.ChangeTracking.Internal; @@ -29,8 +28,7 @@ public void SetValue(IPropertyBase propertyBase, object? value) { if (value == null) { - if (propertyBase is IProperty property - && !property.IsNullable) + if (propertyBase is IProperty { IsNullable: false }) { return; } diff --git a/src/EFCore/ChangeTracking/Internal/SimplePrincipalKeyValueFactory.cs b/src/EFCore/ChangeTracking/Internal/SimplePrincipalKeyValueFactory.cs index c3dc0865d70..69e9f2a3883 100644 --- a/src/EFCore/ChangeTracking/Internal/SimplePrincipalKeyValueFactory.cs +++ b/src/EFCore/ChangeTracking/Internal/SimplePrincipalKeyValueFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections; using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Metadata.Internal; diff --git a/src/EFCore/ChangeTracking/Internal/StateManager.cs b/src/EFCore/ChangeTracking/Internal/StateManager.cs index f857b68bd28..2fbdcb43c89 100644 --- a/src/EFCore/ChangeTracking/Internal/StateManager.cs +++ b/src/EFCore/ChangeTracking/Internal/StateManager.cs @@ -694,7 +694,7 @@ public virtual void Unsubscribe(bool resetting) { disposable.Dispose(); } - else if (!(service is IInjectableService detachable) + else if (service is not IInjectableService detachable || detachable.Detaching(Context, entry.Entity)) { entry[serviceProperty] = null; diff --git a/src/EFCore/ChangeTracking/ReferenceEntry.cs b/src/EFCore/ChangeTracking/ReferenceEntry.cs index c2e53ffa27a..6dc7c55eb1a 100644 --- a/src/EFCore/ChangeTracking/ReferenceEntry.cs +++ b/src/EFCore/ChangeTracking/ReferenceEntry.cs @@ -59,8 +59,7 @@ public ReferenceEntry(InternalEntityEntry internalEntry, INavigation navigation) private void LocalDetectChanges() { - if (!(Metadata is INavigation navigation - && navigation.IsOnDependent)) + if (Metadata is not INavigation { IsOnDependent: true }) { var target = GetTargetEntry(); if (target != null) diff --git a/src/EFCore/DbSet.cs b/src/EFCore/DbSet.cs index 63e084ea9b8..10f4dcc0e1f 100644 --- a/src/EFCore/DbSet.cs +++ b/src/EFCore/DbSet.cs @@ -4,7 +4,6 @@ using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; -using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore; diff --git a/src/EFCore/Diagnostics/Internal/DiagnosticsLogger.cs b/src/EFCore/Diagnostics/Internal/DiagnosticsLogger.cs index 97538520f87..babebe150d7 100644 --- a/src/EFCore/Diagnostics/Internal/DiagnosticsLogger.cs +++ b/src/EFCore/Diagnostics/Internal/DiagnosticsLogger.cs @@ -94,8 +94,7 @@ public virtual bool ShouldLogSensitiveData() { var options = Options; - if (options.IsSensitiveDataLoggingEnabled - && !options.IsSensitiveDataLoggingWarned) + if (options is { IsSensitiveDataLoggingEnabled: true, IsSensitiveDataLoggingWarned: false }) { this.SensitiveDataLoggingEnabledWarning(); diff --git a/src/EFCore/EF.CompileAsyncQuery.cs b/src/EFCore/EF.CompileAsyncQuery.cs index 290b8eb8af7..d199e5ee2f6 100644 --- a/src/EFCore/EF.CompileAsyncQuery.cs +++ b/src/EFCore/EF.CompileAsyncQuery.cs @@ -1,10 +1,9 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Threading; @@ -23,9 +22,7 @@ public static partial class EF /// The query result type. /// The LINQ query expression. /// A delegate that can be invoked to execute the compiled query. - public static Func> CompileAsyncQuery< - TContext, - [DynamicallyAccessedMembers(IEntityType.DynamicallyAccessedMemberTypes)] TResult>( + public static Func> CompileAsyncQuery( Expression>> queryExpression) where TContext : DbContext where TResult : class diff --git a/src/EFCore/EF.CompileAsyncQuery.tt b/src/EFCore/EF.CompileAsyncQuery.tt index bf50717ae92..2974309471b 100644 --- a/src/EFCore/EF.CompileAsyncQuery.tt +++ b/src/EFCore/EF.CompileAsyncQuery.tt @@ -1,5 +1,4 @@ <#@ assembly name="System.Core" #> -<#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.Linq" #> // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. diff --git a/src/EFCore/EF.CompileQuery.cs b/src/EFCore/EF.CompileQuery.cs index 45b0064a96f..12435aae6da 100644 --- a/src/EFCore/EF.CompileQuery.cs +++ b/src/EFCore/EF.CompileQuery.cs @@ -2,11 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.Internal; namespace Microsoft.EntityFrameworkCore diff --git a/src/EFCore/EF.CompileQuery.tt b/src/EFCore/EF.CompileQuery.tt index b3465888125..f4d50c4c7f7 100644 --- a/src/EFCore/EF.CompileQuery.tt +++ b/src/EFCore/EF.CompileQuery.tt @@ -1,5 +1,4 @@ <#@ assembly name="System.Core" #> -<#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.Linq" #> // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. diff --git a/src/EFCore/Extensions/Internal/TypeExtensions.cs b/src/EFCore/Extensions/Internal/TypeExtensions.cs index 3327bf60bc6..066575aed08 100644 --- a/src/EFCore/Extensions/Internal/TypeExtensions.cs +++ b/src/EFCore/Extensions/Internal/TypeExtensions.cs @@ -68,8 +68,7 @@ public static string GenerateParameterName(this Type type) pi => pi.Name == defaultPropertyAttribute.MemberName && pi.IsIndexerProperty() - && pi.SetMethod?.GetParameters() is ParameterInfo[] parameters - && parameters.Length == 2 + && pi.SetMethod?.GetParameters() is ParameterInfo[] { Length: 2 } parameters && parameters[0].ParameterType == typeof(string)); } } diff --git a/src/EFCore/Infrastructure/CoreOptionsExtension.cs b/src/EFCore/Infrastructure/CoreOptionsExtension.cs index 8749b079ba7..c3f39c0a2e3 100644 --- a/src/EFCore/Infrastructure/CoreOptionsExtension.cs +++ b/src/EFCore/Infrastructure/CoreOptionsExtension.cs @@ -562,7 +562,7 @@ public virtual void ApplyServices(IServiceCollection services) /// The options being validated. public virtual void Validate(IDbContextOptions options) { - if (MaxPoolSize.HasValue && MaxPoolSize <= 0) + if (MaxPoolSize is <= 0) { throw new ArgumentOutOfRangeException(nameof(MaxPoolSize), CoreStrings.InvalidPoolSize); } diff --git a/src/EFCore/Infrastructure/DbSetProperty.cs b/src/EFCore/Infrastructure/DbSetProperty.cs index ddbe4c2664e..01481381ccd 100644 --- a/src/EFCore/Infrastructure/DbSetProperty.cs +++ b/src/EFCore/Infrastructure/DbSetProperty.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; -using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/src/EFCore/Infrastructure/ModelValidator.cs b/src/EFCore/Infrastructure/ModelValidator.cs index 3e732be0f2d..c014af1e32c 100644 --- a/src/EFCore/Infrastructure/ModelValidator.cs +++ b/src/EFCore/Infrastructure/ModelValidator.cs @@ -305,7 +305,7 @@ protected virtual void ValidateIgnoredMembers( IModel model, IDiagnosticsLogger logger) { - if (!(model is IConventionModel conventionModel)) + if (model is not IConventionModel conventionModel) { return; } @@ -521,8 +521,7 @@ private static void ValidateClrInheritance( return; } - if (entityType.HasSharedClrType - && entityType.BaseType != null) + if (entityType is { HasSharedClrType: true, BaseType: not null }) { throw new InvalidOperationException(CoreStrings.SharedTypeDerivedType(entityType.DisplayName())); } @@ -702,8 +701,7 @@ protected virtual void ValidateOwnership( } foreach (var fk in entityType.GetDeclaredForeignKeys().Where( - fk => !fk.IsOwnership - && fk.PrincipalToDependent != null + fk => fk is { IsOwnership: false, PrincipalToDependent: not null } && !Contains(fk.DeclaringEntityType.FindOwnership(), fk))) { throw new InvalidOperationException( @@ -944,9 +942,7 @@ protected virtual void ValidateQueryFilters( var requiredNavigationWithQueryFilter = entityType .GetNavigations() .FirstOrDefault( - n => !n.IsCollection - && n.ForeignKey.IsRequired - && n.IsOnDependent + n => n is { IsCollection: false, ForeignKey.IsRequired: true, IsOnDependent: true } && n.ForeignKey.PrincipalEntityType.GetRootType().GetQueryFilter() != null && n.ForeignKey.DeclaringEntityType.GetRootType().GetQueryFilter() == null); diff --git a/src/EFCore/Internal/DbContextFactorySource.cs b/src/EFCore/Internal/DbContextFactorySource.cs index 29205cc99f7..4035d5ac130 100644 --- a/src/EFCore/Internal/DbContextFactorySource.cs +++ b/src/EFCore/Internal/DbContextFactorySource.cs @@ -35,7 +35,7 @@ private static Func, TContext> Crea { var constructors = typeof(TContext).GetTypeInfo().DeclaredConstructors - .Where(c => !c.IsStatic && c.IsPublic && c.GetParameters().Length != 0) + .Where(c => c is { IsStatic: false, IsPublic: true } && c.GetParameters().Length != 0) .ToArray(); if (constructors.Length == 1) diff --git a/src/EFCore/Internal/DbContextPool.cs b/src/EFCore/Internal/DbContextPool.cs index 60fa35b627a..7a39abb8555 100644 --- a/src/EFCore/Internal/DbContextPool.cs +++ b/src/EFCore/Internal/DbContextPool.cs @@ -52,7 +52,7 @@ public DbContextPool(DbContextOptions options, IServiceProvider? servi private static Func CreateActivator(DbContextOptions options, IServiceProvider? serviceProvider) { var constructors = typeof(TContext).GetTypeInfo().DeclaredConstructors - .Where(c => !c.IsStatic && c.IsPublic && c.GetParameters().Length > 0).ToArray(); + .Where(c => c is { IsStatic: false, IsPublic: true } && c.GetParameters().Length > 0).ToArray(); if (constructors.Length == 1 && constructors[0].GetParameters() is { } parameters diff --git a/src/EFCore/Internal/EntityFinderSource.cs b/src/EFCore/Internal/EntityFinderSource.cs index 23e0822bb56..64842f04393 100644 --- a/src/EFCore/Internal/EntityFinderSource.cs +++ b/src/EFCore/Internal/EntityFinderSource.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Concurrent; -using System.Diagnostics.CodeAnalysis; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; diff --git a/src/EFCore/Internal/IDbSetCache.cs b/src/EFCore/Internal/IDbSetCache.cs index c16c6b97d9c..f988750347e 100644 --- a/src/EFCore/Internal/IDbSetCache.cs +++ b/src/EFCore/Internal/IDbSetCache.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; -using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.Internal; diff --git a/src/EFCore/Internal/IDbSetSource.cs b/src/EFCore/Internal/IDbSetSource.cs index 8081768b320..dda703c0107 100644 --- a/src/EFCore/Internal/IDbSetSource.cs +++ b/src/EFCore/Internal/IDbSetSource.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; -using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.Internal; diff --git a/src/EFCore/Metadata/Builders/ReferenceNavigationBuilder.cs b/src/EFCore/Metadata/Builders/ReferenceNavigationBuilder.cs index 8438e96fde3..1256a62347a 100644 --- a/src/EFCore/Metadata/Builders/ReferenceNavigationBuilder.cs +++ b/src/EFCore/Metadata/Builders/ReferenceNavigationBuilder.cs @@ -157,8 +157,7 @@ private InternalForeignKeyBuilder WithManyBuilder(MemberIdentity collection) var builder = Builder.HasEntityTypes( (EntityType)RelatedEntityType, (EntityType)DeclaringEntityType, ConfigurationSource.Explicit)!; var collectionName = collection.Name; - if (builder.Metadata.IsUnique - && builder.Metadata.PrincipalToDependent != null + if (builder.Metadata is { IsUnique: true, PrincipalToDependent: not null } && builder.Metadata.GetPrincipalToDependentConfigurationSource() == ConfigurationSource.Explicit && collectionName != null) { diff --git a/src/EFCore/Metadata/Conventions/DiscriminatorConvention.cs b/src/EFCore/Metadata/Conventions/DiscriminatorConvention.cs index ec66c77eb03..7d4cc93f46c 100644 --- a/src/EFCore/Metadata/Conventions/DiscriminatorConvention.cs +++ b/src/EFCore/Metadata/Conventions/DiscriminatorConvention.cs @@ -38,9 +38,7 @@ public virtual void ProcessEntityTypeBaseTypeChanged( IConventionEntityType? oldBaseType, IConventionContext context) { - if (oldBaseType != null - && oldBaseType.IsInModel - && oldBaseType.BaseType == null + if (oldBaseType is { IsInModel: true, BaseType: null } && !oldBaseType.GetDirectlyDerivedTypes().Any()) { oldBaseType.Builder.HasNoDiscriminator(); diff --git a/src/EFCore/Metadata/Conventions/ForeignKeyAttributeConvention.cs b/src/EFCore/Metadata/Conventions/ForeignKeyAttributeConvention.cs index c67c84c8eab..357d13266dd 100644 --- a/src/EFCore/Metadata/Conventions/ForeignKeyAttributeConvention.cs +++ b/src/EFCore/Metadata/Conventions/ForeignKeyAttributeConvention.cs @@ -505,8 +505,7 @@ public virtual void ProcessSkipNavigationForeignKeyChanged( IConventionForeignKey? oldForeignKey, IConventionContext context) { - if (foreignKey != null - && foreignKey.IsInModel) + if (foreignKey is { IsInModel: true }) { var fkPropertiesToSet = FindCandidateDependentPropertiesThroughNavigation(skipNavigationBuilder.Metadata); if (fkPropertiesToSet != null) diff --git a/src/EFCore/Metadata/Conventions/ForeignKeyPropertyDiscoveryConvention.cs b/src/EFCore/Metadata/Conventions/ForeignKeyPropertyDiscoveryConvention.cs index 4bbe9fd97da..3b183980950 100644 --- a/src/EFCore/Metadata/Conventions/ForeignKeyPropertyDiscoveryConvention.cs +++ b/src/EFCore/Metadata/Conventions/ForeignKeyPropertyDiscoveryConvention.cs @@ -173,9 +173,8 @@ private IConventionForeignKeyBuilder ProcessForeignKey( invertible = false; } else if (ConfigurationSource.Convention.Overrides(foreignKey.GetPrincipalEndConfigurationSource()) - && (foreignKey.PrincipalEntityType.FindOwnership() != null - && foreignKey.PrincipalToDependent != null - && foreignKey.DependentToPrincipal == null)) + && foreignKey.PrincipalEntityType.FindOwnership() != null + && foreignKey is { PrincipalToDependent: not null, DependentToPrincipal: null }) { var invertedRelationshipBuilder = relationshipBuilder.HasEntityTypes( foreignKey.DeclaringEntityType, foreignKey.PrincipalEntityType); @@ -761,8 +760,7 @@ public virtual void ProcessKeyRemoved( .SelectMany(t => t.GetDeclaredForeignKeys()).ToList(); foreach (var foreignKey in foreignKeys) { - if ((foreignKey.IsUnique - && foreignKey.DeclaringEntityType.BaseType == null) + if (foreignKey is { IsUnique: true, DeclaringEntityType.BaseType: null } || !foreignKey.IsInModel) { continue; @@ -785,7 +783,7 @@ public virtual void ProcessEntityTypePrimaryKeyChanged( IConventionKey? previousPrimaryKey, IConventionContext context) { - if (newPrimaryKey != null && !newPrimaryKey.IsInModel) + if (newPrimaryKey is { IsInModel: false }) { return; } diff --git a/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ImmediateConventionScope.cs b/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ImmediateConventionScope.cs index 827cea1dbc0..59e76f1ddd7 100644 --- a/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ImmediateConventionScope.cs +++ b/src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ImmediateConventionScope.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Reflection.Emit; -using System.Xml.Linq; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using Microsoft.EntityFrameworkCore.Metadata.Internal; - namespace Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal; public partial class ConventionDispatcher @@ -319,7 +314,7 @@ public IConventionModelBuilder OnModelInitialized(IConventionModelBuilder modelB } } - return newPrimaryKey != null && !newPrimaryKey.IsInModel ? null : newPrimaryKey; + return newPrimaryKey is { IsInModel: false } ? null : newPrimaryKey; } public override IConventionAnnotation? OnEntityTypeAnnotationChanged( @@ -1340,8 +1335,7 @@ public IConventionModelBuilder OnModelInitialized(IConventionModelBuilder modelB return _annotationConventionContext.Result; } #if DEBUG - Check.DebugAssert(propertyBuilder.Metadata.IsInModel - && propertyBuilder.Metadata.DeclaringEntityType.IsInModel + Check.DebugAssert(propertyBuilder.Metadata is { IsInModel: true, DeclaringEntityType.IsInModel: true } && initialValue == propertyBuilder.Metadata[name], $"Convention {propertyConvention.GetType().Name} changed value without terminating"); #endif diff --git a/src/EFCore/Metadata/Conventions/ManyToManyJoinEntityTypeConvention.cs b/src/EFCore/Metadata/Conventions/ManyToManyJoinEntityTypeConvention.cs index fe190bd4be5..6966a4d3fcb 100644 --- a/src/EFCore/Metadata/Conventions/ManyToManyJoinEntityTypeConvention.cs +++ b/src/EFCore/Metadata/Conventions/ManyToManyJoinEntityTypeConvention.cs @@ -99,9 +99,7 @@ protected virtual bool ShouldCreateJoinType(IConventionSkipNavigation skipNaviga var inverseSkipNavigation = skipNavigation.Inverse; return skipNavigation.ForeignKey == null && skipNavigation.IsCollection - && inverseSkipNavigation != null - && inverseSkipNavigation.ForeignKey == null - && inverseSkipNavigation.IsCollection; + && inverseSkipNavigation is { ForeignKey: null, IsCollection: true }; } /// diff --git a/src/EFCore/Metadata/Internal/ClrCollectionAccessorFactory.cs b/src/EFCore/Metadata/Internal/ClrCollectionAccessorFactory.cs index 235726c192a..bc4c47d4501 100644 --- a/src/EFCore/Metadata/Internal/ClrCollectionAccessorFactory.cs +++ b/src/EFCore/Metadata/Internal/ClrCollectionAccessorFactory.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using JetBrains.Annotations; -using Microsoft.EntityFrameworkCore.Internal; namespace Microsoft.EntityFrameworkCore.Metadata.Internal; diff --git a/src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs b/src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs index e64fa4929fc..8a406133a34 100644 --- a/src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs +++ b/src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs @@ -3419,8 +3419,7 @@ private static InternalIndexBuilder DetachIndex(Index indexToDetach) { InternalForeignKeyBuilder? relationship; var existingNavigation = Metadata.FindNavigation(navigation.Name!); - if (existingNavigation != null - && !existingNavigation.IsOnDependent) + if (existingNavigation is { IsOnDependent: false }) { var existingTargetType = existingNavigation.TargetEntityType; if ((targetEntityType.Type == null @@ -3468,8 +3467,9 @@ private static InternalIndexBuilder DetachIndex(Index indexToDetach) var principalBuilder = Metadata.IsInModel ? Metadata.Builder : ownership?.PrincipalEntityType.FindNavigation(ownership.PrincipalToDependent!.Name)?.TargetEntityType is EntityType - target - && target.IsInModel + { + IsInModel: true + } target ? target.Builder : null; @@ -3503,8 +3503,7 @@ private static InternalIndexBuilder DetachIndex(Index indexToDetach) if (relationship is null || !relationship.Metadata.IsInModel) { - if (ownedEntityTypeBuilder.Metadata.IsInModel - && ownedEntityTypeBuilder.Metadata.HasSharedClrType) + if (ownedEntityTypeBuilder.Metadata is { IsInModel: true, HasSharedClrType: true }) { ModelBuilder.HasNoEntityType(ownedEntityTypeBuilder.Metadata, configurationSource); } @@ -3523,8 +3522,7 @@ private static InternalIndexBuilder DetachIndex(Index indexToDetach) { InternalForeignKeyBuilder? relationship; var existingNavigation = Metadata.FindNavigation(navigation.Name!); - if (existingNavigation != null - && !existingNavigation.IsOnDependent) + if (existingNavigation is { IsOnDependent: false }) { var existingTargetType = existingNavigation.TargetEntityType; if (existingTargetType == targetEntityType) @@ -3725,8 +3723,7 @@ private bool RemoveNonOwnershipRelationships(ForeignKey? futureOwnership, Config var incompatibleRelationships = Metadata.GetDerivedTypesInclusive() .SelectMany(t => t.GetDeclaredForeignKeys()) .Where( - fk => !fk.IsOwnership - && fk.PrincipalToDependent != null + fk => fk is { IsOwnership: false, PrincipalToDependent: not null } && !Contains(ownership, fk)) .Concat( Metadata.GetDerivedTypesInclusive() @@ -3945,8 +3942,7 @@ private static bool Contains(IReadOnlyForeignKey? inheritedFk, IReadOnlyForeignK return null; } - if (targetEntityType.IsNamed - && targetEntityType.Type != null) + if (targetEntityType is { IsNamed: true, Type: not null }) { if (configurationSource == ConfigurationSource.Explicit) { diff --git a/src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs b/src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs index 9071a287064..b24fac41ada 100644 --- a/src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs +++ b/src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal; namespace Microsoft.EntityFrameworkCore.Metadata.Internal; @@ -2494,13 +2493,10 @@ private bool CanSetPrincipalKey( ?? newRelationshipBuilder; } else if (!oldRelationshipInverted - && Metadata.GetIsUniqueConfigurationSource() is var isUniqueConfigurationSource - && isUniqueConfigurationSource.HasValue + && Metadata.GetIsUniqueConfigurationSource() is { } isUniqueConfigurationSource && !newRelationshipBuilder.Metadata.GetIsUniqueConfigurationSource().HasValue) { - newRelationshipBuilder = newRelationshipBuilder.IsUnique( - Metadata.IsUnique, - isUniqueConfigurationSource.Value) + newRelationshipBuilder = newRelationshipBuilder.IsUnique(Metadata.IsUnique, isUniqueConfigurationSource) ?? newRelationshipBuilder; } @@ -2521,26 +2517,24 @@ private bool CanSetPrincipalKey( { if (!oldRelationshipInverted) { - if (Metadata.GetIsRequiredConfigurationSource() is var isRequiredConfigurationSource - && isRequiredConfigurationSource.HasValue + if (Metadata.GetIsRequiredConfigurationSource() is { } isRequiredConfigurationSource && !newRelationshipBuilder.Metadata.GetIsRequiredConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsRequired( Metadata.IsRequired, - isRequiredConfigurationSource.Value) + isRequiredConfigurationSource) ?? newRelationshipBuilder; } } else { - if (Metadata.GetIsRequiredDependentConfigurationSource() is var isRequiredDependentConfigurationSource - && isRequiredDependentConfigurationSource.HasValue - && isRequiredDependentConfigurationSource.Value.Overrides(ConfigurationSource.Explicit) + if (Metadata.GetIsRequiredDependentConfigurationSource() is { } isRequiredDependentConfigurationSource + && isRequiredDependentConfigurationSource.Overrides(ConfigurationSource.Explicit) && !newRelationshipBuilder.Metadata.GetIsRequiredConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsRequired( Metadata.IsRequiredDependent, - isRequiredDependentConfigurationSource.Value) + isRequiredDependentConfigurationSource) ?? newRelationshipBuilder; } } @@ -2564,26 +2558,24 @@ private bool CanSetPrincipalKey( { if (!oldRelationshipInverted) { - if (Metadata.GetIsRequiredDependentConfigurationSource() is var isRequiredDependentConfigurationSource - && isRequiredDependentConfigurationSource.HasValue + if (Metadata.GetIsRequiredDependentConfigurationSource() is { } isRequiredDependentConfigurationSource && !newRelationshipBuilder.Metadata.GetIsRequiredDependentConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsRequiredDependent( Metadata.IsRequiredDependent, - isRequiredDependentConfigurationSource.Value) + isRequiredDependentConfigurationSource) ?? newRelationshipBuilder; } } else { - if (Metadata.GetIsRequiredConfigurationSource() is var isRequiredConfigurationSource - && isRequiredConfigurationSource.HasValue - && isRequiredConfigurationSource.Value.Overrides(ConfigurationSource.Explicit) + if (Metadata.GetIsRequiredConfigurationSource() is { } isRequiredConfigurationSource + && isRequiredConfigurationSource.Overrides(ConfigurationSource.Explicit) && !newRelationshipBuilder.Metadata.GetIsRequiredDependentConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsRequiredDependent( Metadata.IsRequired, - isRequiredConfigurationSource.Value) + isRequiredConfigurationSource) ?? newRelationshipBuilder; } } @@ -2604,13 +2596,12 @@ private bool CanSetPrincipalKey( ?? newRelationshipBuilder; } else if (!oldRelationshipInverted - && Metadata.GetDeleteBehaviorConfigurationSource() is var deleteBehaviorConfigurationSource - && deleteBehaviorConfigurationSource.HasValue + && Metadata.GetDeleteBehaviorConfigurationSource() is { } deleteBehaviorConfigurationSource && !newRelationshipBuilder.Metadata.GetDeleteBehaviorConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.OnDelete( Metadata.DeleteBehavior, - deleteBehaviorConfigurationSource.Value) + deleteBehaviorConfigurationSource) ?? newRelationshipBuilder; } @@ -2714,12 +2705,11 @@ private bool CanSetPrincipalKey( ?? newRelationshipBuilder; } else if (!oldRelationshipInverted - && Metadata.GetIsOwnershipConfigurationSource() is var getIsOwnershipConfigurationSource - && getIsOwnershipConfigurationSource.HasValue) + && Metadata.GetIsOwnershipConfigurationSource() is { } getIsOwnershipConfigurationSource) { newRelationshipBuilder = newRelationshipBuilder.IsOwnership( Metadata.IsOwnership, - getIsOwnershipConfigurationSource.Value) + getIsOwnershipConfigurationSource) ?? newRelationshipBuilder; } @@ -3264,8 +3254,7 @@ private static InternalForeignKeyBuilder MergeFacetsFrom(Navigation newNavigatio if (configurationSource != ConfigurationSource.Explicit && (shouldResetToPrincipal || shouldResetToDependent) && (navigationToPrincipal?.Name is null || navigationToDependent?.Name is null) - && candidateRelationship.Metadata.DependentToPrincipal != null - && candidateRelationship.Metadata.PrincipalToDependent != null + && candidateRelationship.Metadata is { DependentToPrincipal: not null, PrincipalToDependent: not null } && ((!candidateRelationshipInverted && principalEntityType.IsAssignableFrom(candidateRelationship.Metadata.PrincipalEntityType) && dependentEntityType.IsAssignableFrom(candidateRelationship.Metadata.DeclaringEntityType)) @@ -3516,8 +3505,7 @@ private static IReadOnlyList FindRelationships( { var ownership = Metadata.PrincipalEntityType.FindOwnership(); if (Metadata.PrincipalEntityType.HasSharedClrType - && ownership != null - && ownership.PrincipalEntityType.IsInModel) + && ownership is { PrincipalEntityType.IsInModel: true }) { principalEntityType = model.FindEntityType( Metadata.PrincipalEntityType.ClrType, @@ -3565,8 +3553,7 @@ private static IReadOnlyList FindRelationships( if (Metadata.DeclaringEntityType.HasSharedClrType || model.IsShared(Metadata.DeclaringEntityType.ClrType)) { - if (Metadata.IsOwnership - && Metadata.PrincipalToDependent != null) + if (Metadata is { IsOwnership: true, PrincipalToDependent: not null }) { var name = principalEntityType.GetOwnedName( Metadata.DeclaringEntityType.ShortName(), Metadata.PrincipalToDependent.Name); diff --git a/src/EFCore/Metadata/Internal/Model.cs b/src/EFCore/Metadata/Internal/Model.cs index e05b93e0236..9747de2a6b6 100644 --- a/src/EFCore/Metadata/Internal/Model.cs +++ b/src/EFCore/Metadata/Internal/Model.cs @@ -976,8 +976,7 @@ private Model MakeReadonly() /// The MethodInfo to check for. public virtual bool IsIndexerMethod(MethodInfo methodInfo) => !methodInfo.IsStatic - && methodInfo.IsSpecialName - && methodInfo.DeclaringType != null + && methodInfo is { IsSpecialName: true, DeclaringType: not null } && FindIndexerPropertyInfo(methodInfo.DeclaringType) is PropertyInfo indexerProperty && (methodInfo == indexerProperty.GetMethod || methodInfo == indexerProperty.SetMethod); diff --git a/src/EFCore/Metadata/Internal/Property.cs b/src/EFCore/Metadata/Internal/Property.cs index bd79039e222..a5248557df7 100644 --- a/src/EFCore/Metadata/Internal/Property.cs +++ b/src/EFCore/Metadata/Internal/Property.cs @@ -412,7 +412,7 @@ private object? DefaultSentinel /// public virtual int? SetPrecision(int? precision, ConfigurationSource configurationSource) { - if (precision != null && precision < 0) + if (precision is < 0) { throw new ArgumentOutOfRangeException(nameof(precision)); } diff --git a/src/EFCore/Metadata/Internal/PropertyConfiguration.cs b/src/EFCore/Metadata/Internal/PropertyConfiguration.cs index f760e2c73a4..445873011d1 100644 --- a/src/EFCore/Metadata/Internal/PropertyConfiguration.cs +++ b/src/EFCore/Metadata/Internal/PropertyConfiguration.cs @@ -172,7 +172,7 @@ public virtual void SetIsUnicode(bool? unicode) /// public virtual void SetPrecision(int? precision) { - if (precision != null && precision < 0) + if (precision is < 0) { throw new ArgumentOutOfRangeException(nameof(precision)); } diff --git a/src/EFCore/Metadata/RuntimeModel.cs b/src/EFCore/Metadata/RuntimeModel.cs index 7af0aa412c3..60b1161c02a 100644 --- a/src/EFCore/Metadata/RuntimeModel.cs +++ b/src/EFCore/Metadata/RuntimeModel.cs @@ -253,8 +253,7 @@ ChangeTrackingStrategy IReadOnlyModel.GetChangeTrackingStrategy() [DebuggerStepThrough] bool IModel.IsIndexerMethod(MethodInfo methodInfo) => !methodInfo.IsStatic - && methodInfo.IsSpecialName - && methodInfo.DeclaringType != null + && methodInfo is { IsSpecialName: true, DeclaringType: not null } && FindIndexerPropertyInfo(methodInfo.DeclaringType) is PropertyInfo indexerProperty && (methodInfo == indexerProperty.GetMethod || methodInfo == indexerProperty.SetMethod); diff --git a/src/EFCore/Metadata/RuntimeServiceProperty.cs b/src/EFCore/Metadata/RuntimeServiceProperty.cs index 307d050026f..993f359298d 100644 --- a/src/EFCore/Metadata/RuntimeServiceProperty.cs +++ b/src/EFCore/Metadata/RuntimeServiceProperty.cs @@ -3,7 +3,6 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Internal; -using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.Metadata; diff --git a/src/EFCore/ModelBuilder.cs b/src/EFCore/ModelBuilder.cs index f3a20afa408..39c8aec7af4 100644 --- a/src/EFCore/ModelBuilder.cs +++ b/src/EFCore/ModelBuilder.cs @@ -512,8 +512,7 @@ public virtual ModelBuilder ApplyConfigurationsFromAssembly( var applyEntityConfigurationMethod = typeof(ModelBuilder) .GetMethods() .Single( - e => e.Name == nameof(ApplyConfiguration) - && e.ContainsGenericParameters + e => e is { Name: nameof(ApplyConfiguration), ContainsGenericParameters: true } && e.GetParameters().SingleOrDefault()?.ParameterType.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>)); diff --git a/src/EFCore/Query/EntityShaperExpression.cs b/src/EFCore/Query/EntityShaperExpression.cs index 64ff4d19a5f..8a15f0fea34 100644 --- a/src/EFCore/Query/EntityShaperExpression.cs +++ b/src/EFCore/Query/EntityShaperExpression.cs @@ -161,7 +161,7 @@ protected virtual LambdaExpression GenerateMaterializationCondition(IEntityType p => NotEqual( valueBufferParameter.CreateValueBufferReadValueExpression(typeof(object), p.GetIndex(), p), Constant(null))) - .Aggregate((a, b) => OrElse(a, b)), + .Aggregate(OrElse), body, Default(typeof(IEntityType))); } diff --git a/src/EFCore/Query/ExpressionPrinter.cs b/src/EFCore/Query/ExpressionPrinter.cs index da2ee33dfcf..dfee02d5868 100644 --- a/src/EFCore/Query/ExpressionPrinter.cs +++ b/src/EFCore/Query/ExpressionPrinter.cs @@ -453,8 +453,7 @@ protected override Expression VisitConstant(ConstantExpression constantExpressio void PrintValue(object? value) { - if (value is IEnumerable enumerable - && !(value is string)) + if (value is IEnumerable enumerable and not string) { _stringBuilder.Append(value.GetType().ShortDisplayName() + " { "); @@ -526,10 +525,7 @@ protected override Expression VisitLambda(Expression lambdaExpression) { var parameterName = parameter.Name; - if (!_parametersInScope.ContainsKey(parameter)) - { - _parametersInScope.Add(parameter, parameterName); - } + _parametersInScope.TryAdd(parameter, parameterName); Visit(parameter); diff --git a/src/EFCore/Query/Internal/EntityQueryProvider.cs b/src/EFCore/Query/Internal/EntityQueryProvider.cs index c01246faeaf..8b304646ffe 100644 --- a/src/EFCore/Query/Internal/EntityQueryProvider.cs +++ b/src/EFCore/Query/Internal/EntityQueryProvider.cs @@ -13,7 +13,7 @@ public class EntityQueryProvider : IAsyncQueryProvider { private static readonly MethodInfo GenericCreateQueryMethod = typeof(EntityQueryProvider).GetRuntimeMethods() - .Single(m => (m.Name == "CreateQuery") && m.IsGenericMethod); + .Single(m => m is { Name: "CreateQuery", IsGenericMethod: true }); private readonly MethodInfo _genericExecuteMethod; @@ -30,7 +30,7 @@ public EntityQueryProvider(IQueryCompiler queryCompiler) _queryCompiler = queryCompiler; _genericExecuteMethod = queryCompiler.GetType() .GetRuntimeMethods() - .Single(m => (m.Name == "Execute") && m.IsGenericMethod); + .Single(m => m is { Name: "Execute", IsGenericMethod: true }); } /// diff --git a/src/EFCore/Query/Internal/InvocationExpressionRemovingExpressionVisitor.cs b/src/EFCore/Query/Internal/InvocationExpressionRemovingExpressionVisitor.cs index 5cadb23c441..736989c79ed 100644 --- a/src/EFCore/Query/Internal/InvocationExpressionRemovingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/InvocationExpressionRemovingExpressionVisitor.cs @@ -30,8 +30,7 @@ protected override Expression VisitInvocation(InvocationExpression invocationExp private static Expression StripTrivialConversions(Expression expression) { - while (expression is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Convert + while (expression is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression && expression.Type == unaryExpression.Operand.Type && unaryExpression.Method == null) { diff --git a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs index 82c42039939..4b23425bb6a 100644 --- a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs +++ b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs @@ -427,7 +427,7 @@ outerKey is NewArrayExpression newArrayExpression return Expression.NotEqual(left, Expression.Constant(null, left.Type)); }) - .Aggregate((l, r) => Expression.AndAlso(l, r)) + .Aggregate(Expression.AndAlso) : Expression.NotEqual(outerKey, Expression.Constant(null, outerKey.Type)), ExpressionExtensions.CreateEqualsExpression(outerKey, innerKey)); @@ -773,8 +773,7 @@ private Expression ExpandIncludesHelper(Expression root, EntityReference entityR if (!_ignoreAutoIncludes && navigationBase is INavigation && navigationBase.Inverse is INavigation inverseNavigation - && subquery is MethodCallExpression subqueryMethodCallExpression - && subqueryMethodCallExpression.Method.IsGenericMethod) + && subquery is MethodCallExpression { Method.IsGenericMethod: true } subqueryMethodCallExpression) { EntityReference? innerEntityReference = null; if (subqueryMethodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.Where @@ -804,15 +803,16 @@ private Expression ExpandIncludesHelper(Expression root, EntityReference entityR var filterExpression = entityReference.IncludePaths[navigationBase].FilterExpression; if (_queryStateManager && navigationBase is ISkipNavigation skipNavigation - && subquery is MethodCallExpression joinMethodCallExpression - && joinMethodCallExpression.Method.IsGenericMethod + && subquery is MethodCallExpression { Method.IsGenericMethod: true } joinMethodCallExpression && joinMethodCallExpression.Method.GetGenericMethodDefinition() == (skipNavigation.Inverse.ForeignKey.IsRequired ? QueryableMethods.Join : QueryableExtensions.LeftJoinMethodInfo) - && joinMethodCallExpression.Arguments[4] is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Quote - && unaryExpression.Operand is LambdaExpression resultSelectorLambda + && joinMethodCallExpression.Arguments[4] is UnaryExpression + { + NodeType: ExpressionType.Quote, + Operand: LambdaExpression resultSelectorLambda + } && resultSelectorLambda.Body == resultSelectorLambda.Parameters[1]) { var joinParameter = resultSelectorLambda.Parameters[0]; @@ -1236,8 +1236,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp { var method = methodCallExpression.Method; if (method.Name == nameof(object.Equals) - && methodCallExpression.Object != null - && methodCallExpression.Arguments.Count == 1 + && methodCallExpression is { Object: not null, Arguments.Count: 1 } && TryRemoveNavigationComparison( ExpressionType.Equal, methodCallExpression.Object, methodCallExpression.Arguments[0], out var result)) { @@ -1317,11 +1316,9 @@ private static Expression ProcessNavigationPath(Expression expression) { switch (expression) { - case MemberExpression memberExpression - when memberExpression.Expression != null: + case MemberExpression { Expression: not null } memberExpression: var innerExpression = ProcessNavigationPath(memberExpression.Expression); - if (innerExpression is NavigationDataExpression navigationDataExpression - && navigationDataExpression.EntityType != null) + if (innerExpression is NavigationDataExpression { EntityType: not null } navigationDataExpression) { var navigation = navigationDataExpression.EntityType.FindNavigation(memberExpression.Member); if (navigation != null) diff --git a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs index 923b9da71ce..c0725252271 100644 --- a/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.cs @@ -104,9 +104,8 @@ public virtual Expression Expand(Expression query) if (result is GroupByNavigationExpansionExpression groupByNavigationExpansionExpression) { - if (!(groupByNavigationExpansionExpression.Source is MethodCallExpression methodCallExpression - && methodCallExpression.Method.IsGenericMethod - && methodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.GroupByWithKeySelector)) + if (!(groupByNavigationExpansionExpression.Source is MethodCallExpression { Method.IsGenericMethod: true } methodCallExpression + && methodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.GroupByWithKeySelector)) { // If the final operator is not GroupBy in source then GroupBy is not final operator. We throw exception. throw new InvalidOperationException(CoreStrings.TranslationFailed(query.Print())); @@ -117,8 +116,7 @@ public virtual Expression Expand(Expression query) groupByNavigationExpansionExpression.GroupingEnumerable); innerEnumerable = Reduce(innerEnumerable); - if (innerEnumerable is MethodCallExpression selectMethodCall - && selectMethodCall.Method.IsGenericMethod + if (innerEnumerable is MethodCallExpression { Method.IsGenericMethod: true } selectMethodCall && selectMethodCall.Method.GetGenericMethodDefinition() == QueryableMethods.Select) { var elementSelector = selectMethodCall.Arguments[1]; @@ -760,8 +758,7 @@ when QueryableMethods.IsSumWithSelector(method): if (genericMethod == QueryableMethods.AsQueryable) { - if (firstArgument is NavigationTreeExpression navigationTreeExpression - && navigationTreeExpression.Type.IsGenericType + if (firstArgument is NavigationTreeExpression { Type.IsGenericType: true } navigationTreeExpression && navigationTreeExpression.Type.GetGenericTypeDefinition() == typeof(IGrouping<,>)) { // This is groupingElement.AsQueryable so we preserve it @@ -1075,8 +1072,7 @@ private NavigationExpansionExpression ProcessInclude( bool thenInclude, bool setLoaded) { - if (source.PendingSelector is NavigationTreeExpression navigationTree - && navigationTree.Value is EntityReference entityReference) + if (source.PendingSelector is NavigationTreeExpression { Value: EntityReference entityReference }) { #pragma warning disable CS0618 // Type or member is obsolete if (entityReference.EntityType.GetDefiningQuery() != null) @@ -1088,8 +1084,7 @@ private NavigationExpansionExpression ProcessInclude( } #pragma warning restore CS0618 // Type or member is obsolete - if (expression is ConstantExpression includeConstant - && includeConstant.Value is string navigationChain) + if (expression is ConstantExpression { Value: string navigationChain } includeConstant) { var navigationPaths = navigationChain.Split(new[] { "." }, StringSplitOptions.None); var includeTreeNodes = new Queue(); @@ -1191,8 +1186,7 @@ private NavigationExpansionExpression ProcessInclude( static Expression FormatFilter(Expression expression) { - if (expression is MethodCallExpression methodCallExpression - && methodCallExpression.Method.IsGenericMethod + if (expression is MethodCallExpression { Method.IsGenericMethod: true } methodCallExpression && SupportedFilteredIncludeOperations.Contains(methodCallExpression.Method.GetGenericMethodDefinition())) { if (methodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.AsQueryable) @@ -1599,8 +1593,7 @@ private void ApplyPendingOrderings(NavigationExpansionExpression source) var lambdaBody = Visit(keySelector); lambdaBody = _pendingSelectorExpandingExpressionVisitor.Visit(lambdaBody); - if (lambdaBody is NavigationTreeExpression navigationTreeExpression - && navigationTreeExpression.Value is EntityReference entityReference) + if (lambdaBody is NavigationTreeExpression { Value: EntityReference entityReference } navigationTreeExpression) { var primaryKeyProperties = entityReference.EntityType.FindPrimaryKey()?.Properties; if (primaryKeyProperties != null) @@ -1629,8 +1622,10 @@ private void ApplyPendingOrderings(NavigationExpansionExpression source) if (lambdaBody is NavigationExpansionExpression navigationExpansionExpression && navigationExpansionExpression.CardinalityReducingGenericMethodInfo != null - && navigationExpansionExpression.PendingSelector is NavigationTreeExpression subqueryNavigationTreeExpression - && subqueryNavigationTreeExpression.Value is EntityReference subqueryEntityReference) + && navigationExpansionExpression.PendingSelector is NavigationTreeExpression + { + Value: EntityReference subqueryEntityReference + }) { var primaryKeyProperties = subqueryEntityReference.EntityType.FindPrimaryKey()?.Properties; if (primaryKeyProperties != null) @@ -1825,11 +1820,9 @@ private static MethodCallExpression ConvertToEnumerable(MethodInfo queryableMeth : Array.Empty(); var enumerableArguments = arguments.Select( - arg => arg is UnaryExpression unaryExpression - && unaryExpression.NodeType == ExpressionType.Quote - && unaryExpression.Operand is LambdaExpression - ? unaryExpression.Operand - : arg).ToList(); + arg => arg is UnaryExpression { NodeType: ExpressionType.Quote, Operand: LambdaExpression } unaryExpression + ? unaryExpression.Operand + : arg).ToList(); if (queryableMethod.Name == nameof(Enumerable.Min)) { @@ -2022,8 +2015,7 @@ private LambdaExpression GenerateLambda(Expression body, ParameterExpression cur private Expression UnwrapCollectionMaterialization(Expression expression) { - while (expression is MethodCallExpression innerMethodCall - && innerMethodCall.Method.IsGenericMethod + while (expression is MethodCallExpression { Method.IsGenericMethod: true } innerMethodCall && innerMethodCall.Method.GetGenericMethodDefinition() is MethodInfo innerMethod && (innerMethod == EnumerableMethods.AsEnumerable || innerMethod == EnumerableMethods.ToList @@ -2097,7 +2089,7 @@ private void PopulateEagerLoadedNavigations(IncludeTreeNode includeTreeNode) if (_queryCompilationContext.IgnoreAutoIncludes) { - outboundNavigations = outboundNavigations.Where(n => n is INavigation navigation && navigation.ForeignKey.IsOwnership); + outboundNavigations = outboundNavigations.Where(n => n is INavigation { ForeignKey.IsOwnership: true }); } foreach (var navigation in outboundNavigations) @@ -2124,7 +2116,7 @@ private void VerifyNoAutoIncludeCycles( } var autoIncludedNavigations = GetOutgoingEagerLoadedNavigations(entityType) - .Where(n => !(n is INavigation navigation && navigation.ForeignKey.IsOwnership)); + .Where(n => n is not INavigation { ForeignKey.IsOwnership: true }); foreach (var navigationBase in autoIncludedNavigations) { diff --git a/src/EFCore/Query/Internal/NullCheckRemovingExpressionVisitor.cs b/src/EFCore/Query/Internal/NullCheckRemovingExpressionVisitor.cs index 4f1e258e17d..f8bd314174c 100644 --- a/src/EFCore/Query/Internal/NullCheckRemovingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/NullCheckRemovingExpressionVisitor.cs @@ -88,8 +88,7 @@ protected override Expression VisitConditional(ConditionalExpression conditional // Simplify (a ? b : null) == null => !a || b == null // Simplify (a ? null : b) == null => a || b == null // Expression.Equal is fine here since we match the binary expression of same kind. - if (expression is BinaryExpression binaryExpression - && binaryExpression.NodeType == ExpressionType.Equal + if (expression is BinaryExpression { NodeType: ExpressionType.Equal } binaryExpression && (binaryExpression.Left is ConditionalExpression || binaryExpression.Right is ConditionalExpression)) { @@ -170,6 +169,5 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) } private static bool IsNullConstant(Expression expression) - => expression is ConstantExpression constantExpression - && constantExpression.Value == null; + => expression is ConstantExpression { Value: null }; } diff --git a/src/EFCore/Query/Internal/QueryOptimizingExpressionVisitor.cs b/src/EFCore/Query/Internal/QueryOptimizingExpressionVisitor.cs index 965acfd5f37..48903d88446 100644 --- a/src/EFCore/Query/Internal/QueryOptimizingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/QueryOptimizingExpressionVisitor.cs @@ -3,7 +3,6 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Internal; -using ExpressionExtensions = Microsoft.EntityFrameworkCore.Infrastructure.ExpressionExtensions; namespace Microsoft.EntityFrameworkCore.Query.Internal; @@ -184,9 +183,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp if (Equals(StartsWithMethodInfo, methodCallExpression.Method) || Equals(EndsWithMethodInfo, methodCallExpression.Method)) { - if (methodCallExpression.Arguments[0] is ConstantExpression constantArgument - && constantArgument.Value is string stringValue - && stringValue == string.Empty) + if (methodCallExpression.Arguments[0] is ConstantExpression { Value: "" }) { // every string starts/ends with empty string. return Expression.Constant(true); @@ -267,20 +264,18 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp || visited.Method.DeclaringType?.Name == "EmbeddedOperators") && visited.Method.DeclaringType?.Namespace == "Microsoft.VisualBasic.CompilerServices" && visited.Object == null - && visited.Arguments.Count == 3 - && visited.Arguments[2] is ConstantExpression textCompareConstantExpression) + && visited.Arguments is [_, _, ConstantExpression textCompareConstantExpression]) { - return textCompareConstantExpression.Value is bool boolValue - && boolValue - ? Expression.Call( - StringCompareWithComparisonMethod, - visited.Arguments[0], - visited.Arguments[1], - Expression.Constant(StringComparison.OrdinalIgnoreCase)) - : Expression.Call( - StringCompareWithoutComparisonMethod, - visited.Arguments[0], - visited.Arguments[1]); + return textCompareConstantExpression.Value is true + ? Expression.Call( + StringCompareWithComparisonMethod, + visited.Arguments[0], + visited.Arguments[1], + Expression.Constant(StringComparison.OrdinalIgnoreCase)) + : Expression.Call( + StringCompareWithoutComparisonMethod, + visited.Arguments[0], + visited.Arguments[1]); } return visited; @@ -337,14 +332,11 @@ protected override Expression VisitNewArray(NewArrayExpression newArrayExpressio /// protected override Expression VisitUnary(UnaryExpression unaryExpression) { - if (unaryExpression.NodeType == ExpressionType.Not - && unaryExpression.Operand is MethodCallExpression innerMethodCall + if (unaryExpression is { NodeType: ExpressionType.Not, Operand: MethodCallExpression innerMethodCall } && (Equals(StartsWithMethodInfo, innerMethodCall.Method) || Equals(EndsWithMethodInfo, innerMethodCall.Method))) { - if (innerMethodCall.Arguments[0] is ConstantExpression constantArgument - && constantArgument.Value is string stringValue - && stringValue == string.Empty) + if (innerMethodCall.Arguments[0] is ConstantExpression { Value: "" }) { // every string starts/ends with empty string. return Expression.Constant(false); @@ -442,15 +434,16 @@ when unaryExpression.IsLogicalNot(): // Simplify (a != null ? new { Member = b, ... } : null).Member // to a != null ? b : null // Later null check removal will simplify it further - if (expression is MemberExpression visitedMemberExpression - && visitedMemberExpression.Expression is ConditionalExpression conditionalExpression - && conditionalExpression.Test is BinaryExpression binaryTest - && (binaryTest.NodeType == ExpressionType.Equal - || binaryTest.NodeType == ExpressionType.NotEqual) + if (expression is MemberExpression + { + Expression: ConditionalExpression + { + Test: BinaryExpression { NodeType: ExpressionType.Equal or ExpressionType.NotEqual } binaryTest + } conditionalExpression + } visitedMemberExpression // Exclude HasValue/Value over Nullable<> as they return non-null type and we don't have equivalent for it for null part && !(conditionalExpression.Type.IsNullableValueType() - && (visitedMemberExpression.Member.Name == nameof(Nullable.HasValue) - || visitedMemberExpression.Member.Name == nameof(Nullable.Value)))) + && visitedMemberExpression.Member.Name is nameof(Nullable.HasValue) or nameof(Nullable.Value))) { var isLeftNullConstant = IsNullConstant(binaryTest.Left); var isRightNullConstant = IsNullConstant(binaryTest.Right); @@ -488,6 +481,5 @@ when unaryExpression.IsLogicalNot(): } private static bool IsNullConstant(Expression expression) - => expression is ConstantExpression constantExpression - && constantExpression.Value == null; + => expression is ConstantExpression { Value: null } constantExpression; } diff --git a/src/EFCore/Query/Internal/QueryableMethodNormalizingExpressionVisitor.cs b/src/EFCore/Query/Internal/QueryableMethodNormalizingExpressionVisitor.cs index ac8b2ef2b1f..4a663378654 100644 --- a/src/EFCore/Query/Internal/QueryableMethodNormalizingExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/QueryableMethodNormalizingExpressionVisitor.cs @@ -111,8 +111,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp visitedExpression = TryConvertEnumerableToQueryable(methodCallExpression); } - if (method.DeclaringType != null - && method.DeclaringType.IsGenericType + if (method.DeclaringType is { IsGenericType: true } && (method.DeclaringType.GetGenericTypeDefinition() == typeof(ICollection<>) || method.DeclaringType.GetGenericTypeDefinition() == typeof(List<>)) && method.Name == nameof(List.Contains)) @@ -376,8 +375,7 @@ private Expression TryConvertEnumerableToQueryable(MethodCallExpression methodCa // If innerArgument has ToList applied to it then unwrap it. // Also preserve generic argument of ToList is applied to different type if (arguments[i].Type.TryGetElementType(typeof(List<>)) != null - && arguments[i] is MethodCallExpression toListMethodCallExpression - && toListMethodCallExpression.Method.IsGenericMethod + && arguments[i] is MethodCallExpression { Method.IsGenericMethod: true } toListMethodCallExpression && toListMethodCallExpression.Method.GetGenericMethodDefinition() == EnumerableMethods.ToList) { genericType = toListMethodCallExpression.Method.GetGenericArguments()[0]; @@ -474,8 +472,7 @@ private MethodCallExpression TryFlattenGroupJoinSelectMany(MethodCallExpression { // SelectMany var selectManySource = methodCallExpression.Arguments[0]; - if (selectManySource is MethodCallExpression groupJoinMethod - && groupJoinMethod.Method.IsGenericMethod + if (selectManySource is MethodCallExpression { Method.IsGenericMethod: true } groupJoinMethod && groupJoinMethod.Method.GetGenericMethodDefinition() == QueryableMethods.GroupJoin) { // GroupJoin @@ -491,8 +488,7 @@ private MethodCallExpression TryFlattenGroupJoinSelectMany(MethodCallExpression var collectionSelectorBody = selectManyCollectionSelector.Body; var defaultIfEmpty = false; - if (collectionSelectorBody is MethodCallExpression collectionEndingMethod - && collectionEndingMethod.Method.IsGenericMethod + if (collectionSelectorBody is MethodCallExpression { Method.IsGenericMethod: true } collectionEndingMethod && collectionEndingMethod.Method.GetGenericMethodDefinition() == QueryableMethods.DefaultIfEmptyWithoutArgument) { defaultIfEmpty = true; @@ -514,8 +510,7 @@ private MethodCallExpression TryFlattenGroupJoinSelectMany(MethodCallExpression ReplacingExpressionVisitor.Replace( groupJoinResultSelector.Parameters[1], inner, collectionSelectorBody)); - if (inner is MethodCallExpression innerMethodCall - && innerMethodCall.Method.IsGenericMethod + if (inner is MethodCallExpression { Method.IsGenericMethod: true } innerMethodCall && innerMethodCall.Method.GetGenericMethodDefinition() == QueryableMethods.AsQueryable && innerMethodCall.Type == innerMethodCall.Arguments[0].Type) { @@ -578,8 +573,7 @@ private MethodCallExpression TryFlattenGroupJoinSelectMany(MethodCallExpression { // SelectMany var selectManySource = methodCallExpression.Arguments[0]; - if (selectManySource is MethodCallExpression groupJoinMethod - && groupJoinMethod.Method.IsGenericMethod + if (selectManySource is MethodCallExpression { Method.IsGenericMethod: true } groupJoinMethod && groupJoinMethod.Method.GetGenericMethodDefinition() == QueryableMethods.GroupJoin) { // GroupJoin @@ -594,8 +588,7 @@ private MethodCallExpression TryFlattenGroupJoinSelectMany(MethodCallExpression var groupJoinResultSelectorBody = groupJoinResultSelector.Body; var defaultIfEmpty = false; - if (groupJoinResultSelectorBody is MethodCallExpression collectionEndingMethod - && collectionEndingMethod.Method.IsGenericMethod + if (groupJoinResultSelectorBody is MethodCallExpression { Method.IsGenericMethod: true } collectionEndingMethod && collectionEndingMethod.Method.GetGenericMethodDefinition() == QueryableMethods.DefaultIfEmptyWithoutArgument) { defaultIfEmpty = true; diff --git a/src/EFCore/Query/Internal/SubqueryMemberPushdownExpressionVisitor.cs b/src/EFCore/Query/Internal/SubqueryMemberPushdownExpressionVisitor.cs index 0f3c92d67c6..f9480fa4364 100644 --- a/src/EFCore/Query/Internal/SubqueryMemberPushdownExpressionVisitor.cs +++ b/src/EFCore/Query/Internal/SubqueryMemberPushdownExpressionVisitor.cs @@ -61,8 +61,7 @@ public SubqueryMemberPushdownExpressionVisitor(IModel model) protected override Expression VisitMember(MemberExpression memberExpression) { var innerExpression = Visit(memberExpression.Expression); - if (innerExpression is MethodCallExpression methodCallExpression - && methodCallExpression.Method.IsGenericMethod + if (innerExpression is MethodCallExpression { Method.IsGenericMethod: true } methodCallExpression && SupportedMethods.Contains(methodCallExpression.Method.GetGenericMethodDefinition())) { return PushdownMember( @@ -73,7 +72,7 @@ protected override Expression VisitMember(MemberExpression memberExpression) return nullable && !memberAccessExpression.Type.IsNullableType() ? Expression.Convert(memberAccessExpression, memberAccessExpression.Type.MakeNullable()) - : (Expression)memberAccessExpression; + : memberAccessExpression; }, memberExpression.Type); } @@ -93,8 +92,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp { source = Visit(source); - if (source is MethodCallExpression innerMethodCall - && innerMethodCall.Method.IsGenericMethod + if (source is MethodCallExpression { Method.IsGenericMethod: true } innerMethodCall && SupportedMethods.Contains(innerMethodCall.Method.GetGenericMethodDefinition())) { return PushdownMember( @@ -120,8 +118,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp { source = Visit(source); - if (source is MethodCallExpression innerMethodCall - && innerMethodCall.Method.IsGenericMethod + if (source is MethodCallExpression { Method.IsGenericMethod: true } innerMethodCall && SupportedMethods.Contains(innerMethodCall.Method.GetGenericMethodDefinition())) { return PushdownMember( @@ -134,7 +131,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp return nullable && !indexerExpression.Type.IsNullableType() ? Expression.Convert(indexerExpression, indexerExpression.Type.MakeNullable()) - : (Expression)indexerExpression; + : indexerExpression; }, methodCallExpression.Type); } @@ -180,8 +177,7 @@ private Expression PushdownMember( genericMethod = PredicateLessMethodInfo[genericMethod]; } - if (source is MethodCallExpression sourceMethodCallExpression - && sourceMethodCallExpression.Method.IsGenericMethod + if (source is MethodCallExpression { Method.IsGenericMethod: true } sourceMethodCallExpression && sourceMethodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.Select) { var selector = sourceMethodCallExpression.Arguments[1].UnwrapLambdaFromQuote(); diff --git a/src/EFCore/Query/ProjectionMember.cs b/src/EFCore/Query/ProjectionMember.cs index 7f2d164f5fb..6332b071f85 100644 --- a/src/EFCore/Query/ProjectionMember.cs +++ b/src/EFCore/Query/ProjectionMember.cs @@ -86,9 +86,7 @@ public override int GetHashCode() /// [DebuggerStepThrough] public override bool Equals(object? obj) - => obj != null - && (obj is ProjectionMember projectionMember - && Equals(projectionMember)); + => obj is ProjectionMember projectionMember && Equals(projectionMember); private bool Equals(ProjectionMember other) { diff --git a/src/EFCore/Query/QueryCompilationContext.cs b/src/EFCore/Query/QueryCompilationContext.cs index e51a1ab42f4..def674ba898 100644 --- a/src/EFCore/Query/QueryCompilationContext.cs +++ b/src/EFCore/Query/QueryCompilationContext.cs @@ -55,7 +55,6 @@ public class QueryCompilationContext private readonly IQueryableMethodTranslatingExpressionVisitorFactory _queryableMethodTranslatingExpressionVisitorFactory; private readonly IQueryTranslationPostprocessorFactory _queryTranslationPostprocessorFactory; private readonly IShapedQueryCompilingExpressionVisitorFactory _shapedQueryCompilingExpressionVisitorFactory; - private readonly IQueryExpressionInterceptor? _queryExpressionInterceptor; private readonly ExpressionPrinter _expressionPrinter; @@ -85,7 +84,6 @@ public QueryCompilationContext( _shapedQueryCompilingExpressionVisitorFactory = dependencies.ShapedQueryCompilingExpressionVisitorFactory; _expressionPrinter = new ExpressionPrinter(); - _queryExpressionInterceptor = dependencies.Interceptors.Aggregate(); } /// diff --git a/src/EFCore/Query/ShapedQueryCompilingExpressionVisitor.cs b/src/EFCore/Query/ShapedQueryCompilingExpressionVisitor.cs index b717cc5bc09..a554a2be72d 100644 --- a/src/EFCore/Query/ShapedQueryCompilingExpressionVisitor.cs +++ b/src/EFCore/Query/ShapedQueryCompilingExpressionVisitor.cs @@ -210,8 +210,7 @@ public ConstantVerifyingExpressionVisitor(ITypeMappingSource typeMappingSource) private bool ValidConstant(ConstantExpression constantExpression) => constantExpression.Value == null || _typeMappingSource.FindMapping(constantExpression.Type) != null - || constantExpression.Value is Array array - && array.Length == 0; + || constantExpression.Value is Array { Length: 0 }; protected override Expression VisitConstant(ConstantExpression constantExpression) { @@ -436,7 +435,7 @@ private Expression ProcessEntityShaper(EntityShaperExpression entityShaperExpres p => Expression.NotEqual( valueBufferExpression.CreateValueBufferReadValueExpression(typeof(object), p.GetIndex(), p), Expression.Constant(null))) - .Aggregate((a, b) => Expression.AndAlso(a, b)), + .Aggregate(Expression.AndAlso), MaterializeEntity( entityShaperExpression, materializationContextVariable, concreteEntityTypeVariable, instanceVariable, @@ -451,7 +450,7 @@ private Expression ProcessEntityShaper(EntityShaperExpression entityShaperExpres p => Expression.NotEqual( valueBufferExpression.CreateValueBufferReadValueExpression(typeof(object), p.GetIndex(), p), Expression.Constant(null))) - .Aggregate((a, b) => Expression.AndAlso(a, b)), + .Aggregate(Expression.AndAlso), MaterializeEntity( entityShaperExpression, materializationContextVariable, concreteEntityTypeVariable, instanceVariable, diff --git a/src/EFCore/Storage/ExecutionStrategy.cs b/src/EFCore/Storage/ExecutionStrategy.cs index f574b63d2d1..038ad521bd2 100644 --- a/src/EFCore/Storage/ExecutionStrategy.cs +++ b/src/EFCore/Storage/ExecutionStrategy.cs @@ -493,10 +493,9 @@ public static TResult CallOnWrappedException( { while (true) { - if (exception is DbUpdateException dbUpdateException - && dbUpdateException.InnerException != null) + if (exception is DbUpdateException { InnerException: Exception innerException }) { - exception = dbUpdateException.InnerException; + exception = innerException; continue; } diff --git a/src/EFCore/Storage/TypeMappingInfo.cs b/src/EFCore/Storage/TypeMappingInfo.cs index c67514ccc9e..77326d1445d 100644 --- a/src/EFCore/Storage/TypeMappingInfo.cs +++ b/src/EFCore/Storage/TypeMappingInfo.cs @@ -100,7 +100,7 @@ public TypeMappingInfo( IsKeyOrIndex = property.IsKey() || property.IsForeignKey() || property.IsIndex(); Size = fallbackSize ?? mappingHints?.Size; IsUnicode = fallbackUnicode ?? mappingHints?.IsUnicode; - IsRowVersion = property.IsConcurrencyToken && property.ValueGenerated == ValueGenerated.OnAddOrUpdate; + IsRowVersion = property is { IsConcurrencyToken: true, ValueGenerated: ValueGenerated.OnAddOrUpdate }; ClrType = (customConverter?.ProviderClrType ?? property.ClrType).UnwrapNullableType(); Scale = fallbackScale ?? mappingHints?.Scale; Precision = fallbackPrecision ?? mappingHints?.Precision; diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteConnection.cs b/src/Microsoft.Data.Sqlite.Core/SqliteConnection.cs index 5351691d236..228845c0d18 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteConnection.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteConnection.cs @@ -8,7 +8,6 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; -using System.Runtime.CompilerServices; using Microsoft.Data.Sqlite.Properties; using SQLitePCL; using static SQLitePCL.raw; diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionFactory.cs b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionFactory.cs index 1587f0cf117..44fce2e5f2f 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionFactory.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionFactory.cs @@ -31,8 +31,7 @@ protected SqliteConnectionFactory() public SqliteConnectionInternal GetConnection(SqliteConnection outerConnection) { var poolGroup = outerConnection.PoolGroup; - if (poolGroup.IsDisabled - && !poolGroup.IsNonPooled) + if (poolGroup is { IsDisabled: true, IsNonPooled: false }) { poolGroup = GetPoolGroup(poolGroup.ConnectionString); outerConnection.PoolGroup = poolGroup; diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs index 75e8f0fd34c..af98601bdf9 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs @@ -313,7 +313,7 @@ private static TEnum ConvertToEnum(object value) private static bool? ConvertToNullableBoolean(object value) { if (value == null - || (value is string stringValue && stringValue.Length == 0)) + || value is string { Length: 0 }) { return null; } diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteValueReader.cs b/src/Microsoft.Data.Sqlite.Core/SqliteValueReader.cs index 60e62de5cf8..0a8b9b36a70 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteValueReader.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteValueReader.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Diagnostics; using System.Globalization; using System.Text; using Microsoft.Data.Sqlite.Properties; diff --git a/src/Shared/Check.cs b/src/Shared/Check.cs index 40cb77d9cc1..a59e081db29 100644 --- a/src/Shared/Check.cs +++ b/src/Shared/Check.cs @@ -4,9 +4,7 @@ #nullable enable using System.Diagnostics.CodeAnalysis; -using System.Linq; using JetBrains.Annotations; -using Microsoft.EntityFrameworkCore.Diagnostics; namespace Microsoft.EntityFrameworkCore.Utilities; diff --git a/src/Shared/DisposableExtensions.cs b/src/Shared/DisposableExtensions.cs index b7c353a1f96..e43c01870ec 100644 --- a/src/Shared/DisposableExtensions.cs +++ b/src/Shared/DisposableExtensions.cs @@ -3,9 +3,6 @@ #nullable enable -using System; -using System.Threading.Tasks; - namespace Microsoft.EntityFrameworkCore.Utilities; internal static class DisposableExtensions diff --git a/src/Shared/EnumerableExtensions.cs b/src/Shared/EnumerableExtensions.cs index 9188ba74436..eeeceea264f 100644 --- a/src/Shared/EnumerableExtensions.cs +++ b/src/Shared/EnumerableExtensions.cs @@ -4,11 +4,6 @@ #nullable enable using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; // ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore.Utilities; diff --git a/src/Shared/ExpressionExtensions.cs b/src/Shared/ExpressionExtensions.cs index 2455863ca9a..0aa2ad03def 100644 --- a/src/Shared/ExpressionExtensions.cs +++ b/src/Shared/ExpressionExtensions.cs @@ -12,8 +12,7 @@ namespace System.Linq.Expressions; internal static class ExpressionExtensions { public static bool IsNullConstantExpression(this Expression expression) - => RemoveConvert(expression) is ConstantExpression constantExpression - && constantExpression.Value == null; + => RemoveConvert(expression) is ConstantExpression { Value: null }; public static LambdaExpression UnwrapLambdaFromQuote(this Expression expression) => (LambdaExpression)(expression is UnaryExpression unary && expression.NodeType == ExpressionType.Quote diff --git a/src/Shared/Graph.cs b/src/Shared/Graph.cs index c8b75dd3791..f1b1943f2b2 100644 --- a/src/Shared/Graph.cs +++ b/src/Shared/Graph.cs @@ -3,9 +3,6 @@ #nullable enable -using System.Collections.Generic; -using System.Linq; - namespace Microsoft.EntityFrameworkCore.Utilities; internal abstract class Graph diff --git a/src/Shared/MemberInfoExtensions.cs b/src/Shared/MemberInfoExtensions.cs index cbd02188c25..09dc3082894 100644 --- a/src/Shared/MemberInfoExtensions.cs +++ b/src/Shared/MemberInfoExtensions.cs @@ -3,8 +3,6 @@ #nullable enable -using System.Linq; - namespace System.Reflection; internal static class EntityFrameworkMemberInfoExtensions @@ -49,5 +47,5 @@ public static string GetSimpleMemberName(this MemberInfo member) } public static bool IsReallyVirtual(this MethodInfo method) - => method.IsVirtual && !method.IsFinal; + => method is { IsVirtual: true, IsFinal: false }; } diff --git a/src/Shared/MethodInfoExtensions.cs b/src/Shared/MethodInfoExtensions.cs index 6b51a4c79d8..2e596197103 100644 --- a/src/Shared/MethodInfoExtensions.cs +++ b/src/Shared/MethodInfoExtensions.cs @@ -4,17 +4,14 @@ #nullable enable using System.Collections; -using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; namespace System.Reflection; internal static class MethodInfoExtensions { public static bool IsContainsMethod(this MethodInfo method) - => method.Name == nameof(IList.Contains) - && method.DeclaringType != null + => method is { Name: nameof(IList.Contains), DeclaringType: not null } && method.DeclaringType.GetInterfaces().Append(method.DeclaringType).Any( t => t == typeof(IList) || (t.IsGenericType diff --git a/src/Shared/NonCapturingLazyInitializer.cs b/src/Shared/NonCapturingLazyInitializer.cs index 4a638dad865..42412bda950 100644 --- a/src/Shared/NonCapturingLazyInitializer.cs +++ b/src/Shared/NonCapturingLazyInitializer.cs @@ -4,7 +4,6 @@ #nullable enable using System.Diagnostics.CodeAnalysis; -using System.Threading; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Internal; diff --git a/src/Shared/PropertyInfoExtensions.cs b/src/Shared/PropertyInfoExtensions.cs index 32dc9037308..19765c1b89c 100644 --- a/src/Shared/PropertyInfoExtensions.cs +++ b/src/Shared/PropertyInfoExtensions.cs @@ -3,8 +3,7 @@ #nullable enable -using System.Diagnostics; -using System.Linq; + // ReSharper disable once CheckNamespace namespace System.Reflection; diff --git a/src/Shared/SharedTypeExtensions.cs b/src/Shared/SharedTypeExtensions.cs index f71091c39e8..715ba2c595c 100644 --- a/src/Shared/SharedTypeExtensions.cs +++ b/src/Shared/SharedTypeExtensions.cs @@ -3,12 +3,8 @@ #nullable enable -using System.Collections.Generic; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Linq.Expressions; -using System.Reflection; using System.Runtime.CompilerServices; using System.Text; @@ -48,8 +44,7 @@ public static bool IsNullableType(this Type type) => !type.IsValueType || type.IsNullableValueType(); public static bool IsValidEntityType(this Type type) - => type.IsClass - && !type.IsArray; + => type is { IsClass: true, IsArray: false }; public static bool IsPropertyBagType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] this Type type) { @@ -122,8 +117,7 @@ public static bool IsAnonymousType(this Type type) } public static bool IsInstantiable(this Type type) - => !type.IsAbstract - && !type.IsInterface + => type is { IsAbstract: false, IsInterface: false } && (!type.IsGenericType || !type.IsGenericTypeDefinition); public static Type UnwrapEnumType(this Type type) @@ -256,8 +250,7 @@ public static List GetBaseTypesAndInterfacesInclusive(this Type type) typesToProcess.Enqueue(type.GetGenericTypeDefinition()); } - if (!type.IsGenericTypeDefinition - && !type.IsInterface) + if (type is { IsGenericTypeDefinition: false, IsInterface: false }) { if (type.BaseType != null) { @@ -412,8 +405,7 @@ public static IEnumerable GetMembersInHierarchy( [RequiresUnreferencedCode("Gets all types from the given assembly - unsafe for trimming")] public static IEnumerable GetConstructibleTypes(this Assembly assembly) => assembly.GetLoadableDefinedTypes().Where( - t => !t.IsAbstract - && !t.IsGenericTypeDefinition); + t => t is { IsAbstract: false, IsGenericTypeDefinition: false }); [RequiresUnreferencedCode("Gets all types from the given assembly - unsafe for trimming")] public static IEnumerable GetLoadableDefinedTypes(this Assembly assembly) diff --git a/src/ef/CommandLineUtils/CommandOption.cs b/src/ef/CommandLineUtils/CommandOption.cs index 0d1978a41f1..d95ded941df 100644 --- a/src/ef/CommandLineUtils/CommandOption.cs +++ b/src/ef/CommandLineUtils/CommandOption.cs @@ -130,5 +130,5 @@ public bool HasValue() => HasValue() ? Values[0] : null; private static bool IsEnglishLetter(char c) - => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z'; } diff --git a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs index 225007b16c7..a5c90589246 100644 --- a/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs +++ b/test/EFCore.Cosmos.FunctionalTests/TestUtilities/CosmosTestStore.cs @@ -132,8 +132,7 @@ private static bool IsNotConfigured(Exception exception) => exception switch { HttpRequestException re => re.InnerException is SocketException // Exception in Mac/Linux - || (re.InnerException is IOException ioException - && ioException.InnerException is SocketException), // Exception in Windows + || re.InnerException is IOException { InnerException: SocketException }, // Exception in Windows _ => exception.Message.Contains( "The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used.", StringComparison.Ordinal), diff --git a/test/EFCore.Design.Tests/DesignExceptionTest.cs b/test/EFCore.Design.Tests/DesignExceptionTest.cs index 3ffee86105e..717d6a5e6f0 100644 --- a/test/EFCore.Design.Tests/DesignExceptionTest.cs +++ b/test/EFCore.Design.Tests/DesignExceptionTest.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Runtime.Serialization.Formatters.Binary; - namespace Microsoft.EntityFrameworkCore; public class DesignExceptionTest diff --git a/test/EFCore.InMemory.FunctionalTests/CustomConvertersInMemoryTest.cs b/test/EFCore.InMemory.FunctionalTests/CustomConvertersInMemoryTest.cs index 090b15c7ce6..f06c815aff6 100644 --- a/test/EFCore.InMemory.FunctionalTests/CustomConvertersInMemoryTest.cs +++ b/test/EFCore.InMemory.FunctionalTests/CustomConvertersInMemoryTest.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.EntityFrameworkCore.InMemory.Internal; -using static Microsoft.EntityFrameworkCore.DbLoggerCategory; namespace Microsoft.EntityFrameworkCore; diff --git a/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs index bade662fa1b..7db1d8d391c 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/FromSqlQueryTestBase.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Data; -using System.Runtime.Intrinsics.X86; -using Microsoft.EntityFrameworkCore.TestModels.GearsOfWarModel; using Microsoft.EntityFrameworkCore.TestModels.Northwind; // ReSharper disable FormatStringProblem diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindQueryRelationalFixture.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindQueryRelationalFixture.cs index dd8849cfaa9..511923ae445 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindQueryRelationalFixture.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindQueryRelationalFixture.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.TestModels.Northwind; - namespace Microsoft.EntityFrameworkCore.Query; public abstract class NorthwindQueryRelationalFixture : NorthwindQueryFixtureBase diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeNoTrackingQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeNoTrackingQueryTestBase.cs index 4aa984a11e5..5b1a0538f07 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeNoTrackingQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeNoTrackingQueryTestBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.TestModels.Northwind; // ReSharper disable FormatStringProblem diff --git a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeQueryTestBase.cs index 747b26628e3..43798bd320d 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/NorthwindSplitIncludeQueryTestBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.TestModels.Northwind; // ReSharper disable FormatStringProblem diff --git a/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs b/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs index 58dcade93cb..8d07b241513 100644 --- a/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Query/OperatorsProceduralQueryTestBase.cs @@ -297,7 +297,7 @@ private Expression MainLoop( var possibleBinariesForResultType = possibleBinaries.Where(x => x.ResultType == currentResultType).ToList(); var possibleUnariesForResultType = possibleUnaries.Where(x => x.ResultType == currentResultType).ToList(); - // if we can't go any deeper (no matching operations) then simply return source + // if we can't go any deeper (no matching operations) then simply return source if (possibleBinariesForResultType.Count == 0 && possibleUnariesForResultType.Count == 0) { return AddRootPropertyAccess(random, currentResultType, rootPropertyExpressions); @@ -678,8 +678,7 @@ public ResultExpressionProjectionRewriter(Expression resultExpression, Expressio protected override Expression VisitNew(NewExpression newExpression) { - if (newExpression.Constructor is ConstructorInfo ctorInfo - && ctorInfo.DeclaringType is Type { IsGenericType: true } declaringType) + if (newExpression.Constructor is ConstructorInfo { DeclaringType: Type { IsGenericType: true } declaringType }) { if (declaringType.GetGenericTypeDefinition() == typeof(OperatorDto1<,>)) { diff --git a/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs b/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs index b5c5f930fe9..87e5192b62a 100644 --- a/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/TransactionTestBase.cs @@ -1635,10 +1635,7 @@ protected abstract class TransactionEntity public string Name { get; set; } public override bool Equals(object obj) - => !(obj is TransactionCustomer otherCustomer) - ? false - : Id == otherCustomer.Id - && Name == otherCustomer.Name; + => obj is TransactionCustomer otherCustomer && (Id == otherCustomer.Id && Name == otherCustomer.Name); public override string ToString() => "Id = " + Id + ", Name = " + Name; diff --git a/test/EFCore.Relational.Tests/Metadata/RelationalModelTest.cs b/test/EFCore.Relational.Tests/Metadata/RelationalModelTest.cs index dfd710b2445..072cffd7e18 100644 --- a/test/EFCore.Relational.Tests/Metadata/RelationalModelTest.cs +++ b/test/EFCore.Relational.Tests/Metadata/RelationalModelTest.cs @@ -3,7 +3,6 @@ using System.Data; using Microsoft.EntityFrameworkCore.Metadata.Internal; -using Microsoft.EntityFrameworkCore.TestUtilities; using NameSpace1; // ReSharper disable InconsistentNaming diff --git a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs index 4d7ced8fb3e..222e691c9a2 100644 --- a/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs +++ b/test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs @@ -11735,7 +11735,7 @@ public void Primary_key_properties_are_sorted_first() operations => { var dependentTableCreation - = (CreateTableOperation)operations.Single(o => o is CreateTableOperation ct && ct.Name == "Dependent"); + = (CreateTableOperation)operations.Single(o => o is CreateTableOperation { Name: "Dependent" }); Assert.Collection( dependentTableCreation.Columns, diff --git a/test/EFCore.Relational.Tests/Storage/RelationalDataReaderTest.cs b/test/EFCore.Relational.Tests/Storage/RelationalDataReaderTest.cs index f24138952b0..6e83a112a82 100644 --- a/test/EFCore.Relational.Tests/Storage/RelationalDataReaderTest.cs +++ b/test/EFCore.Relational.Tests/Storage/RelationalDataReaderTest.cs @@ -1,14 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.Internal; -using Microsoft.EntityFrameworkCore.TestUtilities; using Microsoft.EntityFrameworkCore.TestUtilities.FakeProvider; -using Xunit; // ReSharper disable MethodHasAsyncOverload diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBase.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBase.cs index 3c63ce6b52c..50cbc0981e9 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBase.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.CompilerServices; diff --git a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs index fa967c3a428..913769005a3 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/GraphUpdatesTestBaseOneToMany.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; + // ReSharper disable InconsistentNaming // ReSharper disable AccessToModifiedClosure diff --git a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesFixtureBase.cs b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesFixtureBase.cs index e86cfc853c8..10cab5cee38 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesFixtureBase.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesFixtureBase.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; - namespace Microsoft.EntityFrameworkCore; public abstract partial class ProxyGraphUpdatesTestBase : IClassFixture diff --git a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToMany.cs b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToMany.cs index e2feb4565bd..8c1adc2bffb 100644 --- a/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToMany.cs +++ b/test/EFCore.Specification.Tests/GraphUpdates/ProxyGraphUpdatesTestBaseOneToMany.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; + // ReSharper disable InconsistentNaming // ReSharper disable AccessToModifiedClosure diff --git a/test/EFCore.Specification.Tests/Query/NorthwindEFPropertyIncludeQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindEFPropertyIncludeQueryTestBase.cs index 8175f6dd065..35e2f09250e 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindEFPropertyIncludeQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindEFPropertyIncludeQueryTestBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.TestModels.Northwind; namespace Microsoft.EntityFrameworkCore.Query; diff --git a/test/EFCore.Specification.Tests/Query/NorthwindIncludeNoTrackingQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindIncludeNoTrackingQueryTestBase.cs index 9c72c3aa17e..97efea4420d 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindIncludeNoTrackingQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindIncludeNoTrackingQueryTestBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.TestModels.Northwind; // ReSharper disable InconsistentNaming diff --git a/test/EFCore.Specification.Tests/Query/NorthwindIncludeQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindIncludeQueryTestBase.cs index a388e0ab56a..a74ac5b0749 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindIncludeQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindIncludeQueryTestBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.TestModels.Northwind; // ReSharper disable InconsistentNaming diff --git a/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs index 81bf6547724..4f420ce4ccf 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindMiscellaneousQueryTestBase.cs @@ -721,7 +721,7 @@ orderby o.OrderID public virtual Task Ternary_should_not_evaluate_both_sides(bool async) { Customer customer = null; - var hasData = !(customer is null); + var hasData = customer is not null; return AssertQuery( async, diff --git a/test/EFCore.Specification.Tests/Query/NorthwindStringIncludeQueryTestBase.cs b/test/EFCore.Specification.Tests/Query/NorthwindStringIncludeQueryTestBase.cs index 58dcc04c09c..7b9feb7babe 100644 --- a/test/EFCore.Specification.Tests/Query/NorthwindStringIncludeQueryTestBase.cs +++ b/test/EFCore.Specification.Tests/Query/NorthwindStringIncludeQueryTestBase.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.EntityFrameworkCore.Diagnostics.Internal; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.TestModels.Northwind; // ReSharper disable InconsistentNaming diff --git a/test/EFCore.Specification.Tests/SerializationTestBase.cs b/test/EFCore.Specification.Tests/SerializationTestBase.cs index 3c049fd6ec6..edb3f0d4c0c 100644 --- a/test/EFCore.Specification.Tests/SerializationTestBase.cs +++ b/test/EFCore.Specification.Tests/SerializationTestBase.cs @@ -3,7 +3,6 @@ using System.Text.Json; using System.Text.Json.Serialization; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.TestModels.ConcurrencyModel; using Newtonsoft.Json; using JsonSerializer = System.Text.Json.JsonSerializer; diff --git a/test/EFCore.Specification.Tests/TestModels/Northwind/Employee.cs b/test/EFCore.Specification.Tests/TestModels/Northwind/Employee.cs index e72489855c0..6ad8a02e5fb 100644 --- a/test/EFCore.Specification.Tests/TestModels/Northwind/Employee.cs +++ b/test/EFCore.Specification.Tests/TestModels/Northwind/Employee.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; namespace Microsoft.EntityFrameworkCore.TestModels.Northwind; diff --git a/test/EFCore.Specification.Tests/TestUtilities/ExpectedQueryRewritingVisitor.cs b/test/EFCore.Specification.Tests/TestUtilities/ExpectedQueryRewritingVisitor.cs index b70014717f2..0a331b71d95 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/ExpectedQueryRewritingVisitor.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/ExpectedQueryRewritingVisitor.cs @@ -310,8 +310,7 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) if ((unaryExpression.NodeType == ExpressionType.Convert || unaryExpression.NodeType == ExpressionType.ConvertChecked || unaryExpression.NodeType == ExpressionType.TypeAs) - && unaryExpression.Operand is MemberExpression memberOperand - && memberOperand.Type.IsValueType + && unaryExpression.Operand is MemberExpression { Type.IsValueType: true } memberOperand && !memberOperand.Type.IsNullableValueType() && memberOperand.Expression != null && unaryExpression.Type.IsNullableValueType() diff --git a/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectThenByPropertyExpressionMutator.cs b/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectThenByPropertyExpressionMutator.cs index 6c9c58b8766..4cfa17fc7eb 100644 --- a/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectThenByPropertyExpressionMutator.cs +++ b/test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/InjectThenByPropertyExpressionMutator.cs @@ -90,8 +90,7 @@ public override Expression Visit(Expression expression) } if (!_insideThenInclude - && expression != null - && !(expression is ConstantExpression) + && expression is not (null or ConstantExpression) && IsOrderedQueryableResult(expression) && !FoundExpressions.ContainsKey(expression)) { diff --git a/test/EFCore.SqlServer.FunctionalTests/BulkUpdates/NorthwindBulkUpdatesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/BulkUpdates/NorthwindBulkUpdatesSqlServerTest.cs index fdfd67385c2..3bc71c710fd 100644 --- a/test/EFCore.SqlServer.FunctionalTests/BulkUpdates/NorthwindBulkUpdatesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/BulkUpdates/NorthwindBulkUpdatesSqlServerTest.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.TestModels.Northwind; - namespace Microsoft.EntityFrameworkCore.BulkUpdates; public class NorthwindBulkUpdatesSqlServerTest : NorthwindBulkUpdatesTestBase> diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindCompiledQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindCompiledQuerySqlServerTest.cs index ad1c28b9080..6b702fb4fc6 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindCompiledQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindCompiledQuerySqlServerTest.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.TestModels.Northwind; - namespace Microsoft.EntityFrameworkCore.Query; public class NorthwindCompiledQuerySqlServerTest : NorthwindCompiledQueryTestBase> diff --git a/test/EFCore.SqlServer.FunctionalTests/Scaffolding/SqlServerDatabaseModelFactoryTest.cs b/test/EFCore.SqlServer.FunctionalTests/Scaffolding/SqlServerDatabaseModelFactoryTest.cs index 420b5e19ecc..9864bb0d71f 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Scaffolding/SqlServerDatabaseModelFactoryTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Scaffolding/SqlServerDatabaseModelFactoryTest.cs @@ -535,28 +535,28 @@ FOREIGN KEY (ForeignKeyId1, ForeignKeyId2) REFERENCES [db2].[PrincipalTable](UC1 // ReSharper disable once PossibleNullReferenceException Assert.Equal("db2", sequence.Schema); - Assert.Single(dbModel.Tables.Where(t => t.Schema == "db.2" && t.Name == "QuotedTableName")); - Assert.Empty(dbModel.Tables.Where(t => t.Schema == "db.2" && t.Name == "Table.With.Dot")); - Assert.Single(dbModel.Tables.Where(t => t.Schema == "db.2" && t.Name == "SimpleTableName")); - Assert.Single(dbModel.Tables.Where(t => t.Schema == "db.2" && t.Name == "JustTableName")); - - Assert.Empty(dbModel.Tables.Where(t => t.Schema == "dbo" && t.Name == "QuotedTableName")); - Assert.Single(dbModel.Tables.Where(t => t.Schema == "dbo" && t.Name == "Table.With.Dot")); - Assert.Single(dbModel.Tables.Where(t => t.Schema == "dbo" && t.Name == "SimpleTableName")); - Assert.Single(dbModel.Tables.Where(t => t.Schema == "dbo" && t.Name == "JustTableName")); - - Assert.Single(dbModel.Tables.Where(t => t.Schema == "db2" && t.Name == "QuotedTableName")); - Assert.Single(dbModel.Tables.Where(t => t.Schema == "db2" && t.Name == "Table.With.Dot")); - Assert.Single(dbModel.Tables.Where(t => t.Schema == "db2" && t.Name == "SimpleTableName")); - Assert.Single(dbModel.Tables.Where(t => t.Schema == "db2" && t.Name == "JustTableName")); - - var principalTable = Assert.Single(dbModel.Tables.Where(t => t.Schema == "db2" && t.Name == "PrincipalTable")); + Assert.Single(dbModel.Tables.Where(t => t is { Schema: "db.2", Name: "QuotedTableName" })); + Assert.Empty(dbModel.Tables.Where(t => t is { Schema: "db.2", Name: "Table.With.Dot" })); + Assert.Single(dbModel.Tables.Where(t => t is { Schema: "db.2", Name: "SimpleTableName" })); + Assert.Single(dbModel.Tables.Where(t => t is { Schema: "db.2", Name: "JustTableName" })); + + Assert.Empty(dbModel.Tables.Where(t => t is { Schema: "dbo", Name: "QuotedTableName" })); + Assert.Single(dbModel.Tables.Where(t => t is { Schema: "dbo", Name: "Table.With.Dot" })); + Assert.Single(dbModel.Tables.Where(t => t is { Schema: "dbo", Name: "SimpleTableName" })); + Assert.Single(dbModel.Tables.Where(t => t is { Schema: "dbo", Name: "JustTableName" })); + + Assert.Single(dbModel.Tables.Where(t => t is { Schema: "db2", Name: "QuotedTableName" })); + Assert.Single(dbModel.Tables.Where(t => t is { Schema: "db2", Name: "Table.With.Dot" })); + Assert.Single(dbModel.Tables.Where(t => t is { Schema: "db2", Name: "SimpleTableName" })); + Assert.Single(dbModel.Tables.Where(t => t is { Schema: "db2", Name: "JustTableName" })); + + var principalTable = Assert.Single(dbModel.Tables.Where(t => t is { Schema: "db2", Name: "PrincipalTable" })); // ReSharper disable once PossibleNullReferenceException Assert.NotNull(principalTable.PrimaryKey); Assert.Single(principalTable.UniqueConstraints); Assert.Single(principalTable.Indexes); - var dependentTable = Assert.Single(dbModel.Tables.Where(t => t.Schema == "db2" && t.Name == "DependentTable")); + var dependentTable = Assert.Single(dbModel.Tables.Where(t => t is { Schema: "db2", Name: "DependentTable" })); // ReSharper disable once PossibleNullReferenceException Assert.Single(dependentTable.ForeignKeys); }, diff --git a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerDatabaseCleaner.cs b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerDatabaseCleaner.cs index 050192bf665..19366c614c3 100644 --- a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerDatabaseCleaner.cs +++ b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerDatabaseCleaner.cs @@ -22,7 +22,7 @@ protected override IDatabaseModelFactory CreateDatabaseModelFactory(ILoggerFacto } protected override bool AcceptTable(DatabaseTable table) - => !(table is DatabaseView); + => table is not DatabaseView; protected override bool AcceptIndex(DatabaseIndex index) => false; diff --git a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/TestSqlServerRetryingExecutionStrategy.cs b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/TestSqlServerRetryingExecutionStrategy.cs index 3d92c3644a1..e1b27c6318f 100644 --- a/test/EFCore.SqlServer.FunctionalTests/TestUtilities/TestSqlServerRetryingExecutionStrategy.cs +++ b/test/EFCore.SqlServer.FunctionalTests/TestUtilities/TestSqlServerRetryingExecutionStrategy.cs @@ -62,8 +62,7 @@ protected override bool ShouldRetryOn(Exception exception) throw new InvalidOperationException(message + exception, exception); } - return exception is InvalidOperationException invalidOperationException - && invalidOperationException.Message == "Internal .Net Framework Data Provider error 6."; + return exception is InvalidOperationException { Message: "Internal .Net Framework Data Provider error 6." }; } public new virtual TimeSpan? GetNextDelay(Exception lastException) diff --git a/test/EFCore.SqlServer.HierarchyId.Tests/Test/Models/Migrations/AnonymousArraySeedContext.cs b/test/EFCore.SqlServer.HierarchyId.Tests/Test/Models/Migrations/AnonymousArraySeedContext.cs index 4c1de1c5539..fdf062c5825 100644 --- a/test/EFCore.SqlServer.HierarchyId.Tests/Test/Models/Migrations/AnonymousArraySeedContext.cs +++ b/test/EFCore.SqlServer.HierarchyId.Tests/Test/Models/Migrations/AnonymousArraySeedContext.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal; - namespace Microsoft.EntityFrameworkCore.SqlServer.Test.Models.Migrations; internal sealed class AnonymousArraySeedContext : MigrationContext diff --git a/test/EFCore.SqlServer.HierarchyId.Tests/Test/Models/Migrations/TypedArraySeedContext.cs b/test/EFCore.SqlServer.HierarchyId.Tests/Test/Models/Migrations/TypedArraySeedContext.cs index 6d19e79ee98..6698c71e381 100644 --- a/test/EFCore.SqlServer.HierarchyId.Tests/Test/Models/Migrations/TypedArraySeedContext.cs +++ b/test/EFCore.SqlServer.HierarchyId.Tests/Test/Models/Migrations/TypedArraySeedContext.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal; - namespace Microsoft.EntityFrameworkCore.SqlServer.Test.Models.Migrations; internal sealed class TypedArraySeedContext : MigrationContext diff --git a/test/EFCore.SqlServer.Tests/Metadata/Conventions/SqlServerOutputClauseConventionTest.cs b/test/EFCore.SqlServer.Tests/Metadata/Conventions/SqlServerOutputClauseConventionTest.cs index c479e0993dc..10ef8d3738b 100644 --- a/test/EFCore.SqlServer.Tests/Metadata/Conventions/SqlServerOutputClauseConventionTest.cs +++ b/test/EFCore.SqlServer.Tests/Metadata/Conventions/SqlServerOutputClauseConventionTest.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.SqlServer.Internal; - namespace Microsoft.EntityFrameworkCore.Metadata.Conventions; #nullable enable diff --git a/test/EFCore.SqlServer.Tests/Metadata/SqlServerBuilderExtensionsTest.cs b/test/EFCore.SqlServer.Tests/Metadata/SqlServerBuilderExtensionsTest.cs index 1c338a09f9f..96614ca705f 100644 --- a/test/EFCore.SqlServer.Tests/Metadata/SqlServerBuilderExtensionsTest.cs +++ b/test/EFCore.SqlServer.Tests/Metadata/SqlServerBuilderExtensionsTest.cs @@ -3,8 +3,6 @@ // ReSharper disable InconsistentNaming -using Microsoft.EntityFrameworkCore.SqlServer.Internal; - namespace Microsoft.EntityFrameworkCore.Metadata; public class SqlServerBuilderExtensionsTest diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/NorthwindCompiledQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/NorthwindCompiledQuerySqliteTest.cs index 0c17fbff107..39151295b81 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/NorthwindCompiledQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/NorthwindCompiledQuerySqliteTest.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.TestModels.Northwind; - namespace Microsoft.EntityFrameworkCore.Query; public class NorthwindCompiledQuerySqliteTest : NorthwindCompiledQueryTestBase> diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/NorthwindMiscellaneousQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/NorthwindMiscellaneousQuerySqliteTest.cs index 7c3d24ac3af..36fe5550a9e 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/NorthwindMiscellaneousQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/NorthwindMiscellaneousQuerySqliteTest.cs @@ -3,7 +3,6 @@ using Microsoft.EntityFrameworkCore.Sqlite.Internal; using Microsoft.EntityFrameworkCore.TestModels.Northwind; -using Xunit.Sdk; namespace Microsoft.EntityFrameworkCore.Query; diff --git a/test/EFCore.Sqlite.FunctionalTests/Query/NullSemanticsQuerySqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Query/NullSemanticsQuerySqliteTest.cs index f1d0e1adc6d..d1f34b107a6 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Query/NullSemanticsQuerySqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Query/NullSemanticsQuerySqliteTest.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.EntityFrameworkCore.TestModels.NullSemanticsModel; -using Xunit.Sdk; namespace Microsoft.EntityFrameworkCore.Query; diff --git a/test/EFCore.Tests/ChangeTracking/Internal/OwnedFixupTest.cs b/test/EFCore.Tests/ChangeTracking/Internal/OwnedFixupTest.cs index 4138fd1fcc0..07f67033a47 100644 --- a/test/EFCore.Tests/ChangeTracking/Internal/OwnedFixupTest.cs +++ b/test/EFCore.Tests/ChangeTracking/Internal/OwnedFixupTest.cs @@ -4,7 +4,6 @@ using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore.Diagnostics.Internal; -using Microsoft.EntityFrameworkCore.Internal; // ReSharper disable UnusedParameter.Local // ReSharper disable UnusedAutoPropertyAccessor.Local diff --git a/test/EFCore.Tests/ChangeTracking/ObservableHashSetTest.cs b/test/EFCore.Tests/ChangeTracking/ObservableHashSetTest.cs index 744d43f3c96..da475cb42d4 100644 --- a/test/EFCore.Tests/ChangeTracking/ObservableHashSetTest.cs +++ b/test/EFCore.Tests/ChangeTracking/ObservableHashSetTest.cs @@ -4,7 +4,6 @@ using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; -using Microsoft.EntityFrameworkCore.Internal; namespace Microsoft.EntityFrameworkCore.ChangeTracking; diff --git a/test/EFCore.Tests/ChangeTracking/TrackGraphTestBase.cs b/test/EFCore.Tests/ChangeTracking/TrackGraphTestBase.cs index 280958b32a8..516060b4b38 100644 --- a/test/EFCore.Tests/ChangeTracking/TrackGraphTestBase.cs +++ b/test/EFCore.Tests/ChangeTracking/TrackGraphTestBase.cs @@ -1024,7 +1024,7 @@ public void Can_attach_parent_with_some_new_and_some_existing_entities() TrackGraph( changeTracker.Context, category, - node => node.Entry.State = node.Entry.Entity is Product product && product.Id == 0 + node => node.Entry.State = node.Entry.Entity is Product { Id: 0 } ? EntityState.Added : EntityState.Unchanged)); }); diff --git a/test/EFCore.Tests/ExceptionTest.cs b/test/EFCore.Tests/ExceptionTest.cs index 19a9c95434e..f53c70e982b 100644 --- a/test/EFCore.Tests/ExceptionTest.cs +++ b/test/EFCore.Tests/ExceptionTest.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Runtime.Serialization.Formatters.Binary; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; diff --git a/test/EFCore.Tests/Extensions/QueryableExtensionsTest.cs b/test/EFCore.Tests/Extensions/QueryableExtensionsTest.cs index 843e83ea9a6..c75fa505db0 100644 --- a/test/EFCore.Tests/Extensions/QueryableExtensionsTest.cs +++ b/test/EFCore.Tests/Extensions/QueryableExtensionsTest.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.TestModels.Northwind; // ReSharper disable InconsistentNaming diff --git a/test/EFCore.Tests/Metadata/Internal/ClrCollectionAccessorFactoryTest.cs b/test/EFCore.Tests/Metadata/Internal/ClrCollectionAccessorFactoryTest.cs index b738c4b266d..9a984c64fc8 100644 --- a/test/EFCore.Tests/Metadata/Internal/ClrCollectionAccessorFactoryTest.cs +++ b/test/EFCore.Tests/Metadata/Internal/ClrCollectionAccessorFactoryTest.cs @@ -506,7 +506,7 @@ private class MyEntityWithCustomComparer public int Id { get; set; } public override bool Equals(object obj) - => obj != null && obj is MyEntityWithCustomComparer other && Id == other.Id; + => obj is MyEntityWithCustomComparer other && Id == other.Id; public override int GetHashCode() => Id.GetHashCode(); diff --git a/test/EFCore.Tests/Storage/TimeOnlyConvertersTest.cs b/test/EFCore.Tests/Storage/TimeOnlyConvertersTest.cs index df1abd17425..4f3c25dc366 100644 --- a/test/EFCore.Tests/Storage/TimeOnlyConvertersTest.cs +++ b/test/EFCore.Tests/Storage/TimeOnlyConvertersTest.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal; - namespace Microsoft.EntityFrameworkCore.Storage; public class TimeOnlyConvertersTest diff --git a/test/EFCore.Tests/Storage/ValueComparerTest.cs b/test/EFCore.Tests/Storage/ValueComparerTest.cs index 5d77bf9a0cd..548017539f5 100644 --- a/test/EFCore.Tests/Storage/ValueComparerTest.cs +++ b/test/EFCore.Tests/Storage/ValueComparerTest.cs @@ -266,7 +266,7 @@ private bool Equals(JustAClassWithEquality other) => A == other.A; public override bool Equals(object obj) - => !(obj is null) + => obj is not null && (ReferenceEquals(this, obj) || obj is JustAClassWithEquality o && Equals(o)); diff --git a/test/Microsoft.Data.Sqlite.Tests/SqliteTransactionTest.cs b/test/Microsoft.Data.Sqlite.Tests/SqliteTransactionTest.cs index 984c63b8b6c..b48a2812138 100644 --- a/test/Microsoft.Data.Sqlite.Tests/SqliteTransactionTest.cs +++ b/test/Microsoft.Data.Sqlite.Tests/SqliteTransactionTest.cs @@ -3,7 +3,6 @@ using System; using System.Data; -using System.IO; using Microsoft.Data.Sqlite.Properties; using Xunit; using static SQLitePCL.raw; @@ -15,28 +14,24 @@ public class SqliteTransactionTest [Fact] public void Ctor_sets_read_uncommitted() { - using (var connection = new SqliteConnection("Data Source=:memory:;Cache=Shared")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:;Cache=Shared"); + connection.Open(); - using (connection.BeginTransaction(IsolationLevel.ReadUncommitted)) - { - Assert.Equal(1L, connection.ExecuteScalar("PRAGMA read_uncommitted;")); - } + using (connection.BeginTransaction(IsolationLevel.ReadUncommitted)) + { + Assert.Equal(1L, connection.ExecuteScalar("PRAGMA read_uncommitted;")); } } [Fact] public void Ctor_unsets_read_uncommitted_when_serializable() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - using (connection.BeginTransaction(IsolationLevel.Serializable)) - { - Assert.Equal(0L, connection.ExecuteScalar("PRAGMA read_uncommitted;")); - } + using (connection.BeginTransaction(IsolationLevel.Serializable)) + { + Assert.Equal(0L, connection.ExecuteScalar("PRAGMA read_uncommitted;")); } } @@ -45,14 +40,12 @@ public void Ctor_unsets_read_uncommitted_when_serializable() [InlineData(IsolationLevel.Snapshot)] public void Ctor_throws_when_invalid_isolation_level(IsolationLevel isolationLevel) { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - var ex = Assert.Throws(() => connection.BeginTransaction(isolationLevel)); + var ex = Assert.Throws(() => connection.BeginTransaction(isolationLevel)); - Assert.Equal(Resources.InvalidIsolationLevel(isolationLevel), ex.Message); - } + Assert.Equal(Resources.InvalidIsolationLevel(isolationLevel), ex.Message); } [Fact] @@ -60,33 +53,31 @@ public void ReadUncommitted_allows_dirty_reads() { const string connectionString = "Data Source=read-uncommitted;Mode=Memory;Cache=Shared"; - using (var connection1 = new SqliteConnection(connectionString)) - using (var connection2 = new SqliteConnection(connectionString)) - { - connection1.Open(); - connection2.Open(); + using var connection1 = new SqliteConnection(connectionString); + using var connection2 = new SqliteConnection(connectionString); + connection1.Open(); + connection2.Open(); - connection1.ExecuteNonQuery("CREATE TABLE Data (Value); INSERT INTO Data VALUES (0);"); + connection1.ExecuteNonQuery("CREATE TABLE Data (Value); INSERT INTO Data VALUES (0);"); - using (connection1.BeginTransaction()) + using (connection1.BeginTransaction()) + { + using (connection2.BeginTransaction(IsolationLevel.ReadUncommitted)) { - using (connection2.BeginTransaction(IsolationLevel.ReadUncommitted)) - { - connection1.ExecuteNonQuery("UPDATE Data SET Value = 1;"); + connection1.ExecuteNonQuery("UPDATE Data SET Value = 1;"); - var value = connection2.ExecuteScalar("SELECT * FROM Data;"); + var value = connection2.ExecuteScalar("SELECT * FROM Data;"); - Assert.Equal(1, value); - } + Assert.Equal(1, value); + } - connection2.DefaultTimeout = 1; + connection2.DefaultTimeout = 1; - var ex = Assert.Throws( - () => connection2.ExecuteScalar("SELECT * FROM Data;")); + var ex = Assert.Throws( + () => connection2.ExecuteScalar("SELECT * FROM Data;")); - Assert.Equal(SQLITE_LOCKED, ex.SqliteErrorCode); - Assert.Equal(SQLITE_LOCKED_SHAREDCACHE, ex.SqliteExtendedErrorCode); - } + Assert.Equal(SQLITE_LOCKED, ex.SqliteErrorCode); + Assert.Equal(SQLITE_LOCKED_SHAREDCACHE, ex.SqliteExtendedErrorCode); } } @@ -95,32 +86,30 @@ public void Serialized_disallows_dirty_reads() { const string connectionString = "Data Source=serialized;Mode=Memory;Cache=Shared"; - using (var connection1 = new SqliteConnection(connectionString)) - using (var connection2 = new SqliteConnection(connectionString)) - { - connection1.Open(); - connection2.Open(); + using var connection1 = new SqliteConnection(connectionString); + using var connection2 = new SqliteConnection(connectionString); + connection1.Open(); + connection2.Open(); - connection1.ExecuteNonQuery("CREATE TABLE Data (Value); INSERT INTO Data VALUES (0);"); + connection1.ExecuteNonQuery("CREATE TABLE Data (Value); INSERT INTO Data VALUES (0);"); - using (connection1.BeginTransaction()) - { - connection1.ExecuteNonQuery("UPDATE Data SET Value = 1;"); + using (connection1.BeginTransaction()) + { + connection1.ExecuteNonQuery("UPDATE Data SET Value = 1;"); - connection2.DefaultTimeout = 1; + connection2.DefaultTimeout = 1; - var ex = Assert.Throws( - () => + var ex = Assert.Throws( + () => + { + using (connection2.BeginTransaction(IsolationLevel.Serializable)) { - using (connection2.BeginTransaction(IsolationLevel.Serializable)) - { - connection2.ExecuteScalar("SELECT * FROM Data;"); - } - }); - - Assert.Equal(SQLITE_LOCKED, ex.SqliteErrorCode); - Assert.Equal(SQLITE_LOCKED_SHAREDCACHE, ex.SqliteExtendedErrorCode); - } + connection2.ExecuteScalar("SELECT * FROM Data;"); + } + }); + + Assert.Equal(SQLITE_LOCKED, ex.SqliteErrorCode); + Assert.Equal(SQLITE_LOCKED_SHAREDCACHE, ex.SqliteExtendedErrorCode); } } @@ -129,24 +118,22 @@ public void Deferred_allows_parallel_reads() { const string connectionString = "Data Source=deferred;Mode=Memory;Cache=Shared"; - using (var connection1 = new SqliteConnection(connectionString)) - using (var connection2 = new SqliteConnection(connectionString)) - { - connection1.Open(); - connection2.Open(); + using var connection1 = new SqliteConnection(connectionString); + using var connection2 = new SqliteConnection(connectionString); + connection1.Open(); + connection2.Open(); - connection1.ExecuteNonQuery("CREATE TABLE Data (Value); INSERT INTO Data VALUES (42);"); + connection1.ExecuteNonQuery("CREATE TABLE Data (Value); INSERT INTO Data VALUES (42);"); - using (connection1.BeginTransaction(deferred: true)) - { - var value1 = connection1.ExecuteScalar("SELECT * FROM Data;"); - Assert.Equal(42L, value1); + using (connection1.BeginTransaction(deferred: true)) + { + var value1 = connection1.ExecuteScalar("SELECT * FROM Data;"); + Assert.Equal(42L, value1); - using (connection2.BeginTransaction(deferred: true)) - { - var value2 = connection2.ExecuteScalar("SELECT * FROM Data;"); - Assert.Equal(42L, value2); - } + using (connection2.BeginTransaction(deferred: true)) + { + var value2 = connection2.ExecuteScalar("SELECT * FROM Data;"); + Assert.Equal(42L, value2); } } } @@ -154,15 +141,11 @@ public void Deferred_allows_parallel_reads() [Fact] public void IsolationLevel_is_serializable_when_unspecified() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - using (var transaction = connection.BeginTransaction()) - { - Assert.Equal(IsolationLevel.Serializable, transaction.IsolationLevel); - } - } + using var transaction = connection.BeginTransaction(); + Assert.Equal(IsolationLevel.Serializable, transaction.IsolationLevel); } [Theory] @@ -171,182 +154,154 @@ public void IsolationLevel_is_serializable_when_unspecified() [InlineData(IsolationLevel.RepeatableRead)] public void IsolationLevel_is_increased_when_unsupported(IsolationLevel isolationLevel) { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - using (var transaction = connection.BeginTransaction(isolationLevel)) - { - Assert.Equal(IsolationLevel.Serializable, transaction.IsolationLevel); - } - } + using var transaction = connection.BeginTransaction(isolationLevel); + Assert.Equal(IsolationLevel.Serializable, transaction.IsolationLevel); } [Fact] public void Commit_throws_when_completed() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - var transaction = connection.BeginTransaction(); - transaction.Dispose(); + var transaction = connection.BeginTransaction(); + transaction.Dispose(); - var ex = Assert.Throws(() => transaction.Commit()); + var ex = Assert.Throws(() => transaction.Commit()); - Assert.Equal(Resources.TransactionCompleted, ex.Message); - } + Assert.Equal(Resources.TransactionCompleted, ex.Message); } [Fact] public void Commit_throws_when_completed_externally() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - using (var transaction = connection.BeginTransaction()) - { - connection.ExecuteNonQuery("ROLLBACK;"); + using var transaction = connection.BeginTransaction(); + connection.ExecuteNonQuery("ROLLBACK;"); - var ex = Assert.Throws(() => transaction.Commit()); + var ex = Assert.Throws(() => transaction.Commit()); - Assert.Equal(Resources.TransactionCompleted, ex.Message); - } - } + Assert.Equal(Resources.TransactionCompleted, ex.Message); } [Fact] public void Commit_throws_when_connection_closed() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - using (var transaction = connection.BeginTransaction()) - { - connection.Close(); + using var transaction = connection.BeginTransaction(); + connection.Close(); - var ex = Assert.Throws(() => transaction.Commit()); + var ex = Assert.Throws(() => transaction.Commit()); - Assert.Equal(Resources.TransactionCompleted, ex.Message); - } - } + Assert.Equal(Resources.TransactionCompleted, ex.Message); } [Fact] public void Commit_works() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); - CreateTestTable(connection); - - using (var transaction = connection.BeginTransaction()) - { - connection.ExecuteNonQuery("INSERT INTO TestTable VALUES (1);"); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + CreateTestTable(connection); - transaction.Commit(); + using (var transaction = connection.BeginTransaction()) + { + connection.ExecuteNonQuery("INSERT INTO TestTable VALUES (1);"); - Assert.Null(connection.Transaction); - Assert.Null(transaction.Connection); - } + transaction.Commit(); - Assert.Equal(1L, connection.ExecuteScalar("SELECT COUNT(*) FROM TestTable;")); + Assert.Null(connection.Transaction); + Assert.Null(transaction.Connection); } + + Assert.Equal(1L, connection.ExecuteScalar("SELECT COUNT(*) FROM TestTable;")); } [Fact] public void Rollback_noops_once_when_completed_externally() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - using (var transaction = connection.BeginTransaction()) - { - connection.ExecuteNonQuery("ROLLBACK;"); + using var transaction = connection.BeginTransaction(); + connection.ExecuteNonQuery("ROLLBACK;"); - transaction.Rollback(); - var ex = Assert.Throws(() => transaction.Rollback()); + transaction.Rollback(); + var ex = Assert.Throws(() => transaction.Rollback()); - Assert.Equal(Resources.TransactionCompleted, ex.Message); - } - } + Assert.Equal(Resources.TransactionCompleted, ex.Message); } [Fact] public void Rollback_throws_when_completed() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - var transaction = connection.BeginTransaction(); - transaction.Dispose(); + var transaction = connection.BeginTransaction(); + transaction.Dispose(); - var ex = Assert.Throws(() => transaction.Rollback()); + var ex = Assert.Throws(() => transaction.Rollback()); - Assert.Equal(Resources.TransactionCompleted, ex.Message); - } + Assert.Equal(Resources.TransactionCompleted, ex.Message); } [Fact] public void Rollback_works() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); - CreateTestTable(connection); - - using (var transaction = connection.BeginTransaction()) - { - connection.ExecuteNonQuery("INSERT INTO TestTable VALUES (1);"); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + CreateTestTable(connection); - transaction.Rollback(); + using (var transaction = connection.BeginTransaction()) + { + connection.ExecuteNonQuery("INSERT INTO TestTable VALUES (1);"); - Assert.Null(connection.Transaction); - Assert.Null(transaction.Connection); - } + transaction.Rollback(); - Assert.Equal(0L, connection.ExecuteScalar("SELECT COUNT(*) FROM TestTable;")); + Assert.Null(connection.Transaction); + Assert.Null(transaction.Connection); } + + Assert.Equal(0L, connection.ExecuteScalar("SELECT COUNT(*) FROM TestTable;")); } [Fact] public void Dispose_works() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); - CreateTestTable(connection); - - using (var transaction = connection.BeginTransaction()) - { - connection.ExecuteNonQuery("INSERT INTO TestTable VALUES (1);"); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); + CreateTestTable(connection); - transaction.Dispose(); + using (var transaction = connection.BeginTransaction()) + { + connection.ExecuteNonQuery("INSERT INTO TestTable VALUES (1);"); - Assert.Null(connection.Transaction); - Assert.Null(transaction.Connection); - } + transaction.Dispose(); - Assert.Equal(0L, connection.ExecuteScalar("SELECT COUNT(*) FROM TestTable;")); + Assert.Null(connection.Transaction); + Assert.Null(transaction.Connection); } + + Assert.Equal(0L, connection.ExecuteScalar("SELECT COUNT(*) FROM TestTable;")); } [Fact] public void Dispose_can_be_called_more_than_once() { - using (var connection = new SqliteConnection("Data Source=:memory:")) - { - connection.Open(); + using var connection = new SqliteConnection("Data Source=:memory:"); + connection.Open(); - var transaction = connection.BeginTransaction(); + var transaction = connection.BeginTransaction(); - transaction.Dispose(); - transaction.Dispose(); - } + transaction.Dispose(); + transaction.Dispose(); } [Fact] @@ -370,12 +325,6 @@ public void Savepoint() } private static void CreateTestTable(SqliteConnection connection) - { - connection.ExecuteNonQuery( - @" - CREATE TABLE TestTable ( - TestColumn INTEGER - )"); - } + => connection.ExecuteNonQuery("CREATE TABLE TestTable (TestColumn INTEGER)"); } }