diff --git a/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs b/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs index 22ac9ad57c9..b35cd851d77 100644 --- a/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs +++ b/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs @@ -79,7 +79,8 @@ public virtual void RemoveAnnotationsHandledByConventions(IModel model, IDiction /// public virtual void RemoveAnnotationsHandledByConventions( - IEntityType entityType, IDictionary annotations) + IEntityType entityType, + IDictionary annotations) { annotations.Remove(RelationalAnnotationNames.IsTableExcludedFromMigrations); @@ -88,7 +89,8 @@ public virtual void RemoveAnnotationsHandledByConventions( /// public virtual void RemoveAnnotationsHandledByConventions( - IProperty property, IDictionary annotations) + IProperty property, + IDictionary annotations) { var columnName = property.GetColumnName(); if (columnName == property.Name) @@ -105,7 +107,8 @@ public virtual void RemoveAnnotationsHandledByConventions(IKey key, IDictionary< /// public virtual void RemoveAnnotationsHandledByConventions( - IForeignKey foreignKey, IDictionary annotations) + IForeignKey foreignKey, + IDictionary annotations) => RemoveConventionalAnnotationsHelper(foreignKey, annotations, IsHandledByConvention); /// @@ -114,7 +117,8 @@ public virtual void RemoveAnnotationsHandledByConventions(IIndex index, IDiction /// public virtual IReadOnlyList GenerateFluentApiCalls( - IModel model, IDictionary annotations) + IModel model, + IDictionary annotations) { var methodCallCodeFragments = new List(); @@ -129,7 +133,8 @@ public virtual IReadOnlyList GenerateFluentApiCalls( /// public virtual IReadOnlyList GenerateFluentApiCalls( - IEntityType entityType, IDictionary annotations) + IEntityType entityType, + IDictionary annotations) { var methodCallCodeFragments = new List(); @@ -144,7 +149,8 @@ public virtual IReadOnlyList GenerateFluentApiCalls( /// public virtual IReadOnlyList GenerateFluentApiCalls( - IProperty property, IDictionary annotations) + IProperty property, + IDictionary annotations) { var methodCallCodeFragments = new List(); @@ -167,16 +173,16 @@ public virtual IReadOnlyList GenerateFluentApiCalls( { methodCallCodeFragments.Add( computedColumnSql?.Length == 0 - ? new MethodCallCodeFragment( - nameof(RelationalPropertyBuilderExtensions.HasComputedColumnSql)) - : TryGetAndRemove(annotations, RelationalAnnotationNames.IsStored, out bool isStored) ? new MethodCallCodeFragment( - nameof(RelationalPropertyBuilderExtensions.HasComputedColumnSql), - computedColumnSql, - isStored) - : new MethodCallCodeFragment( - nameof(RelationalPropertyBuilderExtensions.HasComputedColumnSql), - computedColumnSql)); + nameof(RelationalPropertyBuilderExtensions.HasComputedColumnSql)) + : TryGetAndRemove(annotations, RelationalAnnotationNames.IsStored, out bool isStored) + ? new MethodCallCodeFragment( + nameof(RelationalPropertyBuilderExtensions.HasComputedColumnSql), + computedColumnSql, + isStored) + : new MethodCallCodeFragment( + nameof(RelationalPropertyBuilderExtensions.HasComputedColumnSql), + computedColumnSql)); } GenerateSimpleFluentApiCall( @@ -199,7 +205,8 @@ public virtual IReadOnlyList GenerateFluentApiCalls( /// public virtual IReadOnlyList GenerateFluentApiCalls( - IKey key, IDictionary annotations) + IKey key, + IDictionary annotations) { var methodCallCodeFragments = new List(); @@ -214,7 +221,8 @@ public virtual IReadOnlyList GenerateFluentApiCalls( /// public virtual IReadOnlyList GenerateFluentApiCalls( - IForeignKey navigation, IDictionary annotations) + IForeignKey navigation, + IDictionary annotations) { var methodCallCodeFragments = new List(); @@ -229,7 +237,8 @@ public virtual IReadOnlyList GenerateFluentApiCalls( /// public virtual IReadOnlyList GenerateFluentApiCalls( - INavigation navigation, IDictionary annotations) + INavigation navigation, + IDictionary annotations) { var methodCallCodeFragments = new List(); @@ -240,7 +249,8 @@ public virtual IReadOnlyList GenerateFluentApiCalls( /// public virtual IReadOnlyList GenerateFluentApiCalls( - ISkipNavigation navigation, IDictionary annotations) + ISkipNavigation navigation, + IDictionary annotations) { var methodCallCodeFragments = new List(); @@ -251,7 +261,8 @@ public virtual IReadOnlyList GenerateFluentApiCalls( /// public virtual IReadOnlyList GenerateFluentApiCalls( - IIndex index, IDictionary annotations) + IIndex index, + IDictionary annotations) { var methodCallCodeFragments = new List(); @@ -270,7 +281,8 @@ public virtual IReadOnlyList GenerateFluentApiCalls( /// public virtual IReadOnlyList GenerateDataAnnotationAttributes( - IEntityType entityType, IDictionary annotations) + IEntityType entityType, + IDictionary annotations) { var attributeCodeFragments = new List(); @@ -281,7 +293,8 @@ public virtual IReadOnlyList GenerateDataAnnotationAttrib /// public virtual IReadOnlyList GenerateDataAnnotationAttributes( - IProperty property, IDictionary annotations) + IProperty property, + IDictionary annotations) { var attributeCodeFragments = new List(); @@ -312,8 +325,8 @@ public virtual IReadOnlyList GenerateDataAnnotationAttrib /// The . /// The . /// - /// if the annotation is handled by convention; - /// if code must be generated. + /// if the annotation is handled by convention; + /// if code must be generated. /// protected virtual bool IsHandledByConvention([NotNull] IModel model, [NotNull] IAnnotation annotation) { diff --git a/src/EFCore.Relational/Design/AttributeCodeFragment.cs b/src/EFCore.Relational/Design/AttributeCodeFragment.cs index e74f9049a08..02b0d9bc100 100644 --- a/src/EFCore.Relational/Design/AttributeCodeFragment.cs +++ b/src/EFCore.Relational/Design/AttributeCodeFragment.cs @@ -39,6 +39,7 @@ public AttributeCodeFragment([NotNull] Type type, [NotNull] params object[] argu /// Gets the method call's arguments. /// /// The method call's arguments. - public virtual IReadOnlyList Arguments => _arguments; + public virtual IReadOnlyList Arguments + => _arguments; } } diff --git a/src/EFCore.Relational/Design/IAnnotationCodeGenerator.cs b/src/EFCore.Relational/Design/IAnnotationCodeGenerator.cs index 2d8f06fcaad..e017e8117a8 100644 --- a/src/EFCore.Relational/Design/IAnnotationCodeGenerator.cs +++ b/src/EFCore.Relational/Design/IAnnotationCodeGenerator.cs @@ -61,7 +61,9 @@ void RemoveAnnotationsHandledByConventions([NotNull] IKey key, [NotNull] IDictio /// /// The foreign key to which the annotations are applied. /// The set of annotations from which to remove the conventional ones. - void RemoveAnnotationsHandledByConventions([NotNull] IForeignKey foreignKey, [NotNull] IDictionary annotations) { } + void RemoveAnnotationsHandledByConventions([NotNull] IForeignKey foreignKey, [NotNull] IDictionary annotations) + { + } /// /// Removes annotation whose configuration is already applied by convention, and do not need to be @@ -78,7 +80,8 @@ void RemoveAnnotationsHandledByConventions([NotNull] IIndex index, [NotNull] IDi /// The model to which the annotations are applied. /// The set of annotations from which to generate fluent API calls. IReadOnlyList GenerateFluentApiCalls( - [NotNull] IModel model, [NotNull] IDictionary annotations) + [NotNull] IModel model, + [NotNull] IDictionary annotations) => Array.Empty(); /// @@ -88,7 +91,8 @@ IReadOnlyList GenerateFluentApiCalls( /// The entity type to which the annotations are applied. /// The set of annotations from which to generate fluent API calls. IReadOnlyList GenerateFluentApiCalls( - [NotNull] IEntityType entityType, [NotNull] IDictionary annotations) + [NotNull] IEntityType entityType, + [NotNull] IDictionary annotations) => Array.Empty(); /// @@ -98,7 +102,8 @@ IReadOnlyList GenerateFluentApiCalls( /// The property to which the annotations are applied. /// The set of annotations from which to generate fluent API calls. IReadOnlyList GenerateFluentApiCalls( - [NotNull] IProperty property, [NotNull] IDictionary annotations) + [NotNull] IProperty property, + [NotNull] IDictionary annotations) => Array.Empty(); /// @@ -108,7 +113,8 @@ IReadOnlyList GenerateFluentApiCalls( /// The key to which the annotations are applied. /// The set of annotations from which to generate fluent API calls. IReadOnlyList GenerateFluentApiCalls( - [NotNull] IKey key, [NotNull] IDictionary annotations) + [NotNull] IKey key, + [NotNull] IDictionary annotations) => Array.Empty(); /// @@ -118,7 +124,8 @@ IReadOnlyList GenerateFluentApiCalls( /// The foreign key to which the annotations are applied. /// The set of annotations from which to generate fluent API calls. IReadOnlyList GenerateFluentApiCalls( - [NotNull] IForeignKey foreignKey, [NotNull] IDictionary annotations) + [NotNull] IForeignKey foreignKey, + [NotNull] IDictionary annotations) => Array.Empty(); /// @@ -128,7 +135,8 @@ IReadOnlyList GenerateFluentApiCalls( /// The navigation to which the annotations are applied. /// The set of annotations from which to generate fluent API calls. IReadOnlyList GenerateFluentApiCalls( - [NotNull] INavigation navigation, [NotNull] IDictionary annotations) + [NotNull] INavigation navigation, + [NotNull] IDictionary annotations) => Array.Empty(); /// @@ -138,7 +146,8 @@ IReadOnlyList GenerateFluentApiCalls( /// The skip navigation to which the annotations are applied. /// The set of annotations from which to generate fluent API calls. IReadOnlyList GenerateFluentApiCalls( - [NotNull] ISkipNavigation navigation, [NotNull] IDictionary annotations) + [NotNull] ISkipNavigation navigation, + [NotNull] IDictionary annotations) => Array.Empty(); /// @@ -148,7 +157,8 @@ IReadOnlyList GenerateFluentApiCalls( /// The index to which the annotations are applied. /// The set of annotations from which to generate fluent API calls. IReadOnlyList GenerateFluentApiCalls( - [NotNull] IIndex index, [NotNull] IDictionary annotations) + [NotNull] IIndex index, + [NotNull] IDictionary annotations) => Array.Empty(); /// @@ -158,7 +168,8 @@ IReadOnlyList GenerateFluentApiCalls( /// The entity type to which the annotations are applied. /// The set of annotations from which to generate fluent API calls. IReadOnlyList GenerateDataAnnotationAttributes( - [NotNull] IEntityType entityType, [NotNull] IDictionary annotations) + [NotNull] IEntityType entityType, + [NotNull] IDictionary annotations) => Array.Empty(); /// @@ -168,7 +179,8 @@ IReadOnlyList GenerateDataAnnotationAttributes( /// The property to which the annotations are applied. /// The set of annotations from which to generate fluent API calls. IReadOnlyList GenerateDataAnnotationAttributes( - [NotNull] IProperty property, [NotNull] IDictionary annotations) + [NotNull] IProperty property, + [NotNull] IDictionary annotations) => Array.Empty(); } } diff --git a/src/EFCore.Relational/Design/MethodCallCodeFragment.cs b/src/EFCore.Relational/Design/MethodCallCodeFragment.cs index 2dc86438887..3060783f61a 100644 --- a/src/EFCore.Relational/Design/MethodCallCodeFragment.cs +++ b/src/EFCore.Relational/Design/MethodCallCodeFragment.cs @@ -55,7 +55,8 @@ public MethodCallCodeFragment( /// Gets the method call's arguments. /// /// The method call's arguments. - public virtual IReadOnlyList Arguments => _arguments; + public virtual IReadOnlyList Arguments + => _arguments; /// /// Gets the next method call to chain after this. diff --git a/src/EFCore.Relational/Diagnostics/DbCommandInterceptor.cs b/src/EFCore.Relational/Diagnostics/DbCommandInterceptor.cs index 2cbe83882a3..0250ec5fc8f 100644 --- a/src/EFCore.Relational/Diagnostics/DbCommandInterceptor.cs +++ b/src/EFCore.Relational/Diagnostics/DbCommandInterceptor.cs @@ -21,7 +21,7 @@ public abstract class DbCommandInterceptor : IDbCommandInterceptor /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -33,7 +33,8 @@ public abstract class DbCommandInterceptor : IDbCommandInterceptor /// is to return the value passed in. /// public virtual InterceptionResult CommandCreating( - CommandCorrelatedEventData eventData, InterceptionResult result) + CommandCorrelatedEventData eventData, + InterceptionResult result) => result; /// @@ -66,7 +67,7 @@ public virtual DbCommand CommandCreated(CommandEndEventData eventData, DbCommand /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -90,7 +91,7 @@ public virtual InterceptionResult ReaderExecuting( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -114,7 +115,7 @@ public virtual InterceptionResult ScalarExecuting( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -138,7 +139,7 @@ public virtual InterceptionResult NonQueryExecuting( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -164,7 +165,7 @@ public virtual ValueTask> ReaderExecutingAsync( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -190,7 +191,7 @@ public virtual ValueTask> ScalarExecutingAsync( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -402,7 +403,7 @@ public virtual Task CommandFailedAsync( /// Contextual information about the command and reader. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// diff --git a/src/EFCore.Relational/Diagnostics/DbConnectionInterceptor.cs b/src/EFCore.Relational/Diagnostics/DbConnectionInterceptor.cs index 0f78a1735ee..47483fcbcc0 100644 --- a/src/EFCore.Relational/Diagnostics/DbConnectionInterceptor.cs +++ b/src/EFCore.Relational/Diagnostics/DbConnectionInterceptor.cs @@ -22,7 +22,7 @@ public abstract class DbConnectionInterceptor : IDbConnectionInterceptor /// Contextual information about the connection. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -46,7 +46,7 @@ public virtual InterceptionResult ConnectionOpening( /// Contextual information about the connection. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -94,7 +94,7 @@ public virtual Task ConnectionOpenedAsync( /// Contextual information about the connection. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -118,7 +118,7 @@ public virtual InterceptionResult ConnectionClosing( /// Contextual information about the connection. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// diff --git a/src/EFCore.Relational/Diagnostics/DbTransactionInterceptor.cs b/src/EFCore.Relational/Diagnostics/DbTransactionInterceptor.cs index 6b1be0edadc..68f7fd92017 100644 --- a/src/EFCore.Relational/Diagnostics/DbTransactionInterceptor.cs +++ b/src/EFCore.Relational/Diagnostics/DbTransactionInterceptor.cs @@ -23,7 +23,7 @@ public abstract class DbTransactionInterceptor : IDbTransactionInterceptor /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -74,7 +74,7 @@ public virtual DbTransaction TransactionStarted( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -87,14 +87,17 @@ public virtual DbTransaction TransactionStarted( /// is to return the value passed in, often using /// public virtual ValueTask> TransactionStartingAsync( - DbConnection connection, TransactionStartingEventData eventData, InterceptionResult result, + DbConnection connection, + TransactionStartingEventData eventData, + InterceptionResult result, CancellationToken cancellationToken = default) => new ValueTask>(result); /// /// /// Called immediately after EF calls - /// . + /// + /// . /// /// /// This method is still called if an interceptor suppressed creation in . @@ -115,7 +118,10 @@ public virtual ValueTask> TransactionStartingA /// is to return the value passed in, often using /// public virtual ValueTask TransactionStartedAsync( - DbConnection connection, TransactionEndEventData eventData, DbTransaction result, CancellationToken cancellationToken = default) + DbConnection connection, + TransactionEndEventData eventData, + DbTransaction result, + CancellationToken cancellationToken = default) => new ValueTask(result); /// @@ -172,7 +178,7 @@ public virtual ValueTask TransactionUsedAsync( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -208,7 +214,7 @@ public virtual void TransactionCommitted( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -247,7 +253,7 @@ public virtual Task TransactionCommittedAsync( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -283,7 +289,7 @@ public virtual void TransactionRolledBack( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// diff --git a/src/EFCore.Relational/Diagnostics/IDbCommandInterceptor.cs b/src/EFCore.Relational/Diagnostics/IDbCommandInterceptor.cs index a9b6df971f1..7509429489b 100644 --- a/src/EFCore.Relational/Diagnostics/IDbCommandInterceptor.cs +++ b/src/EFCore.Relational/Diagnostics/IDbCommandInterceptor.cs @@ -37,7 +37,7 @@ public interface IDbCommandInterceptor : IInterceptor /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -82,7 +82,7 @@ DbCommand CommandCreated( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -105,7 +105,7 @@ InterceptionResult ReaderExecuting( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -128,7 +128,7 @@ InterceptionResult ScalarExecuting( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -151,7 +151,7 @@ InterceptionResult NonQueryExecuting( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -176,7 +176,7 @@ ValueTask> ReaderExecutingAsync( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -201,7 +201,7 @@ ValueTask> ScalarExecutingAsync( /// Contextual information about the command and execution. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -403,7 +403,7 @@ Task CommandFailedAsync( /// Contextual information about the command and reader. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// diff --git a/src/EFCore.Relational/Diagnostics/IDbConnectionInterceptor.cs b/src/EFCore.Relational/Diagnostics/IDbConnectionInterceptor.cs index 9219ebbeb20..d5cb68f5351 100644 --- a/src/EFCore.Relational/Diagnostics/IDbConnectionInterceptor.cs +++ b/src/EFCore.Relational/Diagnostics/IDbConnectionInterceptor.cs @@ -38,7 +38,7 @@ public interface IDbConnectionInterceptor : IInterceptor /// Contextual information about the connection. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -61,7 +61,7 @@ InterceptionResult ConnectionOpening( /// Contextual information about the connection. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -107,7 +107,7 @@ Task ConnectionOpenedAsync( /// Contextual information about the connection. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -130,7 +130,7 @@ InterceptionResult ConnectionClosing( /// Contextual information about the connection. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// diff --git a/src/EFCore.Relational/Diagnostics/IDbTransactionInterceptor.cs b/src/EFCore.Relational/Diagnostics/IDbTransactionInterceptor.cs index adbba6b47c2..7c15aa510b0 100644 --- a/src/EFCore.Relational/Diagnostics/IDbTransactionInterceptor.cs +++ b/src/EFCore.Relational/Diagnostics/IDbTransactionInterceptor.cs @@ -39,7 +39,7 @@ public interface IDbTransactionInterceptor : IInterceptor /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -88,7 +88,7 @@ DbTransaction TransactionStarted( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -109,7 +109,8 @@ ValueTask> TransactionStartingAsync( /// /// /// Called immediately after EF calls - /// . + /// + /// . /// /// /// This method is still called if an interceptor suppressed creation in . @@ -187,7 +188,7 @@ ValueTask TransactionUsedAsync( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -220,7 +221,7 @@ void TransactionCommitted( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -257,7 +258,7 @@ Task TransactionCommittedAsync( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -290,7 +291,7 @@ void TransactionRolledBack( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -327,7 +328,7 @@ Task TransactionRolledBackAsync( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -359,7 +360,7 @@ void CreatedSavepoint( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -396,7 +397,7 @@ Task CreatedSavepointAsync( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -428,7 +429,7 @@ void RolledBackToSavepoint( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -465,7 +466,7 @@ Task RolledBackToSavepointAsync( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// @@ -497,7 +498,7 @@ void ReleasedSavepoint( /// Contextual information about connection and transaction. /// /// Represents the current result if one exists. - /// This value will have set to if some previous + /// This value will have set to if some previous /// interceptor suppressed execution by calling . /// This value is typically used as the return value for the implementation of this method. /// diff --git a/src/EFCore.Relational/Diagnostics/IndexWithPropertiesEventData.cs b/src/EFCore.Relational/Diagnostics/IndexWithPropertiesEventData.cs index 686ce11ba98..23d339e2f3a 100644 --- a/src/EFCore.Relational/Diagnostics/IndexWithPropertiesEventData.cs +++ b/src/EFCore.Relational/Diagnostics/IndexWithPropertiesEventData.cs @@ -11,7 +11,7 @@ namespace Microsoft.EntityFrameworkCore.Diagnostics { /// /// A event payload class for the - /// event. + /// event. /// public class IndexWithPropertiesEventData : EventData { diff --git a/src/EFCore.Relational/Diagnostics/Internal/DbCommandInterceptorAggregator.cs b/src/EFCore.Relational/Diagnostics/Internal/DbCommandInterceptorAggregator.cs index da27b612fc9..8b17ca527bd 100644 --- a/src/EFCore.Relational/Diagnostics/Internal/DbCommandInterceptorAggregator.cs +++ b/src/EFCore.Relational/Diagnostics/Internal/DbCommandInterceptorAggregator.cs @@ -237,7 +237,9 @@ public void CommandFailed(DbCommand command, CommandErrorEventData eventData) } public async Task CommandFailedAsync( - DbCommand command, CommandErrorEventData eventData, CancellationToken cancellationToken = default) + DbCommand command, + CommandErrorEventData eventData, + CancellationToken cancellationToken = default) { for (var i = 0; i < _interceptors.Length; i++) { diff --git a/src/EFCore.Relational/Diagnostics/RelationalEventId.cs b/src/EFCore.Relational/Diagnostics/RelationalEventId.cs index 95e21c8e198..655013a1408 100644 --- a/src/EFCore.Relational/Diagnostics/RelationalEventId.cs +++ b/src/EFCore.Relational/Diagnostics/RelationalEventId.cs @@ -95,7 +95,9 @@ private enum Id } private static readonly string _connectionPrefix = DbLoggerCategory.Database.Connection.Name + "."; - private static EventId MakeConnectionId(Id id) => new EventId((int)id, _connectionPrefix + id); + + private static EventId MakeConnectionId(Id id) + => new EventId((int)id, _connectionPrefix + id); /// /// @@ -163,7 +165,9 @@ private enum Id public static readonly EventId ConnectionError = MakeConnectionId(Id.ConnectionError); private static readonly string _sqlPrefix = DbLoggerCategory.Database.Command.Name + "."; - private static EventId MakeCommandId(Id id) => new EventId((int)id, _sqlPrefix + id); + + private static EventId MakeCommandId(Id id) + => new EventId((int)id, _sqlPrefix + id); /// /// @@ -231,7 +235,9 @@ private enum Id public static readonly EventId CommandError = MakeCommandId(Id.CommandError); private static readonly string _transactionPrefix = DbLoggerCategory.Database.Transaction.Name + "."; - private static EventId MakeTransactionId(Id id) => new EventId((int)id, _transactionPrefix + id); + + private static EventId MakeTransactionId(Id id) + => new EventId((int)id, _transactionPrefix + id); /// /// @@ -481,7 +487,9 @@ private enum Id public static readonly EventId DataReaderDisposing = MakeCommandId(Id.DataReaderDisposing); private static readonly string _migrationsPrefix = DbLoggerCategory.Migrations.Name + "."; - private static EventId MakeMigrationsId(Id id) => new EventId((int)id, _migrationsPrefix + id); + + private static EventId MakeMigrationsId(Id id) + => new EventId((int)id, _migrationsPrefix + id); /// /// @@ -588,7 +596,9 @@ private enum Id public static readonly EventId MigrationAttributeMissingWarning = MakeMigrationsId(Id.MigrationAttributeMissingWarning); private static readonly string _queryPrefix = DbLoggerCategory.Query.Name + "."; - private static EventId MakeQueryId(Id id) => new EventId((int)id, _queryPrefix + id); + + private static EventId MakeQueryId(Id id) + => new EventId((int)id, _queryPrefix + id); /// /// @@ -618,7 +628,7 @@ private enum Id /// /// - /// A query is loading multiple related collections without configuring a . + /// A query is loading multiple related collections without configuring a . /// /// /// This event is in the category. @@ -627,7 +637,9 @@ private enum Id public static readonly EventId MultipleCollectionIncludeWarning = MakeQueryId(Id.MultipleCollectionIncludeWarning); private static readonly string _validationPrefix = DbLoggerCategory.Model.Validation.Name + "."; - private static EventId MakeValidationId(Id id) => new EventId((int)id, _validationPrefix + id); + + private static EventId MakeValidationId(Id id) + => new EventId((int)id, _validationPrefix + id); /// /// @@ -666,7 +678,8 @@ private enum Id /// This event uses the payload when used with a . /// /// - public static readonly EventId AllIndexPropertiesNotToMappedToAnyTable = MakeValidationId(Id.AllIndexPropertiesNotToMappedToAnyTable); + public static readonly EventId AllIndexPropertiesNotToMappedToAnyTable = + MakeValidationId(Id.AllIndexPropertiesNotToMappedToAnyTable); /// /// @@ -679,7 +692,8 @@ private enum Id /// This event uses the payload when used with a . /// /// - public static readonly EventId IndexPropertiesBothMappedAndNotMappedToTable = MakeValidationId(Id.IndexPropertiesBothMappedAndNotMappedToTable); + public static readonly EventId IndexPropertiesBothMappedAndNotMappedToTable = + MakeValidationId(Id.IndexPropertiesBothMappedAndNotMappedToTable); /// /// @@ -692,10 +706,13 @@ private enum Id /// This event uses the payload when used with a . /// /// - public static readonly EventId IndexPropertiesMappedToNonOverlappingTables = MakeValidationId(Id.IndexPropertiesMappedToNonOverlappingTables); + public static readonly EventId IndexPropertiesMappedToNonOverlappingTables = + MakeValidationId(Id.IndexPropertiesMappedToNonOverlappingTables); private static readonly string _updatePrefix = DbLoggerCategory.Update.Name + "."; - private static EventId MakeUpdateId(Id id) => new EventId((int)id, _updatePrefix + id); + + private static EventId MakeUpdateId(Id id) + => new EventId((int)id, _updatePrefix + id); /// /// diff --git a/src/EFCore.Relational/Diagnostics/RelationalLoggerExtensions.cs b/src/EFCore.Relational/Diagnostics/RelationalLoggerExtensions.cs index 9e6318efa35..1648b1828f4 100644 --- a/src/EFCore.Relational/Diagnostics/RelationalLoggerExtensions.cs +++ b/src/EFCore.Relational/Diagnostics/RelationalLoggerExtensions.cs @@ -8,7 +8,6 @@ using System.Diagnostics; using System.Globalization; using System.Linq; -using System.Linq.Expressions; using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -20,7 +19,6 @@ using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations.Internal; -using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; @@ -4378,7 +4376,8 @@ public static void AllIndexPropertiesNotToMappedToAnyTable( if (diagnostics.ShouldLog(definition)) { - definition.Log(diagnostics, + definition.Log( + diagnostics, entityType.DisplayName(), index.Properties.Format()); } @@ -4401,7 +4400,8 @@ public static void AllIndexPropertiesNotToMappedToAnyTable( if (diagnostics.ShouldLog(definition)) { - definition.Log(diagnostics, + definition.Log( + diagnostics, index.Name, entityType.DisplayName(), index.Properties.Format()); @@ -4459,7 +4459,8 @@ public static void IndexPropertiesBothMappedAndNotMappedToTable( if (diagnostics.ShouldLog(definition)) { - definition.Log(diagnostics, + definition.Log( + diagnostics, entityType.DisplayName(), index.Properties.Format(), unmappedPropertyName); @@ -4484,7 +4485,8 @@ public static void IndexPropertiesBothMappedAndNotMappedToTable( if (diagnostics.ShouldLog(definition)) { - definition.Log(diagnostics, + definition.Log( + diagnostics, index.Name, entityType.DisplayName(), index.Properties.Format(), @@ -4552,13 +4554,14 @@ public static void IndexPropertiesMappedToNonOverlappingTables( if (diagnostics.ShouldLog(definition)) { - definition.Log(diagnostics, + definition.Log( + diagnostics, entityType.DisplayName(), index.Properties.Format(), - property1Name, - tablesMappedToProperty1.FormatTables(), - property2Name, - tablesMappedToProperty2.FormatTables()); + property1Name, + tablesMappedToProperty1.FormatTables(), + property2Name, + tablesMappedToProperty2.FormatTables()); } if (diagnostics.NeedsEventData(definition, out var diagnosticSourceEnabled, out var simpleLogEnabled)) @@ -4583,7 +4586,8 @@ public static void IndexPropertiesMappedToNonOverlappingTables( if (diagnostics.ShouldLog(definition)) { - definition.Log(diagnostics, + definition.Log( + diagnostics, l => l.Log( definition.Level, definition.EventId, @@ -4633,17 +4637,17 @@ private static string NamedIndexPropertiesMappedToNonOverlappingTables(EventDefi var d = (FallbackEventDefinition)definition; var p = (IndexWithPropertiesEventData)payload; return d.GenerateMessage( - l => l.Log( - d.Level, - d.EventId, - d.MessageFormat, - p.Name, - p.EntityType.DisplayName(), - p.PropertyNames.Format(), - p.Property1Name, - p.TablesMappedToProperty1.FormatTables(), - p.Property2Name, - p.TablesMappedToProperty2.FormatTables())); + l => l.Log( + d.Level, + d.EventId, + d.MessageFormat, + p.Name, + p.EntityType.DisplayName(), + p.PropertyNames.Format(), + p.Property1Name, + p.TablesMappedToProperty1.FormatTables(), + p.Property2Name, + p.TablesMappedToProperty2.FormatTables())); } /// diff --git a/src/EFCore.Relational/Diagnostics/TwoSqlExpressionsEventData.cs b/src/EFCore.Relational/Diagnostics/TwoSqlExpressionsEventData.cs index 1c8c01f6d87..e79b2bf73ca 100644 --- a/src/EFCore.Relational/Diagnostics/TwoSqlExpressionsEventData.cs +++ b/src/EFCore.Relational/Diagnostics/TwoSqlExpressionsEventData.cs @@ -10,7 +10,7 @@ namespace Microsoft.EntityFrameworkCore.Diagnostics { /// /// The event payload base class for events that - /// references two . + /// references two . /// public class TwoSqlExpressionsEventData : EventData { diff --git a/src/EFCore.Relational/Extensions/RelationalDatabaseFacadeExtensions.cs b/src/EFCore.Relational/Extensions/RelationalDatabaseFacadeExtensions.cs index 068556cf55a..0873a5545da 100644 --- a/src/EFCore.Relational/Extensions/RelationalDatabaseFacadeExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalDatabaseFacadeExtensions.cs @@ -131,7 +131,7 @@ public static Task MigrateAsync( /// /// However, never pass a concatenated or interpolated string ($"") with non-validated user-provided values /// into this method. Doing so may expose your application to SQL injection attacks. To use the interpolated string syntax, - /// consider using to create parameters. + /// consider using to create parameters. /// /// /// The for the context. @@ -199,7 +199,7 @@ public static int ExecuteSqlInterpolated( /// /// However, never pass a concatenated or interpolated string ($"") with non-validated user-provided values /// into this method. Doing so may expose your application to SQL injection attacks. To use the interpolated string syntax, - /// consider using to create parameters. + /// consider using to create parameters. /// /// /// The for the context. @@ -326,7 +326,7 @@ public static Task ExecuteSqlRawAsync( /// /// However, never pass a concatenated or interpolated string ($"") with non-validated user-provided values /// into this method. Doing so may expose your application to SQL injection attacks. To use the interpolated string syntax, - /// consider using to create parameters. + /// consider using to create parameters. /// /// /// The for the context. @@ -364,7 +364,7 @@ public static Task ExecuteSqlRawAsync( /// /// However, never pass a concatenated or interpolated string ($"") with non-validated user-provided values /// into this method. Doing so may expose your application to SQL injection attacks. To use the interpolated string syntax, - /// consider using to create parameters. + /// consider using to create parameters. /// /// /// The for the context. @@ -537,7 +537,8 @@ public static Task BeginTransactionAsync( /// The to use. /// A that encapsulates the given transaction. public static IDbContextTransaction UseTransaction( - [NotNull] this DatabaseFacade databaseFacade, [CanBeNull] DbTransaction transaction) + [NotNull] this DatabaseFacade databaseFacade, + [CanBeNull] DbTransaction transaction) => databaseFacade.UseTransaction(transaction, Guid.NewGuid()); /// @@ -548,7 +549,9 @@ public static IDbContextTransaction UseTransaction( /// The unique identifier for the transaction. /// A that encapsulates the given transaction. public static IDbContextTransaction UseTransaction( - [NotNull] this DatabaseFacade databaseFacade, [CanBeNull] DbTransaction transaction, Guid transactionId) + [NotNull] this DatabaseFacade databaseFacade, + [CanBeNull] DbTransaction transaction, + Guid transactionId) { var transactionManager = GetTransactionManager(databaseFacade); @@ -662,13 +665,13 @@ public static string GenerateCreateScript([NotNull] this DatabaseFacade database /// /// - /// Returns if the database provider currently in use is a relational database. + /// Returns if the database provider currently in use is a relational database. /// /// /// The facade from . /// - /// if a relational database provider is being used; - /// otherwise. + /// if a relational database provider is being used; + /// otherwise. /// public static bool IsRelational([NotNull] this DatabaseFacade databaseFacade) => ((IDatabaseFacadeDependenciesAccessor)Check.NotNull(databaseFacade, nameof(databaseFacade))) diff --git a/src/EFCore.Relational/Extensions/RelationalEntityTypeBuilderExtensions.cs b/src/EFCore.Relational/Extensions/RelationalEntityTypeBuilderExtensions.cs index 946f6173306..860a17fee63 100644 --- a/src/EFCore.Relational/Extensions/RelationalEntityTypeBuilderExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalEntityTypeBuilderExtensions.cs @@ -332,7 +332,9 @@ public static OwnedNavigationBuilder ToTable otherwise. /// public static IConventionEntityTypeBuilder ToTable( - [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) { if (!entityTypeBuilder.CanSetTable(name, fromDataAnnotation)) { @@ -355,7 +357,8 @@ public static IConventionEntityTypeBuilder ToTable( /// public static IConventionEntityTypeBuilder ToTable( [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, - [CanBeNull] string name, [CanBeNull] string schema, + [CanBeNull] string name, + [CanBeNull] string schema, bool fromDataAnnotation = false) { if (!entityTypeBuilder.CanSetTable(name, fromDataAnnotation) @@ -378,7 +381,9 @@ public static IConventionEntityTypeBuilder ToTable( /// Indicates whether the configuration was specified using a data annotation. /// if the configuration can be applied. public static bool CanSetTable( - [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) { Check.NullButNotEmpty(name, nameof(name)); @@ -459,7 +464,9 @@ public static IConventionEntityTypeBuilder ExcludeTableFromMigrations( /// Indicates whether the configuration was specified using a data annotation. /// if the configuration can be applied. public static bool CanExcludeTableFromMigrations( - [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, bool? excludedFromMigrations, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, + bool? excludedFromMigrations, + bool fromDataAnnotation = false) => entityTypeBuilder.CanSetAnnotation (RelationalAnnotationNames.IsTableExcludedFromMigrations, excludedFromMigrations, fromDataAnnotation); @@ -535,7 +542,9 @@ public static EntityTypeBuilder ToView( /// The same builder instance if the configuration was applied, otherwise. /// public static IConventionEntityTypeBuilder ToView( - [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) { if (!entityTypeBuilder.CanSetView(name, fromDataAnnotation)) { @@ -558,7 +567,8 @@ public static IConventionEntityTypeBuilder ToView( /// public static IConventionEntityTypeBuilder ToView( [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, - [CanBeNull] string name, [CanBeNull] string schema, + [CanBeNull] string name, + [CanBeNull] string schema, bool fromDataAnnotation = false) { if (!entityTypeBuilder.CanSetView(name, fromDataAnnotation) @@ -581,7 +591,9 @@ public static IConventionEntityTypeBuilder ToView( /// Indicates whether the configuration was specified using a data annotation. /// if the configuration can be applied. public static bool CanSetView( - [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) { Check.NullButNotEmpty(name, nameof(name)); @@ -657,7 +669,9 @@ public static EntityTypeBuilder ToSqlQuery( /// The same builder instance if the configuration was applied, otherwise. /// public static IConventionEntityTypeBuilder ToSqlQuery( - [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) { if (!entityTypeBuilder.CanSetSqlQuery(name, fromDataAnnotation)) { @@ -679,7 +693,9 @@ public static IConventionEntityTypeBuilder ToSqlQuery( /// Indicates whether the configuration was specified using a data annotation. /// if the configuration can be applied. public static bool CanSetSqlQuery( - [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) { Check.NullButNotEmpty(name, nameof(name)); @@ -831,7 +847,8 @@ private static IMutableDbFunction CreateFunction(string name, IMutableEntityType var model = entityType.Model; var function = model.FindDbFunction(name) - ?? model.AddDbFunction(name, typeof(IQueryable<>).MakeGenericType(entityType.ClrType ?? typeof(Dictionary))); + ?? model.AddDbFunction( + name, typeof(IQueryable<>).MakeGenericType(entityType.ClrType ?? typeof(Dictionary))); return function; } @@ -847,7 +864,9 @@ private static IMutableDbFunction CreateFunction(string name, IMutableEntityType /// otherwise. /// public static IConventionEntityTypeBuilder ToFunction( - [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) { if (!entityTypeBuilder.CanSetFunction(name, fromDataAnnotation)) { @@ -871,7 +890,9 @@ public static IConventionEntityTypeBuilder ToFunction( /// Indicates whether the configuration was specified using a data annotation. /// if the configuration can be applied. public static bool CanSetFunction( - [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityTypeBuilder entityTypeBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) { Check.NullButNotEmpty(name, nameof(name)); @@ -965,7 +986,7 @@ public static IConventionEntityTypeBuilder HasCheckConstraint( } if (!(fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention) - .Overrides(constraint.GetConfigurationSource())) + .Overrides(constraint.GetConfigurationSource())) { return null; } @@ -1004,7 +1025,7 @@ public static bool CanSetCheckConstraint( return constraint == null || constraint.Sql == sql || (fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention) - .Overrides(constraint.GetConfigurationSource()); + .Overrides(constraint.GetConfigurationSource()); } /// diff --git a/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs b/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs index ba82da0fa4e..58aecea0c7f 100644 --- a/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs @@ -43,8 +43,8 @@ public static string GetTableName([NotNull] this IEntityType entityType) && ((entityType as IConventionEntityType)?.GetDefiningQueryConfigurationSource() == null) #pragma warning restore CS0618 // Type or member is obsolete && ((entityType as IConventionEntityType)?.GetSqlQueryConfigurationSource() == null) - ? GetDefaultTableName(entityType) - : null; + ? GetDefaultTableName(entityType) + : null; } /// @@ -94,7 +94,9 @@ public static void SetTableName([NotNull] this IMutableEntityType entityType, [C /// Indicates whether the configuration was specified using a data annotation. /// The configured table name. public static string SetTableName( - [NotNull] this IConventionEntityType entityType, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityType entityType, + [CanBeNull] string name, + bool fromDataAnnotation = false) { entityType.SetAnnotation( RelationalAnnotationNames.TableName, @@ -168,7 +170,9 @@ public static void SetSchema([NotNull] this IMutableEntityType entityType, [CanB /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static string SetSchema( - [NotNull] this IConventionEntityType entityType, [CanBeNull] string value, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityType entityType, + [CanBeNull] string value, + bool fromDataAnnotation = false) { entityType.SetAnnotation( RelationalAnnotationNames.Schema, @@ -228,8 +232,8 @@ public static string GetSchemaQualifiedViewName([NotNull] this IEntityType entit /// /// The entity type to get the table mappings for. /// The tables to which the entity type is mapped. - public static IEnumerable GetDefaultMappings([NotNull] this IEntityType entityType) => - (IEnumerable)entityType[RelationalAnnotationNames.DefaultMappings] + public static IEnumerable GetDefaultMappings([NotNull] this IEntityType entityType) + => (IEnumerable)entityType[RelationalAnnotationNames.DefaultMappings] ?? Array.Empty(); /// @@ -237,8 +241,8 @@ public static IEnumerable GetDefaultMappings([NotNull] this I /// /// The entity type to get the table mappings for. /// The tables to which the entity type is mapped. - public static IEnumerable GetTableMappings([NotNull] this IEntityType entityType) => - (IEnumerable)entityType[RelationalAnnotationNames.TableMappings] + public static IEnumerable GetTableMappings([NotNull] this IEntityType entityType) + => (IEnumerable)entityType[RelationalAnnotationNames.TableMappings] ?? Array.Empty(); /// @@ -264,8 +268,8 @@ public static string GetViewName([NotNull] this IEntityType entityType) && (entityType as IConventionEntityType)?.GetDefiningQueryConfigurationSource() == null #pragma warning restore CS0618 // Type or member is obsolete && ((entityType as IConventionEntityType)?.GetSqlQueryConfigurationSource() == null) - ? GetDefaultViewName(entityType) - : null; + ? GetDefaultViewName(entityType) + : null; } /// @@ -278,8 +282,8 @@ public static string GetDefaultViewName([NotNull] this IEntityType entityType) var ownership = entityType.FindOwnership(); return ownership != null && ownership.IsUnique - ? ownership.PrincipalEntityType.GetViewName() - : null; + ? ownership.PrincipalEntityType.GetViewName() + : null; } /// @@ -300,7 +304,9 @@ public static void SetViewName([NotNull] this IMutableEntityType entityType, [Ca /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static string SetViewName( - [NotNull] this IConventionEntityType entityType, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityType entityType, + [CanBeNull] string name, + bool fromDataAnnotation = false) { entityType.SetAnnotation( RelationalAnnotationNames.ViewName, @@ -317,7 +323,7 @@ public static string SetViewName( /// The for the view name. public static ConfigurationSource? GetViewNameConfigurationSource([NotNull] this IConventionEntityType entityType) => entityType.FindAnnotation(RelationalAnnotationNames.ViewName) - ?.GetConfigurationSource(); + ?.GetConfigurationSource(); /// /// Returns the database schema that contains the mapped view. @@ -372,7 +378,9 @@ public static void SetViewSchema([NotNull] this IMutableEntityType entityType, [ /// Indicates whether the configuration was specified using a data annotation. /// The configured schema. public static string SetViewSchema( - [NotNull] this IConventionEntityType entityType, [CanBeNull] string value, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityType entityType, + [CanBeNull] string value, + bool fromDataAnnotation = false) { entityType.SetAnnotation( RelationalAnnotationNames.ViewSchema, @@ -396,8 +404,8 @@ public static string SetViewSchema( /// /// The entity type to get the view mappings for. /// The views to which the entity type is mapped. - public static IEnumerable GetViewMappings([NotNull] this IEntityType entityType) => - (IEnumerable)entityType[RelationalAnnotationNames.ViewMappings] + public static IEnumerable GetViewMappings([NotNull] this IEntityType entityType) + => (IEnumerable)entityType[RelationalAnnotationNames.ViewMappings] ?? Array.Empty(); /// @@ -448,7 +456,9 @@ public static void SetSqlQuery([NotNull] this IMutableEntityType entityType, [Ca /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static string SetSqlQuery( - [NotNull] this IConventionEntityType entityType, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityType entityType, + [CanBeNull] string name, + bool fromDataAnnotation = false) => (string)entityType.SetAnnotation( RelationalAnnotationNames.SqlQuery, Check.NullButNotEmpty(name, nameof(name)), @@ -461,15 +471,15 @@ public static string SetSqlQuery( /// The for the query SQL string. public static ConfigurationSource? GetSqlQueryConfigurationSource([NotNull] this IConventionEntityType entityType) => entityType.FindAnnotation(RelationalAnnotationNames.SqlQuery) - ?.GetConfigurationSource(); + ?.GetConfigurationSource(); /// /// Returns the SQL string mappings. /// /// The entity type to get the function mappings for. /// The functions to which the entity type is mapped. - public static IEnumerable GetSqlQueryMappings([NotNull] this IEntityType entityType) => - (IEnumerable)entityType[RelationalAnnotationNames.SqlQueryMappings] + public static IEnumerable GetSqlQueryMappings([NotNull] this IEntityType entityType) + => (IEnumerable)entityType[RelationalAnnotationNames.SqlQueryMappings] ?? Array.Empty(); /// @@ -511,7 +521,9 @@ public static void SetFunctionName([NotNull] this IMutableEntityType entityType, /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static string SetFunctionName( - [NotNull] this IConventionEntityType entityType, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityType entityType, + [CanBeNull] string name, + bool fromDataAnnotation = false) => (string)entityType.SetAnnotation( RelationalAnnotationNames.ViewName, Check.NullButNotEmpty(name, nameof(name)), @@ -524,15 +536,15 @@ public static string SetFunctionName( /// The for the function name. public static ConfigurationSource? GetFunctionNameConfigurationSource([NotNull] this IConventionEntityType entityType) => entityType.FindAnnotation(RelationalAnnotationNames.FunctionName) - ?.GetConfigurationSource(); + ?.GetConfigurationSource(); /// /// Returns the functions to which the entity type is mapped. /// /// The entity type to get the function mappings for. /// The functions to which the entity type is mapped. - public static IEnumerable GetFunctionMappings([NotNull] this IEntityType entityType) => - (IEnumerable)entityType[RelationalAnnotationNames.FunctionMappings] + public static IEnumerable GetFunctionMappings([NotNull] this IEntityType entityType) + => (IEnumerable)entityType[RelationalAnnotationNames.FunctionMappings] ?? Array.Empty(); /// @@ -545,7 +557,8 @@ public static IEnumerable GetFunctionMappings([NotNull] this I /// given name in the given entity type was found. /// public static ICheckConstraint FindCheckConstraint( - [NotNull] this IEntityType entityType, [NotNull] string name) + [NotNull] this IEntityType entityType, + [NotNull] string name) { Check.NotEmpty(name, nameof(name)); @@ -562,7 +575,8 @@ public static ICheckConstraint FindCheckConstraint( /// given name in the given entity type was found. /// public static IMutableCheckConstraint FindCheckConstraint( - [NotNull] this IMutableEntityType entityType, [NotNull] string name) + [NotNull] this IMutableEntityType entityType, + [NotNull] string name) => (IMutableCheckConstraint)((IEntityType)entityType).FindCheckConstraint(name); /// @@ -575,7 +589,8 @@ public static IMutableCheckConstraint FindCheckConstraint( /// given name in the given entity type was found. /// public static IConventionCheckConstraint FindCheckConstraint( - [NotNull] this IConventionEntityType entityType, [NotNull] string name) + [NotNull] this IConventionEntityType entityType, + [NotNull] string name) => (IConventionCheckConstraint)((IEntityType)entityType).FindCheckConstraint(name); /// @@ -687,7 +702,9 @@ public static void SetComment([NotNull] this IMutableEntityType entityType, [Can /// Indicates whether the configuration was specified using a data annotation. /// The configured comment. public static string SetComment( - [NotNull] this IConventionEntityType entityType, [CanBeNull] string comment, bool fromDataAnnotation = false) + [NotNull] this IConventionEntityType entityType, + [CanBeNull] string comment, + bool fromDataAnnotation = false) { entityType.SetOrRemoveAnnotation(RelationalAnnotationNames.Comment, comment, fromDataAnnotation); @@ -710,7 +727,8 @@ public static string SetComment( /// The entity type. /// The identifier of the store object. public static IEnumerable FindRowInternalForeignKeys( - [NotNull] this IEntityType entityType, StoreObjectIdentifier storeObject) + [NotNull] this IEntityType entityType, + StoreObjectIdentifier storeObject) { var primaryKey = entityType.FindPrimaryKey(); if (primaryKey == null) @@ -739,6 +757,7 @@ public static IEnumerable FindRowInternalForeignKeys( { yield return foreignKey; } + break; case StoreObjectType.View: if (storeObject.Name == principalEntityType.GetViewName() @@ -746,12 +765,14 @@ public static IEnumerable FindRowInternalForeignKeys( { yield return foreignKey; } + break; case StoreObjectType.Function: if (storeObject.Name == principalEntityType.GetFunctionName()) { yield return foreignKey; } + break; default: throw new NotImplementedException(storeObject.StoreObjectType.ToString()); @@ -766,7 +787,9 @@ public static IEnumerable FindRowInternalForeignKeys( /// The entity type. /// The identifier of the store object. public static IEnumerable FindRowInternalForeignKeys( - [NotNull] this IMutableEntityType entityType, in StoreObjectIdentifier storeObject) + [NotNull] this IMutableEntityType entityType, + in StoreObjectIdentifier storeObject) + // ReSharper disable once RedundantCast => ((IEntityType)entityType).FindRowInternalForeignKeys(storeObject).Cast(); /// @@ -776,7 +799,9 @@ public static IEnumerable FindRowInternalForeignKeys( /// The entity type. /// The identifier of the store object. public static IEnumerable FindRowInternalForeignKeys( - [NotNull] this IConventionEntityType entityType, in StoreObjectIdentifier storeObject) + [NotNull] this IConventionEntityType entityType, + in StoreObjectIdentifier storeObject) + // ReSharper disable once RedundantCast => ((IEntityType)entityType).FindRowInternalForeignKeys(storeObject).Cast(); /// @@ -816,7 +841,7 @@ public static bool IsTableExcludedFromMigrations([NotNull] this IEntityType enti /// Sets a value indicating whether the associated table is ignored by Migrations. /// /// The entity type. - /// A value indicating whether the associated table is ignored by Migrations. + /// A value indicating whether the associated table is ignored by Migrations. public static void SetIsTableExcludedFromMigrations([NotNull] this IMutableEntityType entityType, bool? excluded) => entityType.SetOrRemoveAnnotation(RelationalAnnotationNames.IsTableExcludedFromMigrations, excluded); @@ -828,16 +853,20 @@ public static void SetIsTableExcludedFromMigrations([NotNull] this IMutableEntit /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static bool? SetIsTableExcludedFromMigrations( - [NotNull] this IConventionEntityType entityType, bool? excluded, bool fromDataAnnotation = false) - => (bool?)entityType.SetOrRemoveAnnotation(RelationalAnnotationNames.IsTableExcludedFromMigrations, excluded, fromDataAnnotation) + [NotNull] this IConventionEntityType entityType, + bool? excluded, + bool fromDataAnnotation = false) + => (bool?)entityType.SetOrRemoveAnnotation( + RelationalAnnotationNames.IsTableExcludedFromMigrations, excluded, fromDataAnnotation) ?.Value; /// - /// Gets the for . + /// Gets the for . /// /// The entity type to find configuration source for. - /// The for . - public static ConfigurationSource? GetIsTableExcludedFromMigrationsConfigurationSource([NotNull] this IConventionEntityType entityType) + /// The for . + public static ConfigurationSource? GetIsTableExcludedFromMigrationsConfigurationSource( + [NotNull] this IConventionEntityType entityType) => entityType.FindAnnotation(RelationalAnnotationNames.IsTableExcludedFromMigrations) ?.GetConfigurationSource(); } diff --git a/src/EFCore.Relational/Extensions/RelationalForeignKeyBuilderExtensions.cs b/src/EFCore.Relational/Extensions/RelationalForeignKeyBuilderExtensions.cs index 72eb7ad6bcd..e625097acf9 100644 --- a/src/EFCore.Relational/Extensions/RelationalForeignKeyBuilderExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalForeignKeyBuilderExtensions.cs @@ -126,7 +126,9 @@ public static OwnershipBuilder HasConstraintName otherwise. /// public static IConventionForeignKeyBuilder HasConstraintName( - [NotNull] this IConventionForeignKeyBuilder relationship, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionForeignKeyBuilder relationship, + [CanBeNull] string name, + bool fromDataAnnotation = false) { if (!relationship.CanSetConstraintName(name, fromDataAnnotation)) { @@ -146,7 +148,9 @@ public static IConventionForeignKeyBuilder HasConstraintName( /// Indicates whether the configuration was specified using a data annotation. /// if the configuration can be applied. public static bool CanSetConstraintName( - [NotNull] this IConventionForeignKeyBuilder relationship, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionForeignKeyBuilder relationship, + [CanBeNull] string name, + bool fromDataAnnotation = false) => Check.NotNull(relationship, nameof(relationship)) .CanSetAnnotation(RelationalAnnotationNames.Name, name, fromDataAnnotation); } diff --git a/src/EFCore.Relational/Extensions/RelationalForeignKeyExtensions.cs b/src/EFCore.Relational/Extensions/RelationalForeignKeyExtensions.cs index d848b5cceb4..ae648e4d96a 100644 --- a/src/EFCore.Relational/Extensions/RelationalForeignKeyExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalForeignKeyExtensions.cs @@ -25,9 +25,10 @@ public static class RelationalForeignKeyExtensions public static string GetConstraintName([NotNull] this IForeignKey foreignKey) => foreignKey.GetConstraintName( StoreObjectIdentifier.Create(foreignKey.DeclaringEntityType, StoreObjectType.Table).Value, - StoreObjectIdentifier.Create(foreignKey.PrincipalKey.IsPrimaryKey() - ? foreignKey.PrincipalEntityType - : foreignKey.PrincipalKey.DeclaringEntityType, + StoreObjectIdentifier.Create( + foreignKey.PrincipalKey.IsPrimaryKey() + ? foreignKey.PrincipalEntityType + : foreignKey.PrincipalKey.DeclaringEntityType, StoreObjectType.Table).Value); /// @@ -38,7 +39,9 @@ public static string GetConstraintName([NotNull] this IForeignKey foreignKey) /// The identifier of the principal store object. /// The foreign key constraint name. public static string GetConstraintName( - [NotNull] this IForeignKey foreignKey, in StoreObjectIdentifier storeObject, in StoreObjectIdentifier principalStoreObject) + [NotNull] this IForeignKey foreignKey, + in StoreObjectIdentifier storeObject, + in StoreObjectIdentifier principalStoreObject) { var annotation = foreignKey.FindAnnotation(RelationalAnnotationNames.Name); return annotation != null @@ -103,7 +106,8 @@ public static string GetDefaultName( if (principalStoreObject.Name == otherForeignKey.PrincipalEntityType.GetTableName() && principalStoreObject.Schema == otherForeignKey.PrincipalEntityType.GetSchema() && propertyNames.SequenceEqual(otherForeignKey.Properties.GetColumnNames(storeObject)) - && principalPropertyNames.SequenceEqual(otherForeignKey.PrincipalKey.Properties.GetColumnNames(principalStoreObject))) + && principalPropertyNames.SequenceEqual( + otherForeignKey.PrincipalKey.Properties.GetColumnNames(principalStoreObject))) { linkedForeignKey = otherForeignKey; break; @@ -153,7 +157,9 @@ public static void SetConstraintName([NotNull] this IMutableForeignKey foreignKe /// Indicates whether the configuration was specified using a data annotation. /// The configured name. public static string SetConstraintName( - [NotNull] this IConventionForeignKey foreignKey, [CanBeNull] string value, bool fromDataAnnotation = false) + [NotNull] this IConventionForeignKey foreignKey, + [CanBeNull] string value, + bool fromDataAnnotation = false) { foreignKey.SetOrRemoveAnnotation( RelationalAnnotationNames.Name, @@ -177,8 +183,8 @@ public static string SetConstraintName( /// /// The foreign key. /// The foreign key constraints to which the foreign key is mapped. - public static IEnumerable GetMappedConstraints([NotNull] this IForeignKey foreignKey) => - (IEnumerable)foreignKey[RelationalAnnotationNames.ForeignKeyMappings] + public static IEnumerable GetMappedConstraints([NotNull] this IForeignKey foreignKey) + => (IEnumerable)foreignKey[RelationalAnnotationNames.ForeignKeyMappings] ?? Enumerable.Empty(); /// @@ -193,11 +199,14 @@ public static IEnumerable GetMappedConstraints([NotNull] /// The foreign key. /// The identifier of the containing store object. /// The foreign key if found, or if none was found. - public static IForeignKey FindSharedObjectRootForeignKey([NotNull] this IForeignKey foreignKey, in StoreObjectIdentifier storeObject) + public static IForeignKey FindSharedObjectRootForeignKey( + [NotNull] this IForeignKey foreignKey, + in StoreObjectIdentifier storeObject) { Check.NotNull(foreignKey, nameof(foreignKey)); - var foreignKeyName = foreignKey.GetConstraintName(storeObject, + var foreignKeyName = foreignKey.GetConstraintName( + storeObject, StoreObjectIdentifier.Table(foreignKey.PrincipalEntityType.GetTableName(), foreignKey.PrincipalEntityType.GetSchema())); var rootForeignKey = foreignKey; @@ -210,10 +219,11 @@ public static IForeignKey FindSharedObjectRootForeignKey([NotNull] this IForeign .FindRowInternalForeignKeys(storeObject) .SelectMany(fk => fk.PrincipalEntityType.GetForeignKeys())) { - if (otherForeignKey.GetConstraintName(storeObject, - StoreObjectIdentifier.Table( - otherForeignKey.PrincipalEntityType.GetTableName(), - otherForeignKey.PrincipalEntityType.GetSchema())) + if (otherForeignKey.GetConstraintName( + storeObject, + StoreObjectIdentifier.Table( + otherForeignKey.PrincipalEntityType.GetTableName(), + otherForeignKey.PrincipalEntityType.GetSchema())) == foreignKeyName) { linkedForeignKey = otherForeignKey; @@ -245,7 +255,8 @@ public static IForeignKey FindSharedObjectRootForeignKey([NotNull] this IForeign /// The identifier of the containing store object. /// The foreign key if found, or if none was found. public static IMutableForeignKey FindSharedObjectRootForeignKey( - [NotNull] this IMutableForeignKey foreignKey, in StoreObjectIdentifier storeObject) + [NotNull] this IMutableForeignKey foreignKey, + in StoreObjectIdentifier storeObject) => (IMutableForeignKey)((IForeignKey)foreignKey).FindSharedObjectRootForeignKey(storeObject); /// @@ -261,7 +272,8 @@ public static IMutableForeignKey FindSharedObjectRootForeignKey( /// The identifier of the containing store object. /// The foreign key if found, or if none was found. public static IConventionForeignKey FindSharedObjectRootForeignKey( - [NotNull] this IConventionForeignKey foreignKey, in StoreObjectIdentifier storeObject) + [NotNull] this IConventionForeignKey foreignKey, + in StoreObjectIdentifier storeObject) => (IConventionForeignKey)((IForeignKey)foreignKey).FindSharedObjectRootForeignKey(storeObject); } } diff --git a/src/EFCore.Relational/Extensions/RelationalIndexBuilderExtensions.cs b/src/EFCore.Relational/Extensions/RelationalIndexBuilderExtensions.cs index ea062b96ae3..6a7da9f78f2 100644 --- a/src/EFCore.Relational/Extensions/RelationalIndexBuilderExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalIndexBuilderExtensions.cs @@ -45,7 +45,9 @@ public static IndexBuilder HasName([NotNull] this IndexBuilder indexBuilder, [Ca /// The builder for the index being configured. /// The name of the index. /// A builder to further configure the index. - public static IndexBuilder HasDatabaseName([NotNull] this IndexBuilder indexBuilder, [CanBeNull] string name) + public static IndexBuilder HasDatabaseName( + [NotNull] this IndexBuilder indexBuilder, + [CanBeNull] string name) { indexBuilder.Metadata.SetDatabaseName(name); @@ -74,7 +76,9 @@ public static IndexBuilder HasName([NotNull] this IndexBuilder /// otherwise. /// public static IConventionIndexBuilder HasDatabaseName( - [NotNull] this IConventionIndexBuilder indexBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionIndexBuilder indexBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) { if (indexBuilder.CanSetDatabaseName(name, fromDataAnnotation)) { @@ -97,7 +101,9 @@ public static IConventionIndexBuilder HasDatabaseName( /// [Obsolete("Use HasDatabaseName() instead.")] public static IConventionIndexBuilder HasName( - [NotNull] this IConventionIndexBuilder indexBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionIndexBuilder indexBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) => indexBuilder.HasDatabaseName(name, fromDataAnnotation); /// @@ -108,7 +114,9 @@ public static IConventionIndexBuilder HasName( /// Indicates whether the configuration was specified using a data annotation. /// if the given name can be set for the index. public static bool CanSetDatabaseName( - [NotNull] this IConventionIndexBuilder indexBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionIndexBuilder indexBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) => indexBuilder.CanSetAnnotation(RelationalAnnotationNames.Name, name, fromDataAnnotation); /// @@ -120,7 +128,9 @@ public static bool CanSetDatabaseName( /// if the given name can be set for the index. [Obsolete("Use CanSetDatabaseName() instead.")] public static bool CanSetName( - [NotNull] this IConventionIndexBuilder indexBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionIndexBuilder indexBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) => CanSetDatabaseName(indexBuilder, name, fromDataAnnotation); /// @@ -160,7 +170,9 @@ public static IndexBuilder HasFilter([NotNull] this IndexBuild /// otherwise. /// public static IConventionIndexBuilder HasFilter( - [NotNull] this IConventionIndexBuilder indexBuilder, [CanBeNull] string sql, bool fromDataAnnotation = false) + [NotNull] this IConventionIndexBuilder indexBuilder, + [CanBeNull] string sql, + bool fromDataAnnotation = false) { if (indexBuilder.CanSetFilter(sql, fromDataAnnotation)) { @@ -179,7 +191,9 @@ public static IConventionIndexBuilder HasFilter( /// Indicates whether the configuration was specified using a data annotation. /// if the given name can be set for the index. public static bool CanSetFilter( - [NotNull] this IConventionIndexBuilder indexBuilder, [CanBeNull] string sql, bool fromDataAnnotation = false) + [NotNull] this IConventionIndexBuilder indexBuilder, + [CanBeNull] string sql, + bool fromDataAnnotation = false) => indexBuilder.CanSetAnnotation(RelationalAnnotationNames.Filter, sql, fromDataAnnotation); } } diff --git a/src/EFCore.Relational/Extensions/RelationalIndexExtensions.cs b/src/EFCore.Relational/Extensions/RelationalIndexExtensions.cs index 3951a89a696..4dc0ed3e130 100644 --- a/src/EFCore.Relational/Extensions/RelationalIndexExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalIndexExtensions.cs @@ -159,7 +159,10 @@ public static void SetName([NotNull] this IMutableIndex index, [CanBeNull] strin /// The value to set. /// Indicates whether the configuration was specified using a data annotation. /// The configured value. - public static string SetDatabaseName([NotNull] this IConventionIndex index, [CanBeNull] string name, bool fromDataAnnotation = false) + public static string SetDatabaseName( + [NotNull] this IConventionIndex index, + [CanBeNull] string name, + bool fromDataAnnotation = false) { index.SetOrRemoveAnnotation( RelationalAnnotationNames.Name, @@ -265,8 +268,8 @@ public static string SetFilter([NotNull] this IConventionIndex index, [CanBeNull /// /// The index. /// The table indexes to which the index is mapped. - public static IEnumerable GetMappedTableIndexes([NotNull] this IIndex index) => - (IEnumerable)index[RelationalAnnotationNames.TableIndexMappings] + public static IEnumerable GetMappedTableIndexes([NotNull] this IIndex index) + => (IEnumerable)index[RelationalAnnotationNames.TableIndexMappings] ?? Enumerable.Empty(); /// @@ -293,7 +296,7 @@ public static IIndex FindSharedObjectRootIndex([NotNull] this IIndex index, in S for (var i = 0; i < Metadata.Internal.RelationalEntityTypeExtensions.MaxEntityTypesSharingTable; i++) { IIndex linkedIndex = null; - foreach(var otherIndex in rootIndex.DeclaringEntityType + foreach (var otherIndex in rootIndex.DeclaringEntityType .FindRowInternalForeignKeys(storeObject) .SelectMany(fk => fk.PrincipalEntityType.GetIndexes())) { @@ -328,7 +331,8 @@ public static IIndex FindSharedObjectRootIndex([NotNull] this IIndex index, in S /// The identifier of the containing store object. /// The index found, or if none was found. public static IMutableIndex FindSharedObjectRootIndex( - [NotNull] this IMutableIndex index, in StoreObjectIdentifier storeObject) + [NotNull] this IMutableIndex index, + in StoreObjectIdentifier storeObject) => (IMutableIndex)((IIndex)index).FindSharedObjectRootIndex(storeObject); /// @@ -344,7 +348,8 @@ public static IMutableIndex FindSharedObjectRootIndex( /// The identifier of the containing store object. /// The index found, or if none was found. public static IConventionIndex FindSharedObjectRootIndex( - [NotNull] this IConventionIndex index, in StoreObjectIdentifier storeObject) + [NotNull] this IConventionIndex index, + in StoreObjectIdentifier storeObject) => (IConventionIndex)((IIndex)index).FindSharedObjectRootIndex(storeObject); } } diff --git a/src/EFCore.Relational/Extensions/RelationalKeyBuilderExtensions.cs b/src/EFCore.Relational/Extensions/RelationalKeyBuilderExtensions.cs index 369f2a0f9b9..3a931fd5644 100644 --- a/src/EFCore.Relational/Extensions/RelationalKeyBuilderExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalKeyBuilderExtensions.cs @@ -52,7 +52,9 @@ public static KeyBuilder HasName( /// otherwise. /// public static IConventionKeyBuilder HasName( - [NotNull] this IConventionKeyBuilder keyBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionKeyBuilder keyBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) { if (keyBuilder.CanSetName(name, fromDataAnnotation)) { @@ -71,7 +73,9 @@ public static IConventionKeyBuilder HasName( /// Indicates whether the configuration was specified using a data annotation. /// if the given name can be set for the key constraint. public static bool CanSetName( - [NotNull] this IConventionKeyBuilder keyBuilder, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionKeyBuilder keyBuilder, + [CanBeNull] string name, + bool fromDataAnnotation = false) => keyBuilder.CanSetAnnotation(RelationalAnnotationNames.Name, name, fromDataAnnotation); } } diff --git a/src/EFCore.Relational/Extensions/RelationalKeyExtensions.cs b/src/EFCore.Relational/Extensions/RelationalKeyExtensions.cs index 8b6cc7181e9..a790cc808b7 100644 --- a/src/EFCore.Relational/Extensions/RelationalKeyExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalKeyExtensions.cs @@ -33,7 +33,7 @@ public static string GetName([NotNull] this IKey key) /// The key constraint name for this key. public static string GetName([NotNull] this IKey key, in StoreObjectIdentifier storeObject) => (string)key[RelationalAnnotationNames.Name] - ?? key.GetDefaultName(storeObject); + ?? key.GetDefaultName(storeObject); /// /// Returns the default key constraint name that would be used for this key. @@ -110,7 +110,7 @@ public static string GetDefaultName([NotNull] this IKey key, in StoreObjectIdent for (var i = 0; i < Metadata.Internal.RelationalEntityTypeExtensions.MaxEntityTypesSharingTable; i++) { IKey linkedKey = null; - foreach(var otherKey in rootKey.DeclaringEntityType + foreach (var otherKey in rootKey.DeclaringEntityType .FindRowInternalForeignKeys(storeObject) .SelectMany(fk => fk.PrincipalEntityType.GetKeys())) { @@ -185,8 +185,8 @@ public static string SetName([NotNull] this IConventionKey key, [CanBeNull] stri /// /// The key. /// The unique constraints to which the key is mapped. - public static IEnumerable GetMappedConstraints([NotNull] this IKey key) => - (IEnumerable)key[RelationalAnnotationNames.UniqueConstraintMappings] + public static IEnumerable GetMappedConstraints([NotNull] this IKey key) + => (IEnumerable)key[RelationalAnnotationNames.UniqueConstraintMappings] ?? Enumerable.Empty(); /// @@ -248,7 +248,8 @@ public static IKey FindSharedObjectRootKey([NotNull] this IKey key, in StoreObje /// The identifier of the containing store object. /// The key found, or if none was found. public static IMutableKey FindSharedObjectRootKey( - [NotNull] this IMutableKey key, in StoreObjectIdentifier storeObject) + [NotNull] this IMutableKey key, + in StoreObjectIdentifier storeObject) => (IMutableKey)((IKey)key).FindSharedObjectRootKey(storeObject); /// @@ -264,7 +265,8 @@ public static IMutableKey FindSharedObjectRootKey( /// The identifier of the containing store object. /// The key found, or if none was found. public static IConventionKey FindSharedObjectRootKey( - [NotNull] this IConventionKey key, in StoreObjectIdentifier storeObject) + [NotNull] this IConventionKey key, + in StoreObjectIdentifier storeObject) => (IConventionKey)((IKey)key).FindSharedObjectRootKey(storeObject); } } diff --git a/src/EFCore.Relational/Extensions/RelationalModelBuilderExtensions.cs b/src/EFCore.Relational/Extensions/RelationalModelBuilderExtensions.cs index c9793037c92..a781fe2b9ee 100644 --- a/src/EFCore.Relational/Extensions/RelationalModelBuilderExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalModelBuilderExtensions.cs @@ -30,11 +30,12 @@ public static SequenceBuilder HasSequence( [NotNull] this ModelBuilder modelBuilder, [NotNull] string name, [CanBeNull] string schema = null) - => new SequenceBuilder(HasSequence( - Check.NotNull(modelBuilder, nameof(modelBuilder)).Model, - name, - schema, - ConfigurationSource.Explicit)); + => new SequenceBuilder( + HasSequence( + Check.NotNull(modelBuilder, nameof(modelBuilder)).Model, + name, + schema, + ConfigurationSource.Explicit)); /// /// Configures a database sequence when targeting a relational database. @@ -208,7 +209,10 @@ public static IConventionSequenceBuilder HasSequence( fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention).Builder; private static Sequence HasSequence( - IMutableModel model, string name, string schema, ConfigurationSource configurationSource) + IMutableModel model, + string name, + string schema, + ConfigurationSource configurationSource) { Check.NotEmpty(name, nameof(name)); Check.NullButNotEmpty(schema, nameof(schema)); diff --git a/src/EFCore.Relational/Extensions/RelationalModelExtensions.cs b/src/EFCore.Relational/Extensions/RelationalModelExtensions.cs index 0d3c427041c..e87eb9ebe95 100644 --- a/src/EFCore.Relational/Extensions/RelationalModelExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalModelExtensions.cs @@ -16,7 +16,7 @@ namespace Microsoft.EntityFrameworkCore { /// - /// Relational-specific extension methods for and extension methods for . + /// Relational-specific extension methods for and extension methods for . /// public static class RelationalModelExtensions { @@ -87,7 +87,9 @@ public static void SetDefaultSchema([NotNull] this IMutableModel model, [CanBeNu /// Indicates whether the configuration was specified using a data annotation. /// The configured schema. public static string SetDefaultSchema( - [NotNull] this IConventionModel model, [CanBeNull] string value, bool fromDataAnnotation = false) + [NotNull] this IConventionModel model, + [CanBeNull] string value, + bool fromDataAnnotation = false) { model.SetOrRemoveAnnotation( RelationalAnnotationNames.DefaultSchema, @@ -182,7 +184,9 @@ public static ISequence FindSequence([NotNull] this IModel model, [NotNull] stri /// the given schema was found. /// public static IMutableSequence FindSequence( - [NotNull] this IMutableModel model, [NotNull] string name, [CanBeNull] string schema = null) + [NotNull] this IMutableModel model, + [NotNull] string name, + [CanBeNull] string schema = null) => (IMutableSequence)((IModel)model).FindSequence(name, schema); /// @@ -196,7 +200,9 @@ public static IMutableSequence FindSequence( /// the given schema was found. /// public static IConventionSequence FindSequence( - [NotNull] this IConventionModel model, [NotNull] string name, [CanBeNull] string schema = null) + [NotNull] this IConventionModel model, + [NotNull] string name, + [CanBeNull] string schema = null) => (IConventionSequence)((IModel)model).FindSequence(name, schema); /// @@ -208,7 +214,9 @@ public static IConventionSequence FindSequence( /// The schema name, or to use the default schema. /// The sequence. public static IMutableSequence AddSequence( - [NotNull] this IMutableModel model, [NotNull] string name, [CanBeNull] string schema = null) + [NotNull] this IMutableModel model, + [NotNull] string name, + [CanBeNull] string schema = null) => Sequence.AddSequence(model, name, schema, ConfigurationSource.Explicit); /// @@ -221,7 +229,10 @@ public static IMutableSequence AddSequence( /// Indicates whether the configuration was specified using a data annotation. /// The sequence. public static IConventionSequence AddSequence( - [NotNull] this IConventionModel model, [NotNull] string name, [CanBeNull] string schema = null, bool fromDataAnnotation = false) + [NotNull] this IConventionModel model, + [NotNull] string name, + [CanBeNull] string schema = null, + bool fromDataAnnotation = false) => Sequence.AddSequence( (IMutableModel)model, name, schema, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); @@ -237,7 +248,9 @@ public static IConventionSequence AddSequence( /// the given schema was found. /// public static IMutableSequence RemoveSequence( - [NotNull] this IMutableModel model, [NotNull] string name, [CanBeNull] string schema = null) + [NotNull] this IMutableModel model, + [NotNull] string name, + [CanBeNull] string schema = null) => Sequence.RemoveSequence(Check.NotNull(model, nameof(model)), name, schema); /// @@ -251,7 +264,9 @@ public static IMutableSequence RemoveSequence( /// the given schema was found. /// public static IConventionSequence RemoveSequence( - [NotNull] this IConventionModel model, [NotNull] string name, [CanBeNull] string schema = null) + [NotNull] this IConventionModel model, + [NotNull] string name, + [CanBeNull] string schema = null) => Sequence.RemoveSequence((IMutableModel)Check.NotNull(model, nameof(model)), name, schema); /// @@ -341,7 +356,7 @@ public static IConventionDbFunction FindDbFunction([NotNull] this IConventionMod /// The new . public static IMutableDbFunction AddDbFunction([NotNull] this IMutableModel model, [NotNull] MethodInfo methodInfo) => DbFunction.AddDbFunction( - model, Check.NotNull(methodInfo, nameof(methodInfo)), ConfigurationSource.Explicit); + model, Check.NotNull(methodInfo, nameof(methodInfo)), ConfigurationSource.Explicit); /// /// Creates an mapped to the given method. @@ -351,10 +366,12 @@ public static IMutableDbFunction AddDbFunction([NotNull] this IMutableModel mode /// Indicates whether the configuration was specified using a data annotation. /// The new . public static IConventionDbFunction AddDbFunction( - [NotNull] this IConventionModel model, [NotNull] MethodInfo methodInfo, bool fromDataAnnotation = false) + [NotNull] this IConventionModel model, + [NotNull] MethodInfo methodInfo, + bool fromDataAnnotation = false) => DbFunction.AddDbFunction( - (IMutableModel)model, Check.NotNull(methodInfo, nameof(methodInfo)), - fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); + (IMutableModel)model, Check.NotNull(methodInfo, nameof(methodInfo)), + fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// /// Creates an . @@ -368,7 +385,7 @@ public static IMutableDbFunction AddDbFunction( [NotNull] string name, [NotNull] Type returnType) => DbFunction.AddDbFunction( - model, Check.NotNull(name, nameof(name)), returnType, ConfigurationSource.Explicit); + model, Check.NotNull(name, nameof(name)), returnType, ConfigurationSource.Explicit); /// /// Creates an . @@ -384,10 +401,10 @@ public static IConventionDbFunction AddDbFunction( [NotNull] Type returnType, bool fromDataAnnotation = false) => DbFunction.AddDbFunction( - (IMutableModel)model, - Check.NotNull(name, nameof(name)), - returnType, - fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); + (IMutableModel)model, + Check.NotNull(name, nameof(name)), + returnType, + fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// /// Removes the that is mapped to the method represented by the given diff --git a/src/EFCore.Relational/Extensions/RelationalPropertyBuilderExtensions.cs b/src/EFCore.Relational/Extensions/RelationalPropertyBuilderExtensions.cs index 2edf2d7f7ea..8c029f7db6e 100644 --- a/src/EFCore.Relational/Extensions/RelationalPropertyBuilderExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalPropertyBuilderExtensions.cs @@ -126,8 +126,8 @@ public static bool CanSetColumnName( var overrides = RelationalPropertyOverrides.Find(propertyBuilder.Metadata, storeObject); return overrides == null || (fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention) - .Overrides(overrides.GetColumnNameConfigurationSource()) - || overrides.ColumnName == name; + .Overrides(overrides.GetColumnNameConfigurationSource()) + || overrides.ColumnName == name; } /// @@ -776,7 +776,8 @@ public static PropertyBuilder UseCollation([NotNull] this PropertyBuilder proper /// The collation for the column. /// The same builder instance so that multiple calls can be chained. public static PropertyBuilder UseCollation( - [NotNull] this PropertyBuilder propertyBuilder, [CanBeNull] string collation) + [NotNull] this PropertyBuilder propertyBuilder, + [CanBeNull] string collation) => (PropertyBuilder)UseCollation((PropertyBuilder)propertyBuilder, collation); /// diff --git a/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs b/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs index b34c3fa04cf..68806ec67e7 100644 --- a/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs @@ -116,6 +116,7 @@ public static string GetDefaultColumnName([NotNull] this IProperty property, in { entityType = null; } + break; case StoreObjectType.View: if (name != ownerType.GetViewName() @@ -123,12 +124,14 @@ public static string GetDefaultColumnName([NotNull] this IProperty property, in { entityType = null; } + break; case StoreObjectType.Function: if (name != ownerType.GetFunctionName()) { entityType = null; } + break; default: throw new NotImplementedException(storeObject.StoreObjectType.ToString()); @@ -179,7 +182,9 @@ public static void SetColumnName([NotNull] this IMutableProperty property, [CanB /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static string SetColumnName( - [NotNull] this IConventionProperty property, [CanBeNull] string name, bool fromDataAnnotation = false) + [NotNull] this IConventionProperty property, + [CanBeNull] string name, + bool fromDataAnnotation = false) { property.SetOrRemoveAnnotation( RelationalAnnotationNames.ColumnName, @@ -196,7 +201,9 @@ public static string SetColumnName( /// The name to set. /// The identifier of the table-like store object containing the column. public static void SetColumnName( - [NotNull] this IMutableProperty property, [CanBeNull] string name, in StoreObjectIdentifier storeObject) + [NotNull] this IMutableProperty property, + [CanBeNull] string name, + in StoreObjectIdentifier storeObject) => RelationalPropertyOverrides.GetOrCreate(property, storeObject) .SetColumnName(name, ConfigurationSource.Explicit); @@ -291,7 +298,9 @@ public static void SetColumnType([NotNull] this IMutableProperty property, [CanB /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static string SetColumnType( - [NotNull] this IConventionProperty property, [CanBeNull] string value, bool fromDataAnnotation = false) + [NotNull] this IConventionProperty property, + [CanBeNull] string value, + bool fromDataAnnotation = false) { property.SetOrRemoveAnnotation( RelationalAnnotationNames.ColumnType, @@ -314,8 +323,8 @@ public static string SetColumnType( /// /// The property. /// The default columns to which the property would be mapped. - public static IEnumerable GetDefaultColumnMappings([NotNull] this IProperty property) => - (IEnumerable)property[RelationalAnnotationNames.DefaultColumnMappings] + public static IEnumerable GetDefaultColumnMappings([NotNull] this IProperty property) + => (IEnumerable)property[RelationalAnnotationNames.DefaultColumnMappings] ?? Enumerable.Empty(); /// @@ -323,8 +332,8 @@ public static IEnumerable GetDefaultColumnMappings([NotNull] /// /// The property. /// The table columns to which the property is mapped. - public static IEnumerable GetTableColumnMappings([NotNull] this IProperty property) => - (IEnumerable)property[RelationalAnnotationNames.TableColumnMappings] + public static IEnumerable GetTableColumnMappings([NotNull] this IProperty property) + => (IEnumerable)property[RelationalAnnotationNames.TableColumnMappings] ?? Enumerable.Empty(); /// @@ -332,8 +341,8 @@ public static IEnumerable GetTableColumnMappings([NotNull] this /// /// The property. /// The view columns to which the property is mapped. - public static IEnumerable GetViewColumnMappings([NotNull] this IProperty property) => - (IEnumerable)property[RelationalAnnotationNames.ViewColumnMappings] + public static IEnumerable GetViewColumnMappings([NotNull] this IProperty property) + => (IEnumerable)property[RelationalAnnotationNames.ViewColumnMappings] ?? Enumerable.Empty(); /// @@ -341,8 +350,8 @@ public static IEnumerable GetViewColumnMappings([NotNull] th /// /// The property. /// The SQL query columns to which the property is mapped. - public static IEnumerable GetSqlQueryColumnMappings([NotNull] this IProperty property) => - (IEnumerable)property[RelationalAnnotationNames.SqlQueryColumnMappings] + public static IEnumerable GetSqlQueryColumnMappings([NotNull] this IProperty property) + => (IEnumerable)property[RelationalAnnotationNames.SqlQueryColumnMappings] ?? Enumerable.Empty(); /// @@ -350,8 +359,8 @@ public static IEnumerable GetSqlQueryColumnMappings([Not /// /// The property. /// The function columns to which the property is mapped. - public static IEnumerable GetFunctionColumnMappings([NotNull] this IProperty property) => - (IEnumerable)property[RelationalAnnotationNames.FunctionColumnMappings] + public static IEnumerable GetFunctionColumnMappings([NotNull] this IProperty property) + => (IEnumerable)property[RelationalAnnotationNames.FunctionColumnMappings] ?? Enumerable.Empty(); /// @@ -461,7 +470,9 @@ public static void SetDefaultValueSql([NotNull] this IMutableProperty property, /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static string SetDefaultValueSql( - [NotNull] this IConventionProperty property, [CanBeNull] string value, bool fromDataAnnotation = false) + [NotNull] this IConventionProperty property, + [CanBeNull] string value, + bool fromDataAnnotation = false) { property.SetOrRemoveAnnotation( RelationalAnnotationNames.DefaultValueSql, @@ -536,7 +547,9 @@ public static void SetComputedColumnSql([NotNull] this IMutableProperty property /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static string SetComputedColumnSql( - [NotNull] this IConventionProperty property, [CanBeNull] string value, bool fromDataAnnotation = false) + [NotNull] this IConventionProperty property, + [CanBeNull] string value, + bool fromDataAnnotation = false) { property.SetOrRemoveAnnotation( RelationalAnnotationNames.ComputedColumnSql, @@ -616,7 +629,9 @@ public static void SetIsStored([NotNull] this IMutableProperty property, bool? v /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static bool? SetIsStored( - [NotNull] this IConventionProperty property, bool? value, bool fromDataAnnotation = false) + [NotNull] this IConventionProperty property, + bool? value, + bool fromDataAnnotation = false) { property.SetOrRemoveAnnotation(RelationalAnnotationNames.IsStored, value, fromDataAnnotation); @@ -681,7 +696,9 @@ public static void SetDefaultValue([NotNull] this IMutableProperty property, [Ca /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static object SetDefaultValue( - [NotNull] this IConventionProperty property, [CanBeNull] object value, bool fromDataAnnotation = false) + [NotNull] this IConventionProperty property, + [CanBeNull] object value, + bool fromDataAnnotation = false) { property.SetOrRemoveAnnotation( RelationalAnnotationNames.DefaultValue, ConvertDefaultValue(property, value), fromDataAnnotation); @@ -772,7 +789,10 @@ public static void SetIsFixedLength([NotNull] this IMutableProperty property, bo /// A value indicating whether the property is constrained to fixed length values. /// Indicates whether the configuration was specified using a data annotation. /// The configured value. - public static bool? SetIsFixedLength([NotNull] this IConventionProperty property, bool? fixedLength, bool fromDataAnnotation = false) + public static bool? SetIsFixedLength( + [NotNull] this IConventionProperty property, + bool? fixedLength, + bool fromDataAnnotation = false) { property.SetOrRemoveAnnotation(RelationalAnnotationNames.IsFixedLength, fixedLength, fromDataAnnotation); @@ -832,8 +852,8 @@ public static bool IsColumnNullable([NotNull] this IProperty property, in StoreO } return property.IsNullable - || (property.DeclaringEntityType.BaseType != null && property.DeclaringEntityType.GetDiscriminatorProperty() != null) - || IsOptionalSharingDependent(property.DeclaringEntityType, storeObject, 0); + || (property.DeclaringEntityType.BaseType != null && property.DeclaringEntityType.GetDiscriminatorProperty() != null) + || IsOptionalSharingDependent(property.DeclaringEntityType, storeObject, 0); } private static bool IsOptionalSharingDependent(IEntityType entityType, in StoreObjectIdentifier storeObject, int recursionDepth) @@ -904,7 +924,9 @@ public static void SetComment([NotNull] this IMutableProperty property, [CanBeNu /// Indicates whether the configuration was specified using a data annotation. /// The configured value. public static string SetComment( - [NotNull] this IConventionProperty property, [CanBeNull] string comment, bool fromDataAnnotation = false) + [NotNull] this IConventionProperty property, + [CanBeNull] string comment, + bool fromDataAnnotation = false) { property.SetOrRemoveAnnotation(RelationalAnnotationNames.Comment, comment, fromDataAnnotation); @@ -1021,7 +1043,8 @@ public static RelationalTypeMapping FindRelationalTypeMapping([NotNull] this IPr /// The identifier of the table-like store object containing the column. /// The type mapping, or if none was found. public static RelationalTypeMapping FindRelationalTypeMapping( - [NotNull] this IProperty property, in StoreObjectIdentifier storeObject) + [NotNull] this IProperty property, + in StoreObjectIdentifier storeObject) => property.FindRelationalTypeMapping(); /// @@ -1037,7 +1060,8 @@ public static RelationalTypeMapping FindRelationalTypeMapping( /// The identifier of the table-like store object containing the column. /// The property found, or if none was found. public static IProperty FindSharedStoreObjectRootProperty( - [NotNull] this IProperty property, in StoreObjectIdentifier storeObject) + [NotNull] this IProperty property, + in StoreObjectIdentifier storeObject) => FindSharedObjectRootProperty(property, storeObject); /// @@ -1053,7 +1077,8 @@ public static IProperty FindSharedStoreObjectRootProperty( /// The identifier of the table-like store object containing the column. /// The property found, or if none was found. public static IMutableProperty FindSharedStoreObjectRootProperty( - [NotNull] this IMutableProperty property, in StoreObjectIdentifier storeObject) + [NotNull] this IMutableProperty property, + in StoreObjectIdentifier storeObject) => (IMutableProperty)FindSharedObjectRootProperty(property, storeObject); /// @@ -1069,7 +1094,8 @@ public static IMutableProperty FindSharedStoreObjectRootProperty( /// The identifier of the table-like store object containing the column. /// The property found, or if none was found. public static IConventionProperty FindSharedStoreObjectRootProperty( - [NotNull] this IConventionProperty property, in StoreObjectIdentifier storeObject) + [NotNull] this IConventionProperty property, + in StoreObjectIdentifier storeObject) => (IConventionProperty)FindSharedObjectRootProperty(property, storeObject); private static IProperty FindSharedObjectRootProperty([NotNull] IProperty property, in StoreObjectIdentifier storeObject) @@ -1080,8 +1106,9 @@ private static IProperty FindSharedObjectRootProperty([NotNull] IProperty proper if (column == null) { - throw new InvalidOperationException(RelationalStrings.PropertyNotMappedToTable( - property.Name, property.DeclaringEntityType, storeObject.DisplayName())); + throw new InvalidOperationException( + RelationalStrings.PropertyNotMappedToTable( + property.Name, property.DeclaringEntityType, storeObject.DisplayName())); } var rootProperty = property; @@ -1139,7 +1166,9 @@ private static IProperty FindSharedObjectRootPrimaryKeyProperty([NotNull] IPrope return principalProperty == property ? null : principalProperty; } - private static IProperty FindSharedObjectRootConcurrencyTokenProperty([NotNull] IProperty property, in StoreObjectIdentifier storeObject) + private static IProperty FindSharedObjectRootConcurrencyTokenProperty( + [NotNull] IProperty property, + in StoreObjectIdentifier storeObject) { if (!property.IsConcurrencyToken) { @@ -1197,7 +1226,8 @@ public static IAnnotatable FindOverrides([NotNull] this IProperty property, in S /// The identifier of the table-like store object containing the column. /// An object that stores property facet overrides. public static IMutableAnnotatable GetOrCreateOverrides( - [NotNull] this IMutableProperty property, in StoreObjectIdentifier storeObject) + [NotNull] this IMutableProperty property, + in StoreObjectIdentifier storeObject) => RelationalPropertyOverrides.GetOrCreate(property, storeObject); /// @@ -1213,7 +1243,8 @@ public static IMutableAnnotatable GetOrCreateOverrides( /// The identifier of the table-like store object containing the column. /// An object that stores property facet overrides. public static IConventionAnnotatable GetOrCreateOverrides( - [NotNull] this IConventionProperty property, in StoreObjectIdentifier storeObject) + [NotNull] this IConventionProperty property, + in StoreObjectIdentifier storeObject) => RelationalPropertyOverrides.GetOrCreate(property, storeObject); } } diff --git a/src/EFCore.Relational/Extensions/RelationalQueryableExtensions.cs b/src/EFCore.Relational/Extensions/RelationalQueryableExtensions.cs index 8c1aaa5b278..4bebc0320f3 100644 --- a/src/EFCore.Relational/Extensions/RelationalQueryableExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalQueryableExtensions.cs @@ -25,7 +25,7 @@ public static class RelationalQueryableExtensions { /// /// - /// Creates a set up to execute this query. + /// Creates a set up to execute this query. /// /// /// This is only typically supported by queries generated by Entity Framework Core. @@ -35,7 +35,7 @@ public static class RelationalQueryableExtensions /// executed the command. /// /// - /// Note that DbCommand is an object. The caller is responsible for disposing the returned + /// Note that DbCommand is an object. The caller is responsible for disposing the returned /// command. /// /// @@ -73,7 +73,7 @@ public static DbCommand CreateDbCommand([NotNull] this IQueryable source) /// /// However, never pass a concatenated or interpolated string ($"") with non-validated user-provided values /// into this method. Doing so may expose your application to SQL injection attacks. To use the interpolated string syntax, - /// consider using to create parameters. + /// consider using to create parameters. /// /// /// This overload also accepts DbParameter instances as parameter values. This allows you to use named @@ -91,7 +91,7 @@ public static DbCommand CreateDbCommand([NotNull] this IQueryable source) [StringFormatMethod("sql")] public static IQueryable FromSqlRaw( [NotNull] this DbSet source, - [NotNull][NotParameterized] string sql, + [NotNull] [NotParameterized] string sql, [NotNull] params object[] parameters) where TEntity : class { @@ -131,7 +131,7 @@ public static IQueryable FromSqlRaw( /// An representing the interpolated string SQL query. public static IQueryable FromSqlInterpolated( [NotNull] this DbSet source, - [NotNull][NotParameterized] FormattableString sql) + [NotNull] [NotParameterized] FormattableString sql) where TEntity : class { Check.NotNull(source, nameof(source)); @@ -179,7 +179,7 @@ private static FromSqlQueryRootExpression GenerateFromSqlQueryRoot( /// /// /// The default query splitting behavior for queries can be controlled by - /// . + /// . /// /// /// The type of entity being queried. diff --git a/src/EFCore.Relational/Extensions/RelationalTaskExtensions.cs b/src/EFCore.Relational/Extensions/RelationalTaskExtensions.cs index 614e6d43e20..2706d1f0d90 100644 --- a/src/EFCore.Relational/Extensions/RelationalTaskExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalTaskExtensions.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // ReSharper disable once CheckNamespace + namespace System.Threading.Tasks { internal static class RelationalTaskExtensions diff --git a/src/EFCore.Relational/Infrastructure/EntityFrameworkRelationalServicesBuilder.cs b/src/EFCore.Relational/Infrastructure/EntityFrameworkRelationalServicesBuilder.cs index 9c708f5d29b..75d154a2ee6 100644 --- a/src/EFCore.Relational/Infrastructure/EntityFrameworkRelationalServicesBuilder.cs +++ b/src/EFCore.Relational/Infrastructure/EntityFrameworkRelationalServicesBuilder.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using JetBrains.Annotations; -using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Diagnostics.Internal; using Microsoft.EntityFrameworkCore.Internal; @@ -89,8 +88,14 @@ public static readonly IDictionary RelationalServi { typeof(IHistoryRepository), new ServiceCharacteristics(ServiceLifetime.Scoped) }, { typeof(INamedConnectionStringResolver), new ServiceCharacteristics(ServiceLifetime.Scoped) }, { typeof(IInterceptor), new ServiceCharacteristics(ServiceLifetime.Scoped, multipleRegistrations: true) }, - { typeof(IRelationalTypeMappingSourcePlugin), new ServiceCharacteristics(ServiceLifetime.Singleton, multipleRegistrations: true) }, - { typeof(IMethodCallTranslatorPlugin), new ServiceCharacteristics(ServiceLifetime.Singleton, multipleRegistrations: true) }, + { + typeof(IRelationalTypeMappingSourcePlugin), + new ServiceCharacteristics(ServiceLifetime.Singleton, multipleRegistrations: true) + }, + { + typeof(IMethodCallTranslatorPlugin), + new ServiceCharacteristics(ServiceLifetime.Singleton, multipleRegistrations: true) + }, { typeof(IMemberTranslatorPlugin), new ServiceCharacteristics(ServiceLifetime.Singleton, multipleRegistrations: true) }, { typeof(IRelationalParameterBasedSqlProcessorFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) } }; diff --git a/src/EFCore.Relational/Infrastructure/ModelSnapshot.cs b/src/EFCore.Relational/Infrastructure/ModelSnapshot.cs index 5c5a9580727..3e04b5ea2fb 100644 --- a/src/EFCore.Relational/Infrastructure/ModelSnapshot.cs +++ b/src/EFCore.Relational/Infrastructure/ModelSnapshot.cs @@ -25,7 +25,8 @@ private IModel CreateModel() /// /// The snapshot model. /// - public virtual IModel Model => _model ??= CreateModel(); + public virtual IModel Model + => _model ??= CreateModel(); /// /// Called lazily by to build the model snapshot diff --git a/src/EFCore.Relational/Infrastructure/RelationalDbContextOptionsBuilder.cs b/src/EFCore.Relational/Infrastructure/RelationalDbContextOptionsBuilder.cs index 15f5c263ba1..0516d352504 100644 --- a/src/EFCore.Relational/Infrastructure/RelationalDbContextOptionsBuilder.cs +++ b/src/EFCore.Relational/Infrastructure/RelationalDbContextOptionsBuilder.cs @@ -39,7 +39,8 @@ protected RelationalDbContextOptionsBuilder([NotNull] DbContextOptionsBuilder op protected virtual DbContextOptionsBuilder OptionsBuilder { get; } /// - DbContextOptionsBuilder IRelationalDbContextOptionsBuilderInfrastructure.OptionsBuilder => OptionsBuilder; + DbContextOptionsBuilder IRelationalDbContextOptionsBuilderInfrastructure.OptionsBuilder + => OptionsBuilder; /// /// Configures the maximum number of statements that will be included in commands sent to the database @@ -99,7 +100,7 @@ public virtual TBuilder UseRelationalNulls(bool useRelationalNulls = true) => WithOption(e => (TExtension)e.WithUseRelationalNulls(useRelationalNulls)); /// - /// Configures the to use when loading related collections in a query. + /// Configures the to use when loading related collections in a query. /// /// The same builder instance so that multiple calls can be chained. public virtual TBuilder UseQuerySplittingBehavior(QuerySplittingBehavior querySplittingBehavior) @@ -135,22 +136,25 @@ protected virtual TBuilder WithOption([NotNull] Func set /// /// A string that represents the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override string ToString() => base.ToString(); + public override string ToString() + => base.ToString(); /// /// Determines whether the specified object is equal to the current object. /// /// The object to compare with the current object. - /// if the specified object is equal to the current object; otherwise, . + /// if the specified object is equal to the current object; otherwise, . [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object obj) + => base.Equals(obj); /// /// Serves as the default hash function. /// /// A hash code for the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); #endregion } diff --git a/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs b/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs index 494d481bfa7..7f2039cf8e0 100644 --- a/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs +++ b/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs @@ -72,7 +72,8 @@ public override void Validate(IModel model, IDiagnosticsLogger The model to validate. /// The logger to use. protected virtual void ValidateSqlQueries( - [NotNull] IModel model, [NotNull] IDiagnosticsLogger logger) + [NotNull] IModel model, + [NotNull] IDiagnosticsLogger logger) { foreach (var entityType in model.GetEntityTypes()) { @@ -99,7 +100,8 @@ protected virtual void ValidateSqlQueries( /// The model to validate. /// The logger to use. protected virtual void ValidateDbFunctions( - [NotNull] IModel model, [NotNull] IDiagnosticsLogger logger) + [NotNull] IModel model, + [NotNull] IDiagnosticsLogger logger) { foreach (var dbFunction in model.GetDbFunctions()) { @@ -122,14 +124,16 @@ protected virtual void ValidateDbFunctions( || ((IConventionModel)model).IsOwned(elementType) || (entityType == null && model.GetEntityTypes().Any(e => e.ClrType == elementType))) { - throw new InvalidOperationException(RelationalStrings.DbFunctionInvalidIQueryableOwnedReturnType( - dbFunction.ModelName, elementType.ShortDisplayName())); + throw new InvalidOperationException( + RelationalStrings.DbFunctionInvalidIQueryableOwnedReturnType( + dbFunction.ModelName, elementType.ShortDisplayName())); } if (entityType == null) { - throw new InvalidOperationException(RelationalStrings.DbFunctionInvalidReturnEntityType( - dbFunction.ModelName, dbFunction.ReturnType.ShortDisplayName(), elementType.ShortDisplayName())); + throw new InvalidOperationException( + RelationalStrings.DbFunctionInvalidReturnEntityType( + dbFunction.ModelName, dbFunction.ReturnType.ShortDisplayName(), elementType.ShortDisplayName())); } if ((entityType.BaseType != null || entityType.GetDerivedTypes().Any()) @@ -206,7 +210,8 @@ protected virtual void ValidateDbFunctions( /// The model to validate. /// The logger to use. protected virtual void ValidateBoolsWithDefaults( - [NotNull] IModel model, [NotNull] IDiagnosticsLogger logger) + [NotNull] IModel model, + [NotNull] IDiagnosticsLogger logger) { Check.NotNull(model, nameof(model)); @@ -241,7 +246,8 @@ static bool IsNotNullAndFalse(object value) /// The model to validate. /// The logger to use. protected virtual void ValidateDefaultValuesOnKeys( - [NotNull] IModel model, [NotNull] IDiagnosticsLogger logger) + [NotNull] IModel model, + [NotNull] IDiagnosticsLogger logger) { foreach (var entityType in ((IConventionModel)model).GetEntityTypes()) { @@ -329,14 +335,16 @@ protected virtual void ValidateSharedTableCompatibility( } if (mappedType.FindPrimaryKey() != null - && mappedType.FindForeignKeys(mappedType.FindPrimaryKey().Properties) - .Any(fk => fk.PrincipalKey.IsPrimaryKey() - && unvalidatedTypes.Contains(fk.PrincipalEntityType))) + && mappedType.FindForeignKeys(mappedType.FindPrimaryKey().Properties) + .Any( + fk => fk.PrincipalKey.IsPrimaryKey() + && unvalidatedTypes.Contains(fk.PrincipalEntityType))) { if (mappedType.BaseType != null) { var principalType = mappedType.FindForeignKeys(mappedType.FindPrimaryKey().Properties) - .First(fk => fk.PrincipalKey.IsPrimaryKey() + .First( + fk => fk.PrincipalKey.IsPrimaryKey() && unvalidatedTypes.Contains(fk.PrincipalEntityType)) .PrincipalEntityType; throw new InvalidOperationException( @@ -514,14 +522,16 @@ protected virtual void ValidateSharedViewCompatibility( } if (mappedType.FindPrimaryKey() != null - && mappedType.FindForeignKeys(mappedType.FindPrimaryKey().Properties) - .Any(fk => fk.PrincipalKey.IsPrimaryKey() - && unvalidatedTypes.Contains(fk.PrincipalEntityType))) + && mappedType.FindForeignKeys(mappedType.FindPrimaryKey().Properties) + .Any( + fk => fk.PrincipalKey.IsPrimaryKey() + && unvalidatedTypes.Contains(fk.PrincipalEntityType))) { if (mappedType.BaseType != null) { var principalType = mappedType.FindForeignKeys(mappedType.FindPrimaryKey().Properties) - .First(fk => fk.PrincipalKey.IsPrimaryKey() + .First( + fk => fk.PrincipalKey.IsPrimaryKey() && unvalidatedTypes.Contains(fk.PrincipalEntityType)) .PrincipalEntityType; throw new InvalidOperationException( @@ -589,7 +599,8 @@ protected virtual void ValidateSharedViewCompatibility( private static bool IsIdentifyingPrincipal(IEntityType dependentEntityType, IEntityType principalEntityType) => dependentEntityType.FindForeignKeys(dependentEntityType.FindPrimaryKey().Properties) - .Any(fk => fk.PrincipalKey.IsPrimaryKey() + .Any( + fk => fk.PrincipalKey.IsPrimaryKey() && fk.PrincipalEntityType == principalEntityType); /// @@ -606,7 +617,7 @@ protected virtual void ValidateSharedColumnsCompatibility( var concurrencyColumns = TableSharingConcurrencyTokenConvention.GetConcurrencyTokensMap(storeObject, mappedTypes); HashSet missingConcurrencyTokens = null; if (concurrencyColumns != null - && storeObject.StoreObjectType == StoreObjectType.Table) + && storeObject.StoreObjectType == StoreObjectType.Table) { missingConcurrencyTokens = new HashSet(); } @@ -656,7 +667,8 @@ protected virtual void ValidateSharedColumnsCompatibility( if (!columnFound) { throw new InvalidOperationException( - RelationalStrings.MissingConcurrencyColumn(entityType.DisplayName(), missingColumn, storeObject.DisplayName())); + RelationalStrings.MissingConcurrencyColumn( + entityType.DisplayName(), missingColumn, storeObject.DisplayName())); } } } @@ -802,15 +814,15 @@ protected virtual void ValidateCompatible( if (!Equals(currentDefaultValue, previousDefaultValue)) { throw new InvalidOperationException( - RelationalStrings.DuplicateColumnNameDefaultSqlMismatch( - duplicateProperty.DeclaringEntityType.DisplayName(), - duplicateProperty.Name, - property.DeclaringEntityType.DisplayName(), - property.Name, - columnName, - storeObject.DisplayName(), - previousDefaultValue ?? "NULL", - currentDefaultValue ?? "NULL")); + RelationalStrings.DuplicateColumnNameDefaultSqlMismatch( + duplicateProperty.DeclaringEntityType.DisplayName(), + duplicateProperty.Name, + property.DeclaringEntityType.DisplayName(), + property.Name, + columnName, + storeObject.DisplayName(), + previousDefaultValue ?? "NULL", + currentDefaultValue ?? "NULL")); } } @@ -1041,7 +1053,8 @@ protected virtual void ValidateCompatible( /// The model to validate. /// The logger to use. protected override void ValidateInheritanceMapping( - IModel model, IDiagnosticsLogger logger) + IModel model, + IDiagnosticsLogger logger) { foreach (var rootEntityType in model.GetEntityTypes()) { @@ -1081,11 +1094,12 @@ private void ValidateTPTMapping(IEntityType rootEntityType, bool forTables) var schema = forTables ? entityType.GetSchema() : entityType.GetViewSchema(); if (derivedTypes.TryGetValue((name, schema), out var otherType)) { - throw new InvalidOperationException(forTables - ? RelationalStrings.NonTPHTableClash( - entityType.DisplayName(), otherType.DisplayName(), entityType.GetSchemaQualifiedTableName()) - : RelationalStrings.NonTPHViewClash( - entityType.DisplayName(), otherType.DisplayName(), entityType.GetSchemaQualifiedViewName())); + throw new InvalidOperationException( + forTables + ? RelationalStrings.NonTPHTableClash( + entityType.DisplayName(), otherType.DisplayName(), entityType.GetSchemaQualifiedTableName()) + : RelationalStrings.NonTPHViewClash( + entityType.DisplayName(), otherType.DisplayName(), entityType.GetSchemaQualifiedViewName())); } derivedTypes[(name, schema)] = entityType; @@ -1116,13 +1130,14 @@ private void ValidateTPHMapping(IEntityType rootEntityType, bool forTables) var schema = forTables ? entityType.GetSchema() : entityType.GetViewSchema(); if (name != firstName || schema != firstSchema) { - throw new InvalidOperationException(forTables - ? RelationalStrings.TPHTableMismatch( - entityType.DisplayName(), entityType.GetSchemaQualifiedTableName(), - firstType.DisplayName(), firstType.GetSchemaQualifiedTableName()) - : RelationalStrings.TPHViewMismatch( - entityType.DisplayName(), entityType.GetSchemaQualifiedViewName(), - firstType.DisplayName(), firstType.GetSchemaQualifiedViewName())); + throw new InvalidOperationException( + forTables + ? RelationalStrings.TPHTableMismatch( + entityType.DisplayName(), entityType.GetSchemaQualifiedTableName(), + firstType.DisplayName(), firstType.GetSchemaQualifiedTableName()) + : RelationalStrings.TPHViewMismatch( + entityType.DisplayName(), entityType.GetSchemaQualifiedViewName(), + firstType.DisplayName(), firstType.GetSchemaQualifiedViewName())); } } } @@ -1133,7 +1148,8 @@ private void ValidateTPHMapping(IEntityType rootEntityType, bool forTables) /// The model to validate. /// The logger to use. protected virtual void ValidatePropertyOverrides( - [NotNull] IModel model, [NotNull] IDiagnosticsLogger logger) + [NotNull] IModel model, + [NotNull] IDiagnosticsLogger logger) { foreach (var entityType in model.GetEntityTypes()) { @@ -1153,38 +1169,48 @@ protected virtual void ValidatePropertyOverrides( switch (storeOverride.StoreObjectType) { case StoreObjectType.Table: - if (!entityType.GetDerivedTypes().Any(d => - d.GetTableName() == name - && d.GetSchema() == schema)) + if (!entityType.GetDerivedTypes().Any( + d => + d.GetTableName() == name + && d.GetSchema() == schema)) { - throw new InvalidOperationException(RelationalStrings.TableOverrideMismatch( - entityType.DisplayName() + "." + property.Name, - (schema == null ? "" : schema + ".") + name)); + throw new InvalidOperationException( + RelationalStrings.TableOverrideMismatch( + entityType.DisplayName() + "." + property.Name, + (schema == null ? "" : schema + ".") + name)); } + break; case StoreObjectType.View: - if (!entityType.GetDerivedTypes().Any(d => - d.GetViewName() == name - && d.GetViewSchema() == schema)) + if (!entityType.GetDerivedTypes().Any( + d => + d.GetViewName() == name + && d.GetViewSchema() == schema)) { - throw new InvalidOperationException(RelationalStrings.ViewOverrideMismatch( - entityType.DisplayName() + "." + property.Name, - (schema == null ? "" : schema + ".") + name)); + throw new InvalidOperationException( + RelationalStrings.ViewOverrideMismatch( + entityType.DisplayName() + "." + property.Name, + (schema == null ? "" : schema + ".") + name)); } + break; case StoreObjectType.SqlQuery: if (!entityType.GetDerivedTypes().Any(d => d.GetDefaultSqlQueryName() == name)) { - throw new InvalidOperationException(RelationalStrings.SqlQueryOverrideMismatch( - entityType.DisplayName() + "." + property.Name, name)); + throw new InvalidOperationException( + RelationalStrings.SqlQueryOverrideMismatch( + entityType.DisplayName() + "." + property.Name, name)); } + break; case StoreObjectType.Function: if (!entityType.GetDerivedTypes().Any(d => d.GetFunctionName() == name)) { - throw new InvalidOperationException(RelationalStrings.FunctionOverrideMismatch( - entityType.DisplayName() + "." + property.Name, name)); + throw new InvalidOperationException( + RelationalStrings.FunctionOverrideMismatch( + entityType.DisplayName() + "." + property.Name, name)); } + break; default: throw new NotImplementedException(storeOverride.StoreObjectType.ToString()); @@ -1201,7 +1227,8 @@ protected virtual void ValidatePropertyOverrides( /// The model to validate. /// The logger to use. protected virtual void ValidateIndexProperties( - [NotNull] IModel model, [NotNull] IDiagnosticsLogger logger) + [NotNull] IModel model, + [NotNull] IDiagnosticsLogger logger) { Check.NotNull(model, nameof(model)); diff --git a/src/EFCore.Relational/Infrastructure/RelationalOptionsExtension.cs b/src/EFCore.Relational/Infrastructure/RelationalOptionsExtension.cs index e99c367617e..4b62a75f515 100644 --- a/src/EFCore.Relational/Infrastructure/RelationalOptionsExtension.cs +++ b/src/EFCore.Relational/Infrastructure/RelationalOptionsExtension.cs @@ -83,7 +83,8 @@ protected RelationalOptionsExtension([NotNull] RelationalOptionsExtension copyFr /// The connection string, or if a was used instead of /// a connection string. /// - public virtual string ConnectionString => _connectionString; + public virtual string ConnectionString + => _connectionString; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -106,7 +107,8 @@ public virtual RelationalOptionsExtension WithConnectionString([NotNull] string /// The , or if a connection string was used instead of /// the full connection object. /// - public virtual DbConnection Connection => _connection; + public virtual DbConnection Connection + => _connection; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -128,7 +130,8 @@ public virtual RelationalOptionsExtension WithConnection([NotNull] DbConnection /// /// The command timeout, or if none has been set. /// - public virtual int? CommandTimeout => _commandTimeout; + public virtual int? CommandTimeout + => _commandTimeout; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -155,7 +158,8 @@ public virtual RelationalOptionsExtension WithCommandTimeout(int? commandTimeout /// The maximum number of statements that will be included in commands sent to the database /// during or if none has been set. /// - public virtual int? MaxBatchSize => _maxBatchSize; + public virtual int? MaxBatchSize + => _maxBatchSize; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -182,7 +186,8 @@ public virtual RelationalOptionsExtension WithMaxBatchSize(int? maxBatchSize) /// The minimum number of statements that are needed for a multi-statement command sent to the database /// during or if none has been set. /// - public virtual int? MinBatchSize => _minBatchSize; + public virtual int? MinBatchSize + => _minBatchSize; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -210,7 +215,8 @@ public virtual RelationalOptionsExtension WithMinBatchSize(int? minBatchSize) /// Entity Framework will use C# semantics for null values, and generate SQL to compensate for differences /// in how the database handles nulls. /// - public virtual bool UseRelationalNulls => _useRelationalNulls; + public virtual bool UseRelationalNulls + => _useRelationalNulls; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -228,9 +234,10 @@ public virtual RelationalOptionsExtension WithUseRelationalNulls(bool useRelatio } /// - /// The to use when loading related collections in a query. + /// The to use when loading related collections in a query. /// - public virtual QuerySplittingBehavior? QuerySplittingBehavior => _querySplittingBehavior; + public virtual QuerySplittingBehavior? QuerySplittingBehavior + => _querySplittingBehavior; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -250,7 +257,8 @@ public virtual RelationalOptionsExtension WithUseQuerySplittingBehavior(QuerySpl /// /// The name of the assembly that contains migrations, or if none has been set. /// - public virtual string MigrationsAssembly => _migrationsAssembly; + public virtual string MigrationsAssembly + => _migrationsAssembly; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -270,7 +278,8 @@ public virtual RelationalOptionsExtension WithMigrationsAssembly([CanBeNull] str /// /// The table name to use for the migrations history table, or if none has been set. /// - public virtual string MigrationsHistoryTableName => _migrationsHistoryTableName; + public virtual string MigrationsHistoryTableName + => _migrationsHistoryTableName; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -290,7 +299,8 @@ public virtual RelationalOptionsExtension WithMigrationsHistoryTableName([CanBeN /// /// The schema to use for the migrations history table, or if none has been set. /// - public virtual string MigrationsHistoryTableSchema => _migrationsHistoryTableSchema; + public virtual string MigrationsHistoryTableSchema + => _migrationsHistoryTableSchema; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -311,7 +321,8 @@ public virtual RelationalOptionsExtension WithMigrationsHistoryTableSchema([CanB /// A factory for creating the default , or if none has been /// configured. /// - public virtual Func ExecutionStrategyFactory => _executionStrategyFactory; + public virtual Func ExecutionStrategyFactory + => _executionStrategyFactory; /// /// Creates a new instance with all options the same as for this instance, but with the given option changed. @@ -403,14 +414,16 @@ protected RelationalExtensionInfo(IDbContextOptionsExtension extension) /// /// True, since this is a database provider base class. /// - public override bool IsDatabaseProvider => true; + public override bool IsDatabaseProvider + => true; /// /// Returns a hash code created from any options that would cause a new /// to be needed. Most extensions do not have any such options and should return zero. /// /// A hash over options that require a new service provider when changed. - public override long GetServiceProviderHashCode() => 0; + public override long GetServiceProviderHashCode() + => 0; /// /// A message fragment for logging typically containing information about diff --git a/src/EFCore.Relational/Infrastructure/RelationalPropertyExtensions.cs b/src/EFCore.Relational/Infrastructure/RelationalPropertyExtensions.cs index 704617978b7..c93460e06d5 100644 --- a/src/EFCore.Relational/Infrastructure/RelationalPropertyExtensions.cs +++ b/src/EFCore.Relational/Infrastructure/RelationalPropertyExtensions.cs @@ -42,8 +42,10 @@ public static IReadOnlyList GetColumnNames( { return null; } + propertyNames.Add(columnName); } + return propertyNames; } } diff --git a/src/EFCore.Relational/Internal/RelationalDatabaseFacadeDependencies.cs b/src/EFCore.Relational/Internal/RelationalDatabaseFacadeDependencies.cs index 1dbdff0ee76..d3a787ec83c 100644 --- a/src/EFCore.Relational/Internal/RelationalDatabaseFacadeDependencies.cs +++ b/src/EFCore.Relational/Internal/RelationalDatabaseFacadeDependencies.cs @@ -43,7 +43,6 @@ public RelationalDatabaseFacadeDependencies( RawSqlCommandBuilder = rawSqlCommandBuilder; } - /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in diff --git a/src/EFCore.Relational/Metadata/Builders/DbFunctionBuilder.cs b/src/EFCore.Relational/Metadata/Builders/DbFunctionBuilder.cs index 05ec03d9d07..544f192962e 100644 --- a/src/EFCore.Relational/Metadata/Builders/DbFunctionBuilder.cs +++ b/src/EFCore.Relational/Metadata/Builders/DbFunctionBuilder.cs @@ -50,7 +50,6 @@ public DbFunctionBuilder([NotNull] IMutableDbFunction function) public new virtual DbFunctionBuilder IsBuiltIn(bool builtIn = true) => (DbFunctionBuilder)base.IsBuiltIn(builtIn); - /// /// Marks whether the database function can return null value. /// diff --git a/src/EFCore.Relational/Metadata/Builders/DbFunctionBuilderBase.cs b/src/EFCore.Relational/Metadata/Builders/DbFunctionBuilderBase.cs index 3d0244021de..550088a0b64 100644 --- a/src/EFCore.Relational/Metadata/Builders/DbFunctionBuilderBase.cs +++ b/src/EFCore.Relational/Metadata/Builders/DbFunctionBuilderBase.cs @@ -48,7 +48,8 @@ IConventionDbFunctionBuilder IInfrastructure.Insta /// /// The function being configured. /// - public virtual IMutableDbFunction Metadata => Builder.Metadata; + public virtual IMutableDbFunction Metadata + => Builder.Metadata; /// /// Sets the name of the database function. @@ -102,16 +103,18 @@ public virtual DbFunctionParameterBuilder HasParameter([NotNull] string name) /// /// A string that represents the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override string ToString() => base.ToString(); + public override string ToString() + => base.ToString(); /// /// Determines whether the specified object is equal to the current object. /// /// The object to compare with the current object. - /// if the specified object is equal to the current object; otherwise, . + /// if the specified object is equal to the current object; otherwise, . [EditorBrowsable(EditorBrowsableState.Never)] // ReSharper disable once BaseObjectEqualsIsObjectEquals - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object obj) + => base.Equals(obj); /// /// Serves as the default hash function. @@ -119,7 +122,8 @@ public virtual DbFunctionParameterBuilder HasParameter([NotNull] string name) /// A hash code for the current object. [EditorBrowsable(EditorBrowsableState.Never)] // ReSharper disable once BaseObjectGetHashCodeCallInGetHashCode - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); #endregion } diff --git a/src/EFCore.Relational/Metadata/Builders/DbFunctionParameterBuilder.cs b/src/EFCore.Relational/Metadata/Builders/DbFunctionParameterBuilder.cs index 3b0ddabe1a8..2a45412830a 100644 --- a/src/EFCore.Relational/Metadata/Builders/DbFunctionParameterBuilder.cs +++ b/src/EFCore.Relational/Metadata/Builders/DbFunctionParameterBuilder.cs @@ -48,7 +48,8 @@ IConventionDbFunctionParameterBuilder IInfrastructure /// The function parameter metadata that is being built. /// - public virtual IMutableDbFunctionParameter Metadata => Builder.Metadata; + public virtual IMutableDbFunctionParameter Metadata + => Builder.Metadata; /// /// Sets the store type of the function parameter in the database. @@ -81,16 +82,18 @@ public virtual DbFunctionParameterBuilder PropagatesNullability(bool propagatesN /// /// A string that represents the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override string ToString() => base.ToString(); + public override string ToString() + => base.ToString(); /// /// Determines whether the specified object is equal to the current object. /// /// The object to compare with the current object. - /// if the specified object is equal to the current object; otherwise, . + /// if the specified object is equal to the current object; otherwise, . [EditorBrowsable(EditorBrowsableState.Never)] // ReSharper disable once BaseObjectEqualsIsObjectEquals - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object obj) + => base.Equals(obj); /// /// Serves as the default hash function. @@ -98,7 +101,8 @@ public virtual DbFunctionParameterBuilder PropagatesNullability(bool propagatesN /// A hash code for the current object. [EditorBrowsable(EditorBrowsableState.Never)] // ReSharper disable once BaseObjectGetHashCodeCallInGetHashCode - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); #endregion } diff --git a/src/EFCore.Relational/Metadata/Builders/IConventionDbFunctionBuilder.cs b/src/EFCore.Relational/Metadata/Builders/IConventionDbFunctionBuilder.cs index ff297a31eee..1bcc262bf31 100644 --- a/src/EFCore.Relational/Metadata/Builders/IConventionDbFunctionBuilder.cs +++ b/src/EFCore.Relational/Metadata/Builders/IConventionDbFunctionBuilder.cs @@ -151,7 +151,8 @@ public interface IConventionDbFunctionBuilder : IConventionAnnotatableBuilder /// otherwise. /// IConventionDbFunctionBuilder HasTranslation( - [CanBeNull] Func, SqlExpression> translation, bool fromDataAnnotation = false); + [CanBeNull] Func, SqlExpression> translation, + bool fromDataAnnotation = false); /// /// Returns a value indicating whether the given translation can be set for the database function. @@ -160,7 +161,8 @@ IConventionDbFunctionBuilder HasTranslation( /// Indicates whether the configuration was specified using a data annotation. /// if the given translation can be set for the database function. bool CanSetTranslation( - [CanBeNull] Func, SqlExpression> translation, bool fromDataAnnotation = false); + [CanBeNull] Func, SqlExpression> translation, + bool fromDataAnnotation = false); /// /// Returns an object that can be used to configure a parameter with the given name. diff --git a/src/EFCore.Relational/Metadata/Builders/IConventionDbFunctionParameterBuilder.cs b/src/EFCore.Relational/Metadata/Builders/IConventionDbFunctionParameterBuilder.cs index 10ffc4b1fc6..a4e8252b673 100644 --- a/src/EFCore.Relational/Metadata/Builders/IConventionDbFunctionParameterBuilder.cs +++ b/src/EFCore.Relational/Metadata/Builders/IConventionDbFunctionParameterBuilder.cs @@ -30,7 +30,7 @@ public interface IConventionDbFunctionParameterBuilder : IConventionAnnotatableB /// /// The store type of the function parameter in the database. /// Indicates whether the configuration was specified using a data annotation. - /// if the store type can be set for this property. + /// if the store type can be set for this property. bool CanSetStoreType([CanBeNull] string storeType, bool fromDataAnnotation = false); /// @@ -40,7 +40,8 @@ public interface IConventionDbFunctionParameterBuilder : IConventionAnnotatableB /// Indicates whether the configuration was specified using a data annotation. /// The same builder instance if the configuration was applied; null otherwise. IConventionDbFunctionParameterBuilder HasTypeMapping( - [CanBeNull] RelationalTypeMapping typeMapping, bool fromDataAnnotation = false); + [CanBeNull] RelationalTypeMapping typeMapping, + bool fromDataAnnotation = false); /// /// Returns a value indicating whether can be set for this property @@ -48,7 +49,7 @@ IConventionDbFunctionParameterBuilder HasTypeMapping( /// /// The type mapping to use for the function parameter. /// Indicates whether the configuration was specified using a data annotation. - /// if the type mapping can be set for this property. + /// if the type mapping can be set for this property. bool CanSetTypeMapping([CanBeNull] RelationalTypeMapping typeMapping, bool fromDataAnnotation = false); } } diff --git a/src/EFCore.Relational/Metadata/Builders/SequenceBuilder.cs b/src/EFCore.Relational/Metadata/Builders/SequenceBuilder.cs index 9831a4e9c2f..052dfbc3f8b 100644 --- a/src/EFCore.Relational/Metadata/Builders/SequenceBuilder.cs +++ b/src/EFCore.Relational/Metadata/Builders/SequenceBuilder.cs @@ -39,7 +39,8 @@ IConventionSequenceBuilder IInfrastructure.Instance /// /// The sequence. /// - public virtual IMutableSequence Metadata => Builder.Metadata; + public virtual IMutableSequence Metadata + => Builder.Metadata; /// /// Sets the to increment by the given amount when generating each next value. @@ -109,16 +110,18 @@ public virtual SequenceBuilder IsCyclic(bool cyclic = true) /// /// A string that represents the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override string ToString() => base.ToString(); + public override string ToString() + => base.ToString(); /// /// Determines whether the specified object is equal to the current object. /// /// The object to compare with the current object. - /// if the specified object is equal to the current object; otherwise, . + /// if the specified object is equal to the current object; otherwise, . [EditorBrowsable(EditorBrowsableState.Never)] // ReSharper disable once BaseObjectEqualsIsObjectEquals - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object obj) + => base.Equals(obj); /// /// Serves as the default hash function. @@ -126,7 +129,8 @@ public virtual SequenceBuilder IsCyclic(bool cyclic = true) /// A hash code for the current object. [EditorBrowsable(EditorBrowsableState.Never)] // ReSharper disable once BaseObjectGetHashCodeCallInGetHashCode - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); #endregion } diff --git a/src/EFCore.Relational/Metadata/Builders/TableBuilder.cs b/src/EFCore.Relational/Metadata/Builders/TableBuilder.cs index 4bd8fdcf2ef..1a8101095d3 100644 --- a/src/EFCore.Relational/Metadata/Builders/TableBuilder.cs +++ b/src/EFCore.Relational/Metadata/Builders/TableBuilder.cs @@ -48,22 +48,25 @@ public virtual TableBuilder ExcludeFromMigrations(bool excluded = true) /// /// A string that represents the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override string ToString() => base.ToString(); + public override string ToString() + => base.ToString(); /// /// Determines whether the specified object is equal to the current object. /// /// The object to compare with the current object. - /// if the specified object is equal to the current object; otherwise, . + /// if the specified object is equal to the current object; otherwise, . [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object obj) + => base.Equals(obj); /// /// Serves as the default hash function. /// /// A hash code for the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); #endregion } diff --git a/src/EFCore.Relational/Metadata/Builders/TableValuedFunctionBuilder.cs b/src/EFCore.Relational/Metadata/Builders/TableValuedFunctionBuilder.cs index e2c1f355d63..6ed5c1fd3c9 100644 --- a/src/EFCore.Relational/Metadata/Builders/TableValuedFunctionBuilder.cs +++ b/src/EFCore.Relational/Metadata/Builders/TableValuedFunctionBuilder.cs @@ -1,11 +1,8 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; -using System.Collections.Generic; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Query.SqlExpressions; namespace Microsoft.EntityFrameworkCore.Metadata.Builders { diff --git a/src/EFCore.Relational/Metadata/ColumnExtensions.cs b/src/EFCore.Relational/Metadata/ColumnExtensions.cs index d30950ded5d..1bba5d6f83d 100644 --- a/src/EFCore.Relational/Metadata/ColumnExtensions.cs +++ b/src/EFCore.Relational/Metadata/ColumnExtensions.cs @@ -56,8 +56,7 @@ public static string ToDebugString( builder.Append(")"); - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(column.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/ColumnMappingExtensions.cs b/src/EFCore.Relational/Metadata/ColumnMappingExtensions.cs index e79da406e0d..94e81833b57 100644 --- a/src/EFCore.Relational/Metadata/ColumnMappingExtensions.cs +++ b/src/EFCore.Relational/Metadata/ColumnMappingExtensions.cs @@ -38,7 +38,7 @@ public static string ToDebugString( var singleLine = (options & MetadataDebugStringOptions.SingleLine) != 0; if (singleLine) { - builder.Append($"ColumnMapping: "); + builder.Append("ColumnMapping: "); } builder @@ -52,8 +52,7 @@ public static string ToDebugString( .Append(".") .Append(columnMapping.Column.Name); - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(columnMapping.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/Conventions/DbFunctionTypeMappingConvention.cs b/src/EFCore.Relational/Metadata/Conventions/DbFunctionTypeMappingConvention.cs index fe478edb9e7..71572aadc61 100644 --- a/src/EFCore.Relational/Metadata/Conventions/DbFunctionTypeMappingConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/DbFunctionTypeMappingConvention.cs @@ -44,16 +44,18 @@ public virtual void ProcessModelFinalizing( // TODO: This check needs to be updated to skip over enumerable parameter of aggregate. foreach (var parameter in dbFunction.Parameters) { - parameter.Builder.HasTypeMapping(!string.IsNullOrEmpty(parameter.StoreType) - ? _relationalTypeMappingSource.FindMapping(parameter.StoreType) - : _relationalTypeMappingSource.FindMapping(parameter.ClrType)); + parameter.Builder.HasTypeMapping( + !string.IsNullOrEmpty(parameter.StoreType) + ? _relationalTypeMappingSource.FindMapping(parameter.StoreType) + : _relationalTypeMappingSource.FindMapping(parameter.ClrType)); } if (dbFunction.IsScalar) { - dbFunction.Builder.HasTypeMapping(!string.IsNullOrEmpty(dbFunction.StoreType) - ? _relationalTypeMappingSource.FindMapping(dbFunction.StoreType) - : _relationalTypeMappingSource.FindMapping(dbFunction.ReturnType)); + dbFunction.Builder.HasTypeMapping( + !string.IsNullOrEmpty(dbFunction.StoreType) + ? _relationalTypeMappingSource.FindMapping(dbFunction.StoreType) + : _relationalTypeMappingSource.FindMapping(dbFunction.ReturnType)); } } } diff --git a/src/EFCore.Relational/Metadata/Conventions/EntityTypeHierarchyMappingConvention.cs b/src/EFCore.Relational/Metadata/Conventions/EntityTypeHierarchyMappingConvention.cs index 9b870b32a38..21f6b1342ec 100644 --- a/src/EFCore.Relational/Metadata/Conventions/EntityTypeHierarchyMappingConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/EntityTypeHierarchyMappingConvention.cs @@ -26,7 +26,9 @@ public EntityTypeHierarchyMappingConvention( } /// - public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext context) + public virtual void ProcessModelFinalizing( + IConventionModelBuilder modelBuilder, + IConventionContext context) { var nonTphRoots = new HashSet(); @@ -46,7 +48,7 @@ public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, var pk = entityType.FindPrimaryKey(); if (pk != null && !entityType.FindDeclaredForeignKeys(pk.Properties) - .Any(fk => fk.PrincipalKey.IsPrimaryKey() && fk.PrincipalEntityType.IsAssignableFrom(entityType))) + .Any(fk => fk.PrincipalKey.IsPrimaryKey() && fk.PrincipalEntityType.IsAssignableFrom(entityType))) { entityType.Builder.HasRelationship(entityType.BaseType, pk.Properties, entityType.BaseType.FindPrimaryKey()) .IsUnique(true); diff --git a/src/EFCore.Relational/Metadata/Conventions/Infrastructure/RelationalConventionSetBuilder.cs b/src/EFCore.Relational/Metadata/Conventions/Infrastructure/RelationalConventionSetBuilder.cs index 07620b60970..7fa15a200fd 100644 --- a/src/EFCore.Relational/Metadata/Conventions/Infrastructure/RelationalConventionSetBuilder.cs +++ b/src/EFCore.Relational/Metadata/Conventions/Infrastructure/RelationalConventionSetBuilder.cs @@ -67,7 +67,8 @@ public override ConventionSet CreateConventionSet() var tableNameFromDbSetConvention = new TableNameFromDbSetConvention(Dependencies, RelationalDependencies); conventionSet.EntityTypeAddedConventions.Add(new RelationalTableAttributeConvention(Dependencies, RelationalDependencies)); - conventionSet.EntityTypeAddedConventions.Add(new RelationalTableCommentAttributeConvention(Dependencies, RelationalDependencies)); + conventionSet.EntityTypeAddedConventions.Add( + new RelationalTableCommentAttributeConvention(Dependencies, RelationalDependencies)); conventionSet.EntityTypeAddedConventions.Add(tableNameFromDbSetConvention); ValueGenerationConvention valueGenerationConvention = diff --git a/src/EFCore.Relational/Metadata/Conventions/RelationalDbFunctionAttributeConvention.cs b/src/EFCore.Relational/Metadata/Conventions/RelationalDbFunctionAttributeConvention.cs index cb92306a531..499d090ad28 100644 --- a/src/EFCore.Relational/Metadata/Conventions/RelationalDbFunctionAttributeConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/RelationalDbFunctionAttributeConvention.cs @@ -38,7 +38,8 @@ public RelationalDbFunctionAttributeConvention( /// The builder for the model. /// Additional information associated with convention execution. public virtual void ProcessModelInitialized( - IConventionModelBuilder modelBuilder, IConventionContext context) + IConventionModelBuilder modelBuilder, + IConventionContext context) { var contextType = Dependencies.ContextType; while (contextType != null @@ -62,7 +63,9 @@ public virtual void ProcessModelInitialized( } /// - public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext context) + public virtual void ProcessModelFinalizing( + IConventionModelBuilder modelBuilder, + IConventionContext context) { foreach (var function in modelBuilder.Metadata.GetDbFunctions()) { @@ -76,7 +79,8 @@ public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, /// The builder for the . /// Additional information associated with convention execution. protected virtual void ProcessDbFunctionAdded( - [NotNull] IConventionDbFunctionBuilder dbFunctionBuilder, [NotNull] IConventionContext context) + [NotNull] IConventionDbFunctionBuilder dbFunctionBuilder, + [NotNull] IConventionContext context) { var methodInfo = dbFunctionBuilder.Metadata.MethodInfo; var dbFunctionAttribute = methodInfo?.GetCustomAttributes().SingleOrDefault(); diff --git a/src/EFCore.Relational/Metadata/Conventions/RelationalMaxIdentifierLengthConvention.cs b/src/EFCore.Relational/Metadata/Conventions/RelationalMaxIdentifierLengthConvention.cs index 2a4f381e7d5..b8b61188626 100644 --- a/src/EFCore.Relational/Metadata/Conventions/RelationalMaxIdentifierLengthConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/RelationalMaxIdentifierLengthConvention.cs @@ -43,7 +43,8 @@ public RelationalMaxIdentifierLengthConvention( /// The builder for the model. /// Additional information associated with convention execution. public virtual void ProcessModelInitialized( - IConventionModelBuilder modelBuilder, IConventionContext context) + IConventionModelBuilder modelBuilder, + IConventionContext context) { modelBuilder.Metadata.Builder.HasMaxIdentifierLength(MaxIdentifierLength); } diff --git a/src/EFCore.Relational/Metadata/Conventions/RelationalModelConvention.cs b/src/EFCore.Relational/Metadata/Conventions/RelationalModelConvention.cs index fb4812e2659..365a20fddfb 100644 --- a/src/EFCore.Relational/Metadata/Conventions/RelationalModelConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/RelationalModelConvention.cs @@ -32,7 +32,7 @@ public RelationalModelConvention( /// public virtual IModel ProcessModelFinalized(IModel model) => model is IConventionModel conventionModel - ? RelationalModel.Add(conventionModel, RelationalDependencies.RelationalAnnotationProvider) - : model; + ? RelationalModel.Add(conventionModel, RelationalDependencies.RelationalAnnotationProvider) + : model; } } diff --git a/src/EFCore.Relational/Metadata/Conventions/RelationalQueryFilterRewritingConvention.cs b/src/EFCore.Relational/Metadata/Conventions/RelationalQueryFilterRewritingConvention.cs index 06f95e54293..9aad20eed92 100644 --- a/src/EFCore.Relational/Metadata/Conventions/RelationalQueryFilterRewritingConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/RelationalQueryFilterRewritingConvention.cs @@ -86,7 +86,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp else { var formattableString = Expression.Lambda>( - Expression.Convert(methodCallExpression.Arguments[1], typeof(FormattableString))).Compile().Invoke(); + Expression.Convert(methodCallExpression.Arguments[1], typeof(FormattableString))).Compile().Invoke(); sql = formattableString.Format; argument = Expression.Constant(formattableString.GetArguments()); diff --git a/src/EFCore.Relational/Metadata/Conventions/RelationalValueGenerationConvention.cs b/src/EFCore.Relational/Metadata/Conventions/RelationalValueGenerationConvention.cs index c41ea62a1a1..c4bfa170505 100644 --- a/src/EFCore.Relational/Metadata/Conventions/RelationalValueGenerationConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/RelationalValueGenerationConvention.cs @@ -93,9 +93,12 @@ public virtual void ProcessEntityTypeAnnotationChanged( } } - private void ProcessTableChanged(IConventionEntityTypeBuilder entityTypeBuilder, - string oldTable, string oldSchema, - string newTable, string newSchema) + private void ProcessTableChanged( + IConventionEntityTypeBuilder entityTypeBuilder, + string oldTable, + string oldSchema, + string newTable, + string newSchema) { var primaryKey = entityTypeBuilder.Metadata.FindPrimaryKey(); if (primaryKey == null) @@ -111,7 +114,7 @@ private void ProcessTableChanged(IConventionEntityTypeBuilder entityTypeBuilder, : null; if ((oldLink?.Any() != true - && newLink?.Any() != true) + && newLink?.Any() != true) || newLink == null) { return; @@ -148,7 +151,8 @@ private void ProcessTableChanged(IConventionEntityTypeBuilder entityTypeBuilder, public static ValueGenerated? GetValueGenerated([NotNull] IProperty property, in StoreObjectIdentifier storeObject) { var valueGenerated = GetValueGenerated(property); - return valueGenerated ?? (property.GetComputedColumnSql(storeObject) != null + return valueGenerated + ?? (property.GetComputedColumnSql(storeObject) != null ? ValueGenerated.OnAddOrUpdate : property.GetDefaultValue(storeObject) != null || property.GetDefaultValueSql(storeObject) != null ? ValueGenerated.OnAdd diff --git a/src/EFCore.Relational/Metadata/Conventions/SequenceUniquificationConvention.cs b/src/EFCore.Relational/Metadata/Conventions/SequenceUniquificationConvention.cs index a2dfbd000d0..c0bc8e2d55c 100644 --- a/src/EFCore.Relational/Metadata/Conventions/SequenceUniquificationConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/SequenceUniquificationConvention.cs @@ -35,7 +35,9 @@ public SequenceUniquificationConvention( protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; } /// - public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext context) + public virtual void ProcessModelFinalizing( + IConventionModelBuilder modelBuilder, + IConventionContext context) { var model = modelBuilder.Metadata; var modelSequences = diff --git a/src/EFCore.Relational/Metadata/Conventions/SharedTableConvention.cs b/src/EFCore.Relational/Metadata/Conventions/SharedTableConvention.cs index 9daa096b0fe..278e6fcbf34 100644 --- a/src/EFCore.Relational/Metadata/Conventions/SharedTableConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/SharedTableConvention.cs @@ -10,7 +10,6 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Internal; -using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Metadata.Conventions { @@ -37,7 +36,9 @@ public SharedTableConvention( protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; } /// - public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext context) + public virtual void ProcessModelFinalizing( + IConventionModelBuilder modelBuilder, + IConventionContext context) { var maxLength = modelBuilder.Metadata.GetMaxIdentifierLength(); var tables = new Dictionary<(string TableName, string Schema), List>(); @@ -66,7 +67,9 @@ public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, } private static void TryUniquifyTableNames( - IConventionModel model, Dictionary<(string Name, string Schema), List> tables, int maxLength) + IConventionModel model, + Dictionary<(string Name, string Schema), List> tables, + int maxLength) { Dictionary<(string Name, string Schema), Dictionary<(string Name, string Schema), List>> clashingTables = null; @@ -106,7 +109,9 @@ private static void TryUniquifyTableNames( if (clashingTables == null) { - clashingTables = new Dictionary<(string Name, string Schema), Dictionary<(string Name, string Schema), List>>(); + clashingTables = + new Dictionary<(string Name, string Schema), + Dictionary<(string Name, string Schema), List>>(); } if (!clashingTables.TryGetValue(table, out var clashingSubTables)) @@ -171,7 +176,7 @@ private static void TryUniquifyColumnNames( var identifyingMemberInfo = property.PropertyInfo ?? (MemberInfo)property.FieldInfo; if ((identifyingMemberInfo != null - && identifyingMemberInfo.IsSameAs(otherProperty.PropertyInfo ?? (MemberInfo)otherProperty.FieldInfo)) + && identifyingMemberInfo.IsSameAs(otherProperty.PropertyInfo ?? (MemberInfo)otherProperty.FieldInfo)) || (property.IsPrimaryKey() && otherProperty.IsPrimaryKey()) || (property.IsConcurrencyToken && otherProperty.IsConcurrencyToken)) { @@ -208,7 +213,10 @@ private static void TryUniquifyColumnNames( } private static string TryUniquify( - IConventionProperty property, string columnName, Dictionary properties, bool usePrefix, + IConventionProperty property, + string columnName, + Dictionary properties, + bool usePrefix, int maxLength) { if (property.Builder.CanSetColumnName(null)) @@ -280,7 +288,7 @@ private void TryUniquifyKeyNames( /// A key. /// Another key. /// The identifier of the store object. - /// if compatible + /// if compatible protected virtual bool AreCompatible( [NotNull] IKey key, [NotNull] IKey duplicateKey, @@ -288,7 +296,10 @@ protected virtual bool AreCompatible( => key.AreCompatible(duplicateKey, storeObject, shouldThrow: false); private static string TryUniquify( - IConventionKey key, string keyName, Dictionary keys, int maxLength) + IConventionKey key, + string keyName, + Dictionary keys, + int maxLength) { if (key.Builder.CanSetName(null)) { @@ -347,7 +358,7 @@ private void TryUniquifyIndexNames( /// An index. /// Another index. /// The identifier of the store object. - /// if compatible + /// if compatible protected virtual bool AreCompatible( [NotNull] IIndex index, [NotNull] IIndex duplicateIndex, @@ -355,7 +366,10 @@ protected virtual bool AreCompatible( => index.AreCompatible(duplicateIndex, storeObject, shouldThrow: false); private static string TryUniquify( - IConventionIndex index, string indexName, Dictionary indexes, int maxLength) + IConventionIndex index, + string indexName, + Dictionary indexes, + int maxLength) { if (index.Builder.CanSetDatabaseName(null)) { @@ -435,7 +449,7 @@ private void TryUniquifyForeignKeyNames( /// A foreign key. /// Another foreign key. /// The identifier of the store object. - /// if compatible + /// if compatible protected virtual bool AreCompatible( [NotNull] IForeignKey foreignKey, [NotNull] IForeignKey duplicateForeignKey, @@ -443,7 +457,10 @@ protected virtual bool AreCompatible( => foreignKey.AreCompatible(duplicateForeignKey, storeObject, shouldThrow: false); private static string TryUniquify( - IConventionForeignKey foreignKey, string foreignKeyName, Dictionary foreignKeys, int maxLength) + IConventionForeignKey foreignKey, + string foreignKeyName, + Dictionary foreignKeys, + int maxLength) { if (foreignKey.Builder.CanSetConstraintName(null)) { diff --git a/src/EFCore.Relational/Metadata/Conventions/StoreGenerationConvention.cs b/src/EFCore.Relational/Metadata/Conventions/StoreGenerationConvention.cs index 23f11803720..229944fb229 100644 --- a/src/EFCore.Relational/Metadata/Conventions/StoreGenerationConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/StoreGenerationConvention.cs @@ -87,7 +87,9 @@ public virtual void ProcessPropertyAnnotationChanged( } /// - public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext context) + public virtual void ProcessModelFinalizing( + IConventionModelBuilder modelBuilder, + IConventionContext context) { foreach (var entityType in modelBuilder.Metadata.GetEntityTypes()) { diff --git a/src/EFCore.Relational/Metadata/Conventions/TableNameFromDbSetConvention.cs b/src/EFCore.Relational/Metadata/Conventions/TableNameFromDbSetConvention.cs index a6ff811bd57..27fdbffd693 100644 --- a/src/EFCore.Relational/Metadata/Conventions/TableNameFromDbSetConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/TableNameFromDbSetConvention.cs @@ -35,10 +35,11 @@ public TableNameFromDbSetConvention( } else { - if(ambiguousTypes == null) + if (ambiguousTypes == null) { ambiguousTypes = new List(); } + ambiguousTypes.Add(set.Type); } } @@ -107,7 +108,9 @@ public virtual void ProcessEntityTypeAdded( } /// - public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext context) + public virtual void ProcessModelFinalizing( + IConventionModelBuilder modelBuilder, + IConventionContext context) { foreach (var entityType in modelBuilder.Metadata.GetEntityTypes()) { diff --git a/src/EFCore.Relational/Metadata/Conventions/TableSharingConcurrencyTokenConvention.cs b/src/EFCore.Relational/Metadata/Conventions/TableSharingConcurrencyTokenConvention.cs index b584c1ef101..4728edf5892 100644 --- a/src/EFCore.Relational/Metadata/Conventions/TableSharingConcurrencyTokenConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/TableSharingConcurrencyTokenConvention.cs @@ -91,6 +91,7 @@ public virtual void ProcessModelFinalizing( { entityTypesMissingConcurrencyColumn = new Dictionary(); } + // store the entity type which is missing the // concurrency token property, mapped to an example // property which _is_ mapped to this concurrency token @@ -131,7 +132,8 @@ public virtual void ProcessModelFinalizing( /// [EntityFrameworkInternal] public static Dictionary> GetConcurrencyTokensMap( - in StoreObjectIdentifier storeObject, [NotNull] IReadOnlyList mappedTypes) + in StoreObjectIdentifier storeObject, + [NotNull] IReadOnlyList mappedTypes) { if (mappedTypes.Count < 2) { @@ -211,12 +213,14 @@ public static bool IsConcurrencyTokenMissing( } var linkingFks = declaringEntityType.FindForeignKeys(declaringEntityType.FindPrimaryKey().Properties) - .Where(fk => fk.PrincipalKey.IsPrimaryKey() - && mappedTypes.Contains(fk.PrincipalEntityType)).ToList(); + .Where( + fk => fk.PrincipalKey.IsPrimaryKey() + && mappedTypes.Contains(fk.PrincipalEntityType)).ToList(); if (linkingFks.Count > 0 && !linkingFks.Any(fk => fk.PrincipalEntityType == entityType) - && linkingFks.Any(fk => fk.PrincipalEntityType.IsAssignableFrom(entityType) - || entityType.IsAssignableFrom(fk.PrincipalEntityType))) + && linkingFks.Any( + fk => fk.PrincipalEntityType.IsAssignableFrom(entityType) + || entityType.IsAssignableFrom(fk.PrincipalEntityType))) { // The concurrency token is on a type that shares the row with a base or derived type continue; diff --git a/src/EFCore.Relational/Metadata/Conventions/TableValuedDbFunctionConvention.cs b/src/EFCore.Relational/Metadata/Conventions/TableValuedDbFunctionConvention.cs index 282c7c999ba..55e9126740d 100644 --- a/src/EFCore.Relational/Metadata/Conventions/TableValuedDbFunctionConvention.cs +++ b/src/EFCore.Relational/Metadata/Conventions/TableValuedDbFunctionConvention.cs @@ -34,7 +34,9 @@ public TableValuedDbFunctionConvention( protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; } /// - public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext context) + public virtual void ProcessModelFinalizing( + IConventionModelBuilder modelBuilder, + IConventionContext context) { foreach (var function in modelBuilder.Metadata.GetDbFunctions()) { @@ -48,7 +50,8 @@ public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, /// The builder for the . /// Additional information associated with convention execution. private void ProcessDbFunctionAdded( - [NotNull] IConventionDbFunctionBuilder dbFunctionBuilder, [NotNull] IConventionContext context) + [NotNull] IConventionDbFunctionBuilder dbFunctionBuilder, + [NotNull] IConventionContext context) { var function = dbFunctionBuilder.Metadata; if (function.IsScalar) @@ -59,8 +62,9 @@ private void ProcessDbFunctionAdded( var elementType = function.ReturnType.TryGetElementType(typeof(IQueryable<>)); if (!elementType.IsValidEntityType()) { - throw new InvalidOperationException(RelationalStrings.DbFunctionInvalidIQueryableReturnType( - function.ModelName, function.ReturnType.ShortDisplayName())); + throw new InvalidOperationException( + RelationalStrings.DbFunctionInvalidIQueryableReturnType( + function.ModelName, function.ReturnType.ShortDisplayName())); } var model = function.Model; @@ -84,6 +88,7 @@ private void ProcessDbFunctionAdded( { return; } + entityType = entityTypeBuilder.Metadata; } diff --git a/src/EFCore.Relational/Metadata/ForeignKeyConstraintExtensions.cs b/src/EFCore.Relational/Metadata/ForeignKeyConstraintExtensions.cs index d3553989b2c..ac57e10eea6 100644 --- a/src/EFCore.Relational/Metadata/ForeignKeyConstraintExtensions.cs +++ b/src/EFCore.Relational/Metadata/ForeignKeyConstraintExtensions.cs @@ -60,8 +60,7 @@ public static string ToDebugString( .Append(foreignKey.OnDeleteAction); } - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(foreignKey.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/FunctionColumnExtensions.cs b/src/EFCore.Relational/Metadata/FunctionColumnExtensions.cs index 49e5bb86442..d744ccc1d6b 100644 --- a/src/EFCore.Relational/Metadata/FunctionColumnExtensions.cs +++ b/src/EFCore.Relational/Metadata/FunctionColumnExtensions.cs @@ -56,8 +56,7 @@ public static string ToDebugString( builder.Append(")"); - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(column.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/FunctionColumnMappingExtensions.cs b/src/EFCore.Relational/Metadata/FunctionColumnMappingExtensions.cs index 185772d362f..95f0b75107b 100644 --- a/src/EFCore.Relational/Metadata/FunctionColumnMappingExtensions.cs +++ b/src/EFCore.Relational/Metadata/FunctionColumnMappingExtensions.cs @@ -38,15 +38,14 @@ public static string ToDebugString( var singleLine = (options & MetadataDebugStringOptions.SingleLine) != 0; if (singleLine) { - builder.Append($"FunctionColumnMapping: "); + builder.Append("FunctionColumnMapping: "); } builder.Append(columnMapping.Property.Name).Append(" - "); builder.Append(columnMapping.Column.Name); - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(columnMapping.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/FunctionMappingExtensions.cs b/src/EFCore.Relational/Metadata/FunctionMappingExtensions.cs index 01e4090bc22..ef30b7cfb8c 100644 --- a/src/EFCore.Relational/Metadata/FunctionMappingExtensions.cs +++ b/src/EFCore.Relational/Metadata/FunctionMappingExtensions.cs @@ -38,7 +38,7 @@ public static string ToDebugString( var singleLine = (options & MetadataDebugStringOptions.SingleLine) != 0; if (singleLine) { - builder.Append($"FunctionMapping: "); + builder.Append("FunctionMapping: "); } builder.Append(functionMapping.EntityType.Name).Append(" - "); @@ -47,16 +47,15 @@ public static string ToDebugString( if (functionMapping.IsDefaultFunctionMapping) { - builder.Append($" DefaultMapping"); + builder.Append(" DefaultMapping"); } if (functionMapping.IncludesDerivedTypes) { - builder.Append($" IncludesDerivedTypes"); + builder.Append(" IncludesDerivedTypes"); } - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(functionMapping.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/IColumn.cs b/src/EFCore.Relational/Metadata/IColumn.cs index 3d3ffbee915..48947fe4dbe 100644 --- a/src/EFCore.Relational/Metadata/IColumn.cs +++ b/src/EFCore.Relational/Metadata/IColumn.cs @@ -25,36 +25,42 @@ public interface IColumn : IColumnBase /// Gets the maximum length of data that is allowed in this column. For example, if the property is a ' /// then this is the maximum number of characters. /// - int? MaxLength => PropertyMappings.First().Property.GetMaxLength(); + int? MaxLength + => PropertyMappings.First().Property.GetMaxLength(); /// /// Gets the precision of data that is allowed in this column. For example, if the property is a ' /// then this is the maximum number of digits. /// - int? Precision => PropertyMappings.First().Property.GetPrecision(); + int? Precision + => PropertyMappings.First().Property.GetPrecision(); /// /// Gets the scale of data that is allowed in this column. For example, if the property is a ' /// then this is the maximum number of decimal places. /// - int? Scale => PropertyMappings.First().Property.GetScale(); + int? Scale + => PropertyMappings.First().Property.GetScale(); /// /// Gets a value indicating whether or not the property can persist Unicode characters. /// - bool? IsUnicode => PropertyMappings.First().Property.IsUnicode(); + bool? IsUnicode + => PropertyMappings.First().Property.IsUnicode(); /// /// Returns a flag indicating if the property as capable of storing only fixed-length data, such as strings. /// - bool? IsFixedLength => PropertyMappings.First().Property.IsFixedLength(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); + bool? IsFixedLength + => PropertyMappings.First().Property.IsFixedLength(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); /// /// Indicates whether or not this column acts as an automatic concurrency token by generating a different value /// on every update in the same vein as 'rowversion'/'timestamp' columns on SQL Server. /// - bool IsRowVersion => PropertyMappings.First().Property.IsConcurrencyToken - && PropertyMappings.First().Property.ValueGenerated == ValueGenerated.OnAddOrUpdate; + bool IsRowVersion + => PropertyMappings.First().Property.IsConcurrencyToken + && PropertyMappings.First().Property.ValueGenerated == ValueGenerated.OnAddOrUpdate; /// /// Returns the object that is used as the default value for this column. @@ -76,32 +82,37 @@ public virtual object DefaultValue /// /// Returns the SQL expression that is used as the default value for this column. /// - public virtual string DefaultValueSql => PropertyMappings.First().Property - .GetDefaultValueSql(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); + public virtual string DefaultValueSql + => PropertyMappings.First().Property + .GetDefaultValueSql(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); /// /// Returns the SQL expression that is used as the computed value for this column. /// - public virtual string ComputedColumnSql => PropertyMappings.First().Property - .GetComputedColumnSql(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); + public virtual string ComputedColumnSql + => PropertyMappings.First().Property + .GetComputedColumnSql(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); /// /// Returns whether the value of the computed column this property is mapped to is stored in the database, or calculated when /// it is read. /// - public virtual bool? IsStored => PropertyMappings.First().Property - .GetIsStored(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); + public virtual bool? IsStored + => PropertyMappings.First().Property + .GetIsStored(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); /// /// Comment for this column /// - public virtual string Comment => PropertyMappings.First().Property - .GetComment(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); + public virtual string Comment + => PropertyMappings.First().Property + .GetComment(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); /// /// Collation for this column /// - public virtual string Collation => PropertyMappings.First().Property - .GetCollation(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); + public virtual string Collation + => PropertyMappings.First().Property + .GetCollation(StoreObjectIdentifier.Table(Table.Name, Table.Schema)); } } diff --git a/src/EFCore.Relational/Metadata/IConventionDbFunction.cs b/src/EFCore.Relational/Metadata/IConventionDbFunction.cs index 2a02dd4fb9d..a7bc0aa59f3 100644 --- a/src/EFCore.Relational/Metadata/IConventionDbFunction.cs +++ b/src/EFCore.Relational/Metadata/IConventionDbFunction.cs @@ -125,7 +125,8 @@ public interface IConventionDbFunction : IConventionAnnotatable, IDbFunction /// Indicates whether the configuration was specified using a data annotation. /// The configured value. Func, SqlExpression> SetTranslation( - [CanBeNull] Func, SqlExpression> translation, bool fromDataAnnotation = false); + [CanBeNull] Func, SqlExpression> translation, + bool fromDataAnnotation = false); /// /// Gets the configuration source for . diff --git a/src/EFCore.Relational/Metadata/IDbFunction.cs b/src/EFCore.Relational/Metadata/IDbFunction.cs index c015b9677ab..df018c20b9a 100644 --- a/src/EFCore.Relational/Metadata/IDbFunction.cs +++ b/src/EFCore.Relational/Metadata/IDbFunction.cs @@ -86,7 +86,7 @@ public interface IDbFunction : IAnnotatable Func, SqlExpression> Translation { get; } /// - /// Gets the associated . + /// Gets the associated . /// IStoreFunction StoreFunction { get; } } diff --git a/src/EFCore.Relational/Metadata/IDbFunctionParameter.cs b/src/EFCore.Relational/Metadata/IDbFunctionParameter.cs index cc483f6c8d0..792316c36e7 100644 --- a/src/EFCore.Relational/Metadata/IDbFunctionParameter.cs +++ b/src/EFCore.Relational/Metadata/IDbFunctionParameter.cs @@ -33,7 +33,8 @@ public interface IDbFunctionParameter : IAnnotatable string StoreType { get; } /// - /// Gets the value which indicates whether parameter propagates nullability, meaning if it's value is null the database function itself returns null. + /// Gets the value which indicates whether parameter propagates nullability, meaning if it's value is null the database function itself + /// returns null. /// bool PropagatesNullability { get; } @@ -43,7 +44,7 @@ public interface IDbFunctionParameter : IAnnotatable RelationalTypeMapping TypeMapping { get; } /// - /// Gets the associated . + /// Gets the associated . /// IStoreFunctionParameter StoreFunctionParameter { get; } } diff --git a/src/EFCore.Relational/Metadata/IRelationalModel.cs b/src/EFCore.Relational/Metadata/IRelationalModel.cs index 82bc3143a90..f9c984a5401 100644 --- a/src/EFCore.Relational/Metadata/IRelationalModel.cs +++ b/src/EFCore.Relational/Metadata/IRelationalModel.cs @@ -37,7 +37,8 @@ public interface IRelationalModel : IAnnotatable /// /// Returns all sequences contained in the model. /// - IEnumerable Sequences => Model.GetSequences(); + IEnumerable Sequences + => Model.GetSequences(); /// /// Returns all user-defined functions contained in the model. @@ -47,7 +48,8 @@ public interface IRelationalModel : IAnnotatable /// /// Returns the database collation. /// - string Collation => Model.GetCollation(); + string Collation + => Model.GetCollation(); /// /// Gets the table with the given name. Returns if no table with the given name is defined. diff --git a/src/EFCore.Relational/Metadata/IStoreFunction.cs b/src/EFCore.Relational/Metadata/IStoreFunction.cs index b6d37e9ec88..433a05008e2 100644 --- a/src/EFCore.Relational/Metadata/IStoreFunction.cs +++ b/src/EFCore.Relational/Metadata/IStoreFunction.cs @@ -12,7 +12,7 @@ namespace Microsoft.EntityFrameworkCore.Metadata public interface IStoreFunction : ITableBase { /// - /// Gets the associated s. + /// Gets the associated s. /// IEnumerable DbFunctions { get; } diff --git a/src/EFCore.Relational/Metadata/IStoreFunctionParameter.cs b/src/EFCore.Relational/Metadata/IStoreFunctionParameter.cs index e866536ad37..062df759837 100644 --- a/src/EFCore.Relational/Metadata/IStoreFunctionParameter.cs +++ b/src/EFCore.Relational/Metadata/IStoreFunctionParameter.cs @@ -17,7 +17,7 @@ public interface IStoreFunctionParameter : IAnnotatable IStoreFunction Function { get; } /// - /// Gets the associated s. + /// Gets the associated s. /// IEnumerable DbFunctionParameters { get; } diff --git a/src/EFCore.Relational/Metadata/ITableMappingBase.cs b/src/EFCore.Relational/Metadata/ITableMappingBase.cs index d725b9a3257..9e414654aa1 100644 --- a/src/EFCore.Relational/Metadata/ITableMappingBase.cs +++ b/src/EFCore.Relational/Metadata/ITableMappingBase.cs @@ -40,7 +40,7 @@ public interface ITableMappingBase : IAnnotatable /// /// Gets the value indicating whether the mapped table-like object includes rows for the derived entity types. - /// Set to for inherited mappings. + /// Set to for inherited mappings. /// bool IncludesDerivedTypes { get; } } diff --git a/src/EFCore.Relational/Metadata/Internal/CheckConstraint.cs b/src/EFCore.Relational/Metadata/Internal/CheckConstraint.cs index a865e0a1e2a..6bc5e55b558 100644 --- a/src/EFCore.Relational/Metadata/Internal/CheckConstraint.cs +++ b/src/EFCore.Relational/Metadata/Internal/CheckConstraint.cs @@ -77,13 +77,16 @@ public static IEnumerable GetCheckConstraints([NotNull] IEntity /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public static ICheckConstraint FindCheckConstraint( - [NotNull] IEntityType entityType, [NotNull] string name) + [NotNull] IEntityType entityType, + [NotNull] string name) { var dataDictionary = GetConstraintsDictionary(entityType); return dataDictionary == null ? null - : dataDictionary.TryGetValue(name, out var checkConstraint) ? checkConstraint : null; + : dataDictionary.TryGetValue(name, out var checkConstraint) + ? checkConstraint + : null; } /// @@ -93,7 +96,8 @@ public static ICheckConstraint FindCheckConstraint( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public static CheckConstraint RemoveCheckConstraint( - [NotNull] IMutableEntityType entityType, [NotNull] string name) + [NotNull] IMutableEntityType entityType, + [NotNull] string name) { var dataDictionary = GetConstraintsDictionary(entityType); @@ -137,7 +141,8 @@ public static CheckConstraint RemoveCheckConstraint( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource GetConfigurationSource() => _configurationSource; + public virtual ConfigurationSource GetConfigurationSource() + => _configurationSource; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -159,7 +164,8 @@ private static Dictionary GetConstraintsDictionary(IEnt /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -167,7 +173,8 @@ private static Dictionary GetConstraintsDictionary(IEnt /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - IConventionEntityType IConventionCheckConstraint.EntityType => (IConventionEntityType)EntityType; + IConventionEntityType IConventionCheckConstraint.EntityType + => (IConventionEntityType)EntityType; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -175,6 +182,7 @@ private static Dictionary GetConstraintsDictionary(IEnt /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - IMutableEntityType IMutableCheckConstraint.EntityType => (IMutableEntityType)EntityType; + IMutableEntityType IMutableCheckConstraint.EntityType + => (IMutableEntityType)EntityType; } } diff --git a/src/EFCore.Relational/Metadata/Internal/Column.cs b/src/EFCore.Relational/Metadata/Internal/Column.cs index c8d6a53f1c3..8a5f49019fe 100644 --- a/src/EFCore.Relational/Metadata/Internal/Column.cs +++ b/src/EFCore.Relational/Metadata/Internal/Column.cs @@ -28,8 +28,9 @@ public Column([NotNull] string name, [CanBeNull] string type, [NotNull] Table ta { } - /// - public new virtual ITable Table => (ITable)base.Table; + /// + public new virtual ITable Table + => (ITable)base.Table; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -37,9 +38,10 @@ public Column([NotNull] string name, [CanBeNull] string type, [NotNull] Table ta /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IEnumerable IColumn.PropertyMappings { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/ColumnBase.cs b/src/EFCore.Relational/Metadata/Internal/ColumnBase.cs index 8a008f74afb..8e5936e6c96 100644 --- a/src/EFCore.Relational/Metadata/Internal/ColumnBase.cs +++ b/src/EFCore.Relational/Metadata/Internal/ColumnBase.cs @@ -30,16 +30,16 @@ public ColumnBase([NotNull] string name, [NotNull] string type, [NotNull] TableB Table = table; } - /// + /// public virtual string Name { get; } - /// + /// public virtual ITableBase Table { get; } - /// + /// public virtual string StoreType { get; } - /// + /// public virtual bool IsNullable { get; set; } /// @@ -64,7 +64,7 @@ public static string Format([NotNull] IEnumerable columns) columns.Select(p => "'" + p.Name + "'")) + "}"; - /// + /// IEnumerable IColumnBase.PropertyMappings { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/ColumnMapping.cs b/src/EFCore.Relational/Metadata/Internal/ColumnMapping.cs index 85903e13406..be9e1da9f42 100644 --- a/src/EFCore.Relational/Metadata/Internal/ColumnMapping.cs +++ b/src/EFCore.Relational/Metadata/Internal/ColumnMapping.cs @@ -31,8 +31,9 @@ public ColumnMapping( { } - /// - public new virtual ITableMapping TableMapping => (ITableMapping)base.TableMapping; + /// + public new virtual ITableMapping TableMapping + => (ITableMapping)base.TableMapping; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -40,9 +41,10 @@ public ColumnMapping( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IColumn IColumnMapping.Column { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/ColumnMappingBase.cs b/src/EFCore.Relational/Metadata/Internal/ColumnMappingBase.cs index efdec9f4782..b3048933aa8 100644 --- a/src/EFCore.Relational/Metadata/Internal/ColumnMappingBase.cs +++ b/src/EFCore.Relational/Metadata/Internal/ColumnMappingBase.cs @@ -33,16 +33,16 @@ public ColumnMappingBase( TableMapping = tableMapping; } - /// + /// public virtual IProperty Property { get; } - /// + /// public virtual IColumnBase Column { get; } - /// + /// public virtual RelationalTypeMapping TypeMapping { get; } - /// + /// public virtual ITableMappingBase TableMapping { get; } } } diff --git a/src/EFCore.Relational/Metadata/Internal/DbFunction.cs b/src/EFCore.Relational/Metadata/Internal/DbFunction.cs index 1912799cea4..3830a9e8cc2 100644 --- a/src/EFCore.Relational/Metadata/Internal/DbFunction.cs +++ b/src/EFCore.Relational/Metadata/Internal/DbFunction.cs @@ -54,11 +54,12 @@ public DbFunction( [NotNull] MethodInfo methodInfo, [NotNull] IMutableModel model, ConfigurationSource configurationSource) - : this(methodInfo.Name, - methodInfo.ReturnType, - methodInfo.GetParameters().Select(pi => (pi.Name, pi.ParameterType)), - model, - configurationSource) + : this( + methodInfo.Name, + methodInfo.ReturnType, + methodInfo.GetParameters().Select(pi => (pi.Name, pi.ParameterType)), + model, + configurationSource) { if (methodInfo.IsGenericMethod) { @@ -123,8 +124,12 @@ public DbFunction( } private static string GetFunctionName(MethodInfo methodInfo, ParameterInfo[] parameters) - => methodInfo.DeclaringType.FullName + "." + methodInfo.Name - + "(" + string.Join(",", parameters.Select(p => p.ParameterType.FullName)) + ")"; + => methodInfo.DeclaringType.FullName + + "." + + methodInfo.Name + + "(" + + string.Join(",", parameters.Select(p => p.ParameterType.FullName)) + + ")"; /// public virtual IMutableModel Model { get; } @@ -145,7 +150,8 @@ private static string GetFunctionName(MethodInfo methodInfo, ParameterInfo[] par /// public static IEnumerable GetDbFunctions([NotNull] IModel model) => ((SortedDictionary)model[RelationalAnnotationNames.DbFunctions]) - ?.Values ?? Enumerable.Empty(); + ?.Values + ?? Enumerable.Empty(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -155,9 +161,9 @@ public static IEnumerable GetDbFunctions([NotNull] IModel model) /// public static DbFunction FindDbFunction([NotNull] IModel model, [NotNull] MethodInfo methodInfo) => model[RelationalAnnotationNames.DbFunctions] is SortedDictionary functions - && functions.TryGetValue(GetFunctionName(methodInfo, methodInfo.GetParameters()), out var dbFunction) - ? dbFunction - : null; + && functions.TryGetValue(GetFunctionName(methodInfo, methodInfo.GetParameters()), out var dbFunction) + ? dbFunction + : null; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -167,9 +173,9 @@ public static DbFunction FindDbFunction([NotNull] IModel model, [NotNull] Method /// public static DbFunction FindDbFunction([NotNull] IModel model, [NotNull] string name) => model[RelationalAnnotationNames.DbFunctions] is SortedDictionary functions - && functions.TryGetValue(name, out var dbFunction) - ? dbFunction - : null; + && functions.TryGetValue(name, out var dbFunction) + ? dbFunction + : null; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -178,7 +184,9 @@ public static DbFunction FindDbFunction([NotNull] IModel model, [NotNull] string /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public static DbFunction AddDbFunction( - [NotNull] IMutableModel model, [NotNull] MethodInfo methodInfo, ConfigurationSource configurationSource) + [NotNull] IMutableModel model, + [NotNull] MethodInfo methodInfo, + ConfigurationSource configurationSource) { var function = new DbFunction(methodInfo, model, configurationSource); @@ -254,7 +262,7 @@ public static DbFunction RemoveDbFunction( } /// - public virtual string ModelName { get; private set; } + public virtual string ModelName { get; } /// public virtual MethodInfo MethodInfo { get; } @@ -318,7 +326,8 @@ public virtual string SetSchema([CanBeNull] string schema, ConfigurationSource c /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetSchemaConfigurationSource() => _schemaConfigurationSource; + public virtual ConfigurationSource? GetSchemaConfigurationSource() + => _schemaConfigurationSource; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -357,7 +366,8 @@ public virtual string SetName([CanBeNull] string name, ConfigurationSource confi /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetNameConfigurationSource() => _nameConfigurationSource; + public virtual ConfigurationSource? GetNameConfigurationSource() + => _nameConfigurationSource; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -391,7 +401,8 @@ public virtual bool SetIsBuiltIn(bool builtIn, ConfigurationSource configuration /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetIsBuiltInConfigurationSource() => _builtInConfigurationSource; + public virtual ConfigurationSource? GetIsBuiltInConfigurationSource() + => _builtInConfigurationSource; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -430,7 +441,8 @@ public virtual bool SetIsNullable(bool nullable, ConfigurationSource configurati /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetIsNullableConfigurationSource() => _nullableConfigurationSource; + public virtual ConfigurationSource? GetIsNullableConfigurationSource() + => _nullableConfigurationSource; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -467,7 +479,8 @@ public virtual string SetStoreType([CanBeNull] string storeType, ConfigurationSo /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetStoreTypeConfigurationSource() => _storeTypeConfigurationSource; + public virtual ConfigurationSource? GetStoreTypeConfigurationSource() + => _storeTypeConfigurationSource; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -488,7 +501,8 @@ public virtual RelationalTypeMapping TypeMapping /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual RelationalTypeMapping SetTypeMapping( - [CanBeNull] RelationalTypeMapping typeMapping, ConfigurationSource configurationSource) + [CanBeNull] RelationalTypeMapping typeMapping, + ConfigurationSource configurationSource) { _typeMapping = typeMapping; @@ -505,7 +519,8 @@ public virtual RelationalTypeMapping SetTypeMapping( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetTypeMappingConfigurationSource() => _typeMappingConfigurationSource; + public virtual ConfigurationSource? GetTypeMappingConfigurationSource() + => _typeMappingConfigurationSource; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -556,7 +571,8 @@ public virtual Func, SqlExpression> SetTransl /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetTranslationConfigurationSource() => _translationConfigurationSource; + public virtual ConfigurationSource? GetTranslationConfigurationSource() + => _translationConfigurationSource; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -572,7 +588,8 @@ public virtual Func, SqlExpression> SetTransl /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); /// IConventionDbFunctionBuilder IConventionDbFunction.Builder @@ -634,7 +651,8 @@ IReadOnlyList IMutableDbFunction.Parameters /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual DbFunctionParameter FindParameter([NotNull] string name) => Parameters.SingleOrDefault(p => p.Name == name); + public virtual DbFunctionParameter FindParameter([NotNull] string name) + => Parameters.SingleOrDefault(p => p.Name == name); /// [DebuggerStepThrough] @@ -669,7 +687,8 @@ RelationalTypeMapping IConventionDbFunction.SetTypeMapping(RelationalTypeMapping /// [DebuggerStepThrough] Func, SqlExpression> IConventionDbFunction.SetTranslation( - Func, SqlExpression> translation, bool fromDataAnnotation) + Func, SqlExpression> translation, + bool fromDataAnnotation) => SetTranslation(translation, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); } } diff --git a/src/EFCore.Relational/Metadata/Internal/DbFunctionParameter.cs b/src/EFCore.Relational/Metadata/Internal/DbFunctionParameter.cs index 2666e43bc7f..3af162b9679 100644 --- a/src/EFCore.Relational/Metadata/Internal/DbFunctionParameter.cs +++ b/src/EFCore.Relational/Metadata/Internal/DbFunctionParameter.cs @@ -56,10 +56,11 @@ public DbFunctionParameter( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual InternalDbFunctionParameterBuilder Builder { get; private set; } + public virtual InternalDbFunctionParameterBuilder Builder { get; } /// - IConventionDbFunctionParameterBuilder IConventionDbFunctionParameter.Builder => Builder; + IConventionDbFunctionParameterBuilder IConventionDbFunctionParameter.Builder + => Builder; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -98,7 +99,8 @@ IMutableDbFunction IMutableDbFunctionParameter.Function /// [DebuggerStepThrough] - public virtual ConfigurationSource GetConfigurationSource() => Function.GetConfigurationSource(); + public virtual ConfigurationSource GetConfigurationSource() + => Function.GetConfigurationSource(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -133,7 +135,8 @@ public virtual string SetStoreType([CanBeNull] string storeType, ConfigurationSo /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetStoreTypeConfigurationSource() => _storeTypeConfigurationSource; + public virtual ConfigurationSource? GetStoreTypeConfigurationSource() + => _storeTypeConfigurationSource; /// [DebuggerStepThrough] @@ -159,7 +162,8 @@ public virtual RelationalTypeMapping TypeMapping /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual RelationalTypeMapping SetTypeMapping( - [NotNull] RelationalTypeMapping typeMapping, ConfigurationSource configurationSource) + [NotNull] RelationalTypeMapping typeMapping, + ConfigurationSource configurationSource) { _typeMapping = typeMapping; _typeMappingConfigurationSource = configurationSource.Max(_typeMappingConfigurationSource); @@ -204,7 +208,8 @@ public virtual bool SetPropagatesNullability(bool propagatesNullability, Configu /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetPropagatesNullabilityConfigurationSource() => _propagatesNullabilityConfigurationSource; + public virtual ConfigurationSource? GetPropagatesNullabilityConfigurationSource() + => _propagatesNullabilityConfigurationSource; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -212,7 +217,8 @@ public virtual bool SetPropagatesNullability(bool propagatesNullability, Configu /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetTypeMappingConfigurationSource() => _typeMappingConfigurationSource; + public virtual ConfigurationSource? GetTypeMappingConfigurationSource() + => _typeMappingConfigurationSource; /// [DebuggerStepThrough] @@ -228,6 +234,7 @@ RelationalTypeMapping IConventionDbFunctionParameter.SetTypeMapping(RelationalTy /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); } } diff --git a/src/EFCore.Relational/Metadata/Internal/ForeignKeyConstraint.cs b/src/EFCore.Relational/Metadata/Internal/ForeignKeyConstraint.cs index c3a30b24fdf..64709dfb89f 100644 --- a/src/EFCore.Relational/Metadata/Internal/ForeignKeyConstraint.cs +++ b/src/EFCore.Relational/Metadata/Internal/ForeignKeyConstraint.cs @@ -85,19 +85,24 @@ public ForeignKeyConstraint( public virtual ReferentialAction OnDeleteAction { get; set; } /// - IEnumerable IForeignKeyConstraint.MappedForeignKeys => MappedForeignKeys; + IEnumerable IForeignKeyConstraint.MappedForeignKeys + => MappedForeignKeys; /// - ITable IForeignKeyConstraint.Table => Table; + ITable IForeignKeyConstraint.Table + => Table; /// - ITable IForeignKeyConstraint.PrincipalTable => PrincipalTable; + ITable IForeignKeyConstraint.PrincipalTable + => PrincipalTable; /// - IReadOnlyList IForeignKeyConstraint.Columns => Columns; + IReadOnlyList IForeignKeyConstraint.Columns + => Columns; /// - IReadOnlyList IForeignKeyConstraint.PrincipalColumns => PrincipalColumns; + IReadOnlyList IForeignKeyConstraint.PrincipalColumns + => PrincipalColumns; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -105,6 +110,7 @@ public ForeignKeyConstraint( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); } } diff --git a/src/EFCore.Relational/Metadata/Internal/FunctionColumn.cs b/src/EFCore.Relational/Metadata/Internal/FunctionColumn.cs index ce3f94b78ac..49a5aa10740 100644 --- a/src/EFCore.Relational/Metadata/Internal/FunctionColumn.cs +++ b/src/EFCore.Relational/Metadata/Internal/FunctionColumn.cs @@ -28,8 +28,9 @@ public FunctionColumn([NotNull] string name, [NotNull] string type, [NotNull] St { } - /// - public virtual IStoreFunction Function => (IStoreFunction)Table; + /// + public virtual IStoreFunction Function + => (IStoreFunction)Table; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -37,9 +38,10 @@ public FunctionColumn([NotNull] string name, [NotNull] string type, [NotNull] St /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IEnumerable IFunctionColumn.PropertyMappings { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/FunctionColumnMapping.cs b/src/EFCore.Relational/Metadata/Internal/FunctionColumnMapping.cs index 0e74ea6f8e9..eedb18126dc 100644 --- a/src/EFCore.Relational/Metadata/Internal/FunctionColumnMapping.cs +++ b/src/EFCore.Relational/Metadata/Internal/FunctionColumnMapping.cs @@ -31,8 +31,9 @@ public FunctionColumnMapping( { } - /// - public virtual IFunctionMapping FunctionMapping => (IFunctionMapping)TableMapping; + /// + public virtual IFunctionMapping FunctionMapping + => (IFunctionMapping)TableMapping; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -40,7 +41,8 @@ public FunctionColumnMapping( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); IFunctionColumn IFunctionColumnMapping.Column { diff --git a/src/EFCore.Relational/Metadata/Internal/FunctionMapping.cs b/src/EFCore.Relational/Metadata/Internal/FunctionMapping.cs index c0bc8950483..35670ece875 100644 --- a/src/EFCore.Relational/Metadata/Internal/FunctionMapping.cs +++ b/src/EFCore.Relational/Metadata/Internal/FunctionMapping.cs @@ -33,13 +33,14 @@ public FunctionMapping( DbFunction = dbFunction; } - /// + /// public virtual bool IsDefaultFunctionMapping { get; set; } - /// - public virtual IStoreFunction StoreFunction => (IStoreFunction)base.Table; + /// + public virtual IStoreFunction StoreFunction + => (IStoreFunction)base.Table; - /// + /// public virtual IDbFunction DbFunction { get; } /// @@ -48,9 +49,10 @@ public FunctionMapping( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IEnumerable IFunctionMapping.ColumnMappings { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionBuilder.cs b/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionBuilder.cs index ad536d64bfc..ff0ea68aad5 100644 --- a/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionBuilder.cs +++ b/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionBuilder.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Diagnostics; using JetBrains.Annotations; -using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; @@ -177,7 +176,8 @@ public virtual bool CanSetStoreType([CanBeNull] string storeType, ConfigurationS /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual IConventionDbFunctionBuilder HasTypeMapping( - [CanBeNull] RelationalTypeMapping returnTypeMapping, ConfigurationSource configurationSource) + [CanBeNull] RelationalTypeMapping returnTypeMapping, + ConfigurationSource configurationSource) { if (CanSetTypeMapping(returnTypeMapping, configurationSource)) { @@ -205,7 +205,8 @@ public virtual bool CanSetTypeMapping([CanBeNull] RelationalTypeMapping returnTy /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual IConventionDbFunctionBuilder HasTranslation( - [CanBeNull] Func, SqlExpression> translation, ConfigurationSource configurationSource) + [CanBeNull] Func, SqlExpression> translation, + ConfigurationSource configurationSource) { if (CanSetTranslation(translation, configurationSource)) { @@ -223,7 +224,8 @@ public virtual IConventionDbFunctionBuilder HasTranslation( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual bool CanSetTranslation( - [CanBeNull] Func, SqlExpression> translation, ConfigurationSource configurationSource) + [CanBeNull] Func, SqlExpression> translation, + ConfigurationSource configurationSource) => (Metadata.IsScalar && !Metadata.IsAggregate || configurationSource == ConfigurationSource.Explicit) && (configurationSource.Overrides(Metadata.GetTranslationConfigurationSource()) || Metadata.Translation == translation); @@ -315,13 +317,15 @@ bool IConventionDbFunctionBuilder.CanSetTypeMapping(RelationalTypeMapping typeMa /// [DebuggerStepThrough] IConventionDbFunctionBuilder IConventionDbFunctionBuilder.HasTranslation( - Func, SqlExpression> translation, bool fromDataAnnotation) + Func, SqlExpression> translation, + bool fromDataAnnotation) => HasTranslation(translation, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// [DebuggerStepThrough] bool IConventionDbFunctionBuilder.CanSetTranslation( - Func, SqlExpression> translation, bool fromDataAnnotation) + Func, SqlExpression> translation, + bool fromDataAnnotation) => CanSetTranslation(translation, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// diff --git a/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionParameterBuilder.cs b/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionParameterBuilder.cs index 914cfc3b2cc..03f70ced2f9 100644 --- a/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionParameterBuilder.cs +++ b/src/EFCore.Relational/Metadata/Internal/InternalDbFunctionParameterBuilder.cs @@ -18,7 +18,8 @@ namespace Microsoft.EntityFrameworkCore.Metadata.Builders.Internal /// and it is not designed to be directly constructed in your application code. /// /// - public class InternalDbFunctionParameterBuilder : AnnotatableBuilder, IConventionDbFunctionParameterBuilder + public class InternalDbFunctionParameterBuilder : AnnotatableBuilder, + IConventionDbFunctionParameterBuilder { /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -39,7 +40,8 @@ public InternalDbFunctionParameterBuilder([NotNull] DbFunctionParameter paramete /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual IConventionDbFunctionParameterBuilder HasStoreType( - [CanBeNull] string storeType, ConfigurationSource configurationSource) + [CanBeNull] string storeType, + ConfigurationSource configurationSource) { if (CanSetStoreType(storeType, configurationSource)) { @@ -67,7 +69,8 @@ public virtual bool CanSetStoreType([CanBeNull] string storeType, ConfigurationS /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual IConventionDbFunctionParameterBuilder HasTypeMapping( - [CanBeNull] RelationalTypeMapping typeMapping, ConfigurationSource configurationSource) + [CanBeNull] RelationalTypeMapping typeMapping, + ConfigurationSource configurationSource) { if (CanSetTypeMapping(typeMapping, configurationSource)) { @@ -137,7 +140,8 @@ bool IConventionDbFunctionParameterBuilder.CanSetStoreType(string storeType, boo /// [DebuggerStepThrough] IConventionDbFunctionParameterBuilder IConventionDbFunctionParameterBuilder.HasTypeMapping( - RelationalTypeMapping typeMapping, bool fromDataAnnotation) + RelationalTypeMapping typeMapping, + bool fromDataAnnotation) => HasTypeMapping(typeMapping, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// diff --git a/src/EFCore.Relational/Metadata/Internal/InternalSequenceBuilder.cs b/src/EFCore.Relational/Metadata/Internal/InternalSequenceBuilder.cs index 5ad862ee134..92eeab8ebb7 100644 --- a/src/EFCore.Relational/Metadata/Internal/InternalSequenceBuilder.cs +++ b/src/EFCore.Relational/Metadata/Internal/InternalSequenceBuilder.cs @@ -65,7 +65,8 @@ public virtual bool CanSetType([CanBeNull] Type type, ConfigurationSource config /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual IConventionSequenceBuilder IncrementsBy( - int? increment, ConfigurationSource configurationSource) + int? increment, + ConfigurationSource configurationSource) { if (CanSetIncrementsBy(increment, configurationSource)) { diff --git a/src/EFCore.Relational/Metadata/Internal/NamedListComparer.cs b/src/EFCore.Relational/Metadata/Internal/NamedListComparer.cs index 3f44ef8797f..351c1bebe10 100644 --- a/src/EFCore.Relational/Metadata/Internal/NamedListComparer.cs +++ b/src/EFCore.Relational/Metadata/Internal/NamedListComparer.cs @@ -13,7 +13,8 @@ namespace Microsoft.EntityFrameworkCore.Metadata.Internal /// doing so can result in application failures when updating to a new Entity Framework Core release. /// // Sealed for perf - public sealed class NamedListComparer : IComparer<(string, string, IReadOnlyList)>, IEqualityComparer<(string, string, IReadOnlyList)> + public sealed class NamedListComparer : IComparer<(string, string, IReadOnlyList)>, + IEqualityComparer<(string, string, IReadOnlyList)> { /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to diff --git a/src/EFCore.Relational/Metadata/Internal/RelationalEntityTypeExtensions.cs b/src/EFCore.Relational/Metadata/Internal/RelationalEntityTypeExtensions.cs index 401d1550429..90cc9369f8e 100644 --- a/src/EFCore.Relational/Metadata/Internal/RelationalEntityTypeExtensions.cs +++ b/src/EFCore.Relational/Metadata/Internal/RelationalEntityTypeExtensions.cs @@ -29,9 +29,9 @@ public static class RelationalEntityTypeExtensions /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public static IEnumerable GetViewOrTableMappings([NotNull] this IEntityType entityType) => - (IEnumerable)(entityType[RelationalAnnotationNames.ViewMappings] - ?? entityType[RelationalAnnotationNames.TableMappings]) + public static IEnumerable GetViewOrTableMappings([NotNull] this IEntityType entityType) + => (IEnumerable)(entityType[RelationalAnnotationNames.ViewMappings] + ?? entityType[RelationalAnnotationNames.TableMappings]) ?? Enumerable.Empty(); /// diff --git a/src/EFCore.Relational/Metadata/Internal/RelationalForeignKeyExtensions.cs b/src/EFCore.Relational/Metadata/Internal/RelationalForeignKeyExtensions.cs index b5e55e7ba5d..bd9db75eaab 100644 --- a/src/EFCore.Relational/Metadata/Internal/RelationalForeignKeyExtensions.cs +++ b/src/EFCore.Relational/Metadata/Internal/RelationalForeignKeyExtensions.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -31,8 +30,8 @@ public static bool AreCompatible( bool shouldThrow) { var principalType = foreignKey.PrincipalKey.IsPrimaryKey() - ? foreignKey.PrincipalEntityType - : foreignKey.PrincipalKey.DeclaringEntityType; + ? foreignKey.PrincipalEntityType + : foreignKey.PrincipalKey.DeclaringEntityType; var principalTable = StoreObjectIdentifier.Create(principalType, StoreObjectType.Table); var duplicatePrincipalType = duplicateForeignKey.PrincipalKey.IsPrimaryKey() diff --git a/src/EFCore.Relational/Metadata/Internal/RelationalModel.cs b/src/EFCore.Relational/Metadata/Internal/RelationalModel.cs index ac81bb44798..f10f6119e58 100644 --- a/src/EFCore.Relational/Metadata/Internal/RelationalModel.cs +++ b/src/EFCore.Relational/Metadata/Internal/RelationalModel.cs @@ -31,7 +31,7 @@ public RelationalModel([NotNull] IModel model) Model = model; } - /// + /// public virtual IModel Model { get; } /// @@ -79,25 +79,25 @@ public RelationalModel([NotNull] IModel model) public virtual SortedDictionary<(string, string, IReadOnlyList), StoreFunction> Functions { get; } = new SortedDictionary<(string, string, IReadOnlyList), StoreFunction>(NamedListComparer.Instance); - /// + /// public virtual ITable FindTable(string name, string schema) => Tables.TryGetValue((name, schema), out var table) ? table : null; - /// + /// public virtual IView FindView(string name, string schema) => Views.TryGetValue((name, schema), out var view) ? view : null; - /// + /// public virtual ISqlQuery FindQuery(string name) => Queries.TryGetValue(name, out var query) ? query : null; - /// + /// public virtual IStoreFunction FindFunction(string name, string schema, IReadOnlyList parameters) => Functions.TryGetValue((name, schema, parameters), out var function) ? function @@ -110,7 +110,8 @@ public virtual IStoreFunction FindFunction(string name, string schema, IReadOnly /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public static IModel Add( - [NotNull] IConventionModel model, [CanBeNull] IRelationalAnnotationProvider relationalAnnotationProvider) + [NotNull] IConventionModel model, + [CanBeNull] IRelationalAnnotationProvider relationalAnnotationProvider) { if (model.FindAnnotation(RelationalAnnotationNames.RelationalModel) != null) { @@ -236,8 +237,7 @@ private static void AddDefaultMappings(RelationalModel databaseModel, IConventio var tableMapping = new TableMappingBase(entityType, defaultTable, includesDerivedTypes: true) { - IsSharedTablePrincipal = true, - IsSplitEntityTypePrincipal = true + IsSharedTablePrincipal = true, IsSplitEntityTypePrincipal = true }; foreach (var property in entityType.GetProperties()) @@ -322,7 +322,8 @@ private static void AddTables(RelationalModel databaseModel, IConventionEntityTy if (mappedType == entityType) { - Check.DebugAssert(table.EntityTypeMappings.Count == 0 + Check.DebugAssert( + table.EntityTypeMappings.Count == 0 || table.IsExcludedFromMigrations == entityType.IsTableExcludedFromMigrations(), "Table should be excluded on all entity types"); @@ -517,10 +518,7 @@ private static void AddSqlQueries(RelationalModel databaseModel, IConventionEnti var mappedQuery = StoreObjectIdentifier.SqlQuery(definingType); if (!databaseModel.Queries.TryGetValue(mappedQuery.Name, out var sqlQuery)) { - sqlQuery = new SqlQuery(mappedQuery.Name, databaseModel) - { - Sql = mappedTypeSqlQuery - }; + sqlQuery = new SqlQuery(mappedQuery.Name, databaseModel) { Sql = mappedTypeSqlQuery }; databaseModel.Queries.Add(mappedQuery.Name, sqlQuery); } @@ -701,7 +699,8 @@ private static FunctionMapping CreateFunctionMapping( column.IsNullable = false; } - var columnMapping = new FunctionColumnMapping(property, column, property.FindRelationalTypeMapping(mappedFunction), functionMapping); + var columnMapping = new FunctionColumnMapping( + property, column, property.FindRelationalTypeMapping(mappedFunction), functionMapping); functionMapping.ColumnMappings.Add(columnMapping); column.PropertyMappings.Add(columnMapping); @@ -769,14 +768,16 @@ private static void PopulateConstraints(Table table) } var principalTable = (Table)principalMapping.Table; - var name = foreignKey.GetConstraintName(storeObject, + var name = foreignKey.GetConstraintName( + storeObject, StoreObjectIdentifier.Table(principalTable.Name, principalTable.Schema)); if (name == null) { continue; } - var foreignKeyConstraints = foreignKey[RelationalAnnotationNames.ForeignKeyMappings] as SortedSet; + var foreignKeyConstraints = + foreignKey[RelationalAnnotationNames.ForeignKeyMappings] as SortedSet; if (table.ForeignKeyConstraints.TryGetValue(name, out var constraint)) { if (foreignKeyConstraints == null) @@ -829,7 +830,8 @@ private static void PopulateConstraints(Table table) break; } - constraint = new ForeignKeyConstraint(name, table, principalTable, columns, principalColumns, + constraint = new ForeignKeyConstraint( + name, table, principalTable, columns, principalColumns, ToReferentialAction(foreignKey.DeleteBehavior)); constraint.MappedForeignKeys.Add(foreignKey); @@ -969,6 +971,7 @@ private static void PopulateRowInternalForeignKeys(TableBase table) { rowInternalForeignKeys = new SortedSet(ForeignKeyComparer.Instance); } + rowInternalForeignKeys.Add(foreignKey); if (referencingInternalForeignKeyMap == null) @@ -983,6 +986,7 @@ private static void PopulateRowInternalForeignKeys(TableBase table) internalReferencingForeignKeys = new SortedSet(ForeignKeyComparer.Instance); referencingInternalForeignKeyMap[principalEntityType] = internalReferencingForeignKeys; } + ((SortedSet)internalReferencingForeignKeys).Add(foreignKey); } } @@ -1040,6 +1044,7 @@ private static void PopulateRowInternalForeignKeys(TableBase table) { continue; } + optionalTypes[entityType] = optional; if (referencingInternalForeignKeyMap.TryGetValue(entityType, out var referencingInternalForeignKeys)) diff --git a/src/EFCore.Relational/Metadata/Internal/RelationalPropertyOverrides.cs b/src/EFCore.Relational/Metadata/Internal/RelationalPropertyOverrides.cs index 31b19c813bc..171f2977062 100644 --- a/src/EFCore.Relational/Metadata/Internal/RelationalPropertyOverrides.cs +++ b/src/EFCore.Relational/Metadata/Internal/RelationalPropertyOverrides.cs @@ -52,7 +52,8 @@ public virtual string SetColumnName([CanBeNull] string columnName, Configuration /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual ConfigurationSource? GetColumnNameConfigurationSource() => _columnNameConfigurationSource; + public virtual ConfigurationSource? GetColumnNameConfigurationSource() + => _columnNameConfigurationSource; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -66,8 +67,8 @@ public static RelationalPropertyOverrides Find([NotNull] IProperty property, in property[RelationalAnnotationNames.RelationalOverrides]; return tableOverrides != null && tableOverrides.TryGetValue(storeObject, out var overrides) - ? overrides - : null; + ? overrides + : null; } /// @@ -77,7 +78,8 @@ public static RelationalPropertyOverrides Find([NotNull] IProperty property, in /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public static RelationalPropertyOverrides GetOrCreate( - [NotNull] IMutableProperty property, in StoreObjectIdentifier storeObject) + [NotNull] IMutableProperty property, + in StoreObjectIdentifier storeObject) { var tableOverrides = (SortedDictionary) property[RelationalAnnotationNames.RelationalOverrides]; @@ -103,7 +105,8 @@ public static RelationalPropertyOverrides GetOrCreate( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public static RelationalPropertyOverrides GetOrCreate( - [NotNull] IConventionProperty property, in StoreObjectIdentifier storeObject) + [NotNull] IConventionProperty property, + in StoreObjectIdentifier storeObject) => GetOrCreate((IMutableProperty)property, storeObject); } } diff --git a/src/EFCore.Relational/Metadata/Internal/Sequence.cs b/src/EFCore.Relational/Metadata/Internal/Sequence.cs index a381463bc91..c5e6a6db270 100644 --- a/src/EFCore.Relational/Metadata/Internal/Sequence.cs +++ b/src/EFCore.Relational/Metadata/Internal/Sequence.cs @@ -146,7 +146,8 @@ public Sequence([NotNull] IModel model, [NotNull] string annotationName) /// public static IEnumerable GetSequences([NotNull] IModel model) => ((SortedDictionary<(string, string), Sequence>)model[RelationalAnnotationNames.Sequences]) - ?.Values ?? Enumerable.Empty(); + ?.Values + ?? Enumerable.Empty(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -173,7 +174,10 @@ public static Sequence FindSequence([NotNull] IModel model, [NotNull] string nam /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public static Sequence AddSequence( - [NotNull] IMutableModel model, [NotNull] string name, [CanBeNull] string schema, ConfigurationSource configurationSource) + [NotNull] IMutableModel model, + [NotNull] string name, + [CanBeNull] string schema, + ConfigurationSource configurationSource) { var sequence = new Sequence(name, schema, model, configurationSource); var sequences = (SortedDictionary<(string, string), Sequence>)model[RelationalAnnotationNames.Sequences]; @@ -194,7 +198,9 @@ public static Sequence AddSequence( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public static Sequence SetName( - [NotNull] IMutableModel model, [NotNull] Sequence sequence, [NotNull] string name) + [NotNull] IMutableModel model, + [NotNull] Sequence sequence, + [NotNull] string name) { Check.NotNull(model, nameof(model)); Check.NotNull(sequence, nameof(sequence)); @@ -252,7 +258,8 @@ public static Sequence RemoveSequence([NotNull] IMutableModel model, [NotNull] s /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual IModel Model => _model; + public virtual IModel Model + => _model; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -268,7 +275,8 @@ public static Sequence RemoveSequence([NotNull] IMutableModel model, [NotNull] s /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual string Schema => _schema ?? Model.GetDefaultSchema(); + public virtual string Schema + => _schema ?? Model.GetDefaultSchema(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -570,7 +578,8 @@ public virtual bool IsCyclic /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -578,7 +587,8 @@ public virtual bool IsCyclic /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - IConventionSequenceBuilder IConventionSequence.Builder => Builder; + IConventionSequenceBuilder IConventionSequence.Builder + => Builder; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -586,7 +596,8 @@ public virtual bool IsCyclic /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - IMutableModel IMutableSequence.Model => (IMutableModel)Model; + IMutableModel IMutableSequence.Model + => (IMutableModel)Model; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -594,7 +605,8 @@ public virtual bool IsCyclic /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - IConventionModel IConventionSequence.Model => (IConventionModel)Model; + IConventionModel IConventionSequence.Model + => (IConventionModel)Model; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to diff --git a/src/EFCore.Relational/Metadata/Internal/SqlQuery.cs b/src/EFCore.Relational/Metadata/Internal/SqlQuery.cs index cdd78dc94f3..ecc71654d32 100644 --- a/src/EFCore.Relational/Metadata/Internal/SqlQuery.cs +++ b/src/EFCore.Relational/Metadata/Internal/SqlQuery.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -29,10 +28,10 @@ public SqlQuery([NotNull] string name, [NotNull] RelationalModel model) { } - /// + /// public virtual string Sql { get; [param: NotNull] set; } - /// + /// public override IColumnBase FindColumn(IProperty property) => property.GetSqlQueryColumnMappings() .FirstOrDefault(cm => cm.TableMapping.Table == this) @@ -44,28 +43,29 @@ public override IColumnBase FindColumn(IProperty property) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IEnumerable ISqlQuery.EntityTypeMappings { [DebuggerStepThrough] get => EntityTypeMappings.Cast(); } - /// + /// IEnumerable ISqlQuery.Columns { [DebuggerStepThrough] get => Columns.Values.Cast(); } - /// + /// [DebuggerStepThrough] ISqlQueryColumn ISqlQuery.FindColumn(string name) => (ISqlQueryColumn)base.FindColumn(name); - /// + /// [DebuggerStepThrough] ISqlQueryColumn ISqlQuery.FindColumn(IProperty property) => (ISqlQueryColumn)FindColumn(property); diff --git a/src/EFCore.Relational/Metadata/Internal/SqlQueryColumn.cs b/src/EFCore.Relational/Metadata/Internal/SqlQueryColumn.cs index 2ae65f66441..d54fb397b21 100644 --- a/src/EFCore.Relational/Metadata/Internal/SqlQueryColumn.cs +++ b/src/EFCore.Relational/Metadata/Internal/SqlQueryColumn.cs @@ -28,8 +28,9 @@ public SqlQueryColumn([NotNull] string name, [NotNull] string type, [NotNull] Sq { } - /// - public virtual ISqlQuery SqlQuery => (ISqlQuery)Table; + /// + public virtual ISqlQuery SqlQuery + => (ISqlQuery)Table; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -37,9 +38,10 @@ public SqlQueryColumn([NotNull] string name, [NotNull] string type, [NotNull] Sq /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IEnumerable ISqlQueryColumn.PropertyMappings { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/SqlQueryColumnMapping.cs b/src/EFCore.Relational/Metadata/Internal/SqlQueryColumnMapping.cs index 36b12a66efe..7a84d3d937e 100644 --- a/src/EFCore.Relational/Metadata/Internal/SqlQueryColumnMapping.cs +++ b/src/EFCore.Relational/Metadata/Internal/SqlQueryColumnMapping.cs @@ -31,8 +31,9 @@ public SqlQueryColumnMapping( { } - /// - public virtual ISqlQueryMapping SqlQueryMapping => (ISqlQueryMapping)TableMapping; + /// + public virtual ISqlQueryMapping SqlQueryMapping + => (ISqlQueryMapping)TableMapping; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -40,9 +41,10 @@ public SqlQueryColumnMapping( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// ISqlQueryColumn ISqlQueryColumnMapping.Column { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/SqlQueryMapping.cs b/src/EFCore.Relational/Metadata/Internal/SqlQueryMapping.cs index df8c528e860..a2b3107d5c8 100644 --- a/src/EFCore.Relational/Metadata/Internal/SqlQueryMapping.cs +++ b/src/EFCore.Relational/Metadata/Internal/SqlQueryMapping.cs @@ -31,11 +31,12 @@ public SqlQueryMapping( { } - /// + /// public virtual bool IsDefaultSqlQueryMapping { get; set; } - /// - public virtual ISqlQuery SqlQuery => (ISqlQuery)base.Table; + /// + public virtual ISqlQuery SqlQuery + => (ISqlQuery)base.Table; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -43,9 +44,10 @@ public SqlQueryMapping( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IEnumerable ISqlQueryMapping.ColumnMappings { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/StoreFunction.cs b/src/EFCore.Relational/Metadata/Internal/StoreFunction.cs index e905df86fd4..97f5e43f41a 100644 --- a/src/EFCore.Relational/Metadata/Internal/StoreFunction.cs +++ b/src/EFCore.Relational/Metadata/Internal/StoreFunction.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -27,7 +26,7 @@ public class StoreFunction : TableBase, IStoreFunction public StoreFunction([NotNull] DbFunction dbFunction, [NotNull] RelationalModel model) : base(dbFunction.Name, dbFunction.Schema, model) { - DbFunctions = new SortedDictionary() { { dbFunction.ModelName, dbFunction } }; + DbFunctions = new SortedDictionary { { dbFunction.ModelName, dbFunction } }; IsBuiltIn = dbFunction.IsBuiltIn; ReturnType = dbFunction.StoreType; @@ -36,6 +35,7 @@ public StoreFunction([NotNull] DbFunction dbFunction, [NotNull] RelationalModel { Parameters[i] = new StoreFunctionParameter(this, dbFunction.Parameters[i]); } + dbFunction.StoreFunction = this; } @@ -61,7 +61,7 @@ public StoreFunction([NotNull] DbFunction dbFunction, [NotNull] RelationalModel /// public virtual StoreFunctionParameter[] Parameters { get; } - /// + /// public override IColumnBase FindColumn(IProperty property) => property.GetFunctionColumnMappings() .FirstOrDefault(cm => cm.TableMapping.Table == this) @@ -73,7 +73,8 @@ public override IColumnBase FindColumn(IProperty property) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); /// IEnumerable IStoreFunction.EntityTypeMappings @@ -103,12 +104,12 @@ IEnumerable IStoreFunction.DbFunctions get => DbFunctions.Values; } - /// + /// [DebuggerStepThrough] IFunctionColumn IStoreFunction.FindColumn(string name) => (IFunctionColumn)base.FindColumn(name); - /// + /// [DebuggerStepThrough] IFunctionColumn IStoreFunction.FindColumn(IProperty property) => (IFunctionColumn)FindColumn(property); diff --git a/src/EFCore.Relational/Metadata/Internal/StoreFunctionParameter.cs b/src/EFCore.Relational/Metadata/Internal/StoreFunctionParameter.cs index 54a80d072cf..ac1c74b394a 100644 --- a/src/EFCore.Relational/Metadata/Internal/StoreFunctionParameter.cs +++ b/src/EFCore.Relational/Metadata/Internal/StoreFunctionParameter.cs @@ -56,7 +56,8 @@ public StoreFunctionParameter( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); IEnumerable IStoreFunctionParameter.DbFunctionParameters { diff --git a/src/EFCore.Relational/Metadata/Internal/Table.cs b/src/EFCore.Relational/Metadata/Internal/Table.cs index bde9005dde8..cf3f0634077 100644 --- a/src/EFCore.Relational/Metadata/Internal/Table.cs +++ b/src/EFCore.Relational/Metadata/Internal/Table.cs @@ -48,7 +48,8 @@ public Table([NotNull] string name, [CanBeNull] string schema, [NotNull] Relatio /// public virtual UniqueConstraint PrimaryKey { - get => _primaryKey; [param: NotNull] + get => _primaryKey; + [param: NotNull] set { var oldPrimaryKey = _primaryKey; @@ -119,10 +120,10 @@ public virtual UniqueConstraint FindUniqueConstraint([NotNull] string name) public virtual SortedDictionary Indexes { get; } = new SortedDictionary(); - /// + /// public virtual bool IsExcludedFromMigrations { get; set; } - /// + /// public override IColumnBase FindColumn(IProperty property) => property.GetTableColumnMappings() .FirstOrDefault(cm => cm.TableMapping.Table == this) @@ -134,56 +135,57 @@ public override IColumnBase FindColumn(IProperty property) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IEnumerable ITable.EntityTypeMappings { [DebuggerStepThrough] get => base.EntityTypeMappings.Cast(); } - /// + /// IEnumerable ITable.Columns { [DebuggerStepThrough] get => base.Columns.Values.Cast(); } - /// + /// IEnumerable ITable.ForeignKeyConstraints { [DebuggerStepThrough] get => ForeignKeyConstraints.Values; } - /// + /// IPrimaryKeyConstraint ITable.PrimaryKey { [DebuggerStepThrough] get => PrimaryKey; } - /// + /// IEnumerable ITable.UniqueConstraints { [DebuggerStepThrough] get => UniqueConstraints.Values; } - /// + /// IEnumerable ITable.Indexes { [DebuggerStepThrough] get => Indexes.Values; } - /// + /// [DebuggerStepThrough] IColumn ITable.FindColumn(string name) => (IColumn)base.FindColumn(name); - /// + /// [DebuggerStepThrough] IColumn ITable.FindColumn(IProperty property) => (IColumn)FindColumn(property); diff --git a/src/EFCore.Relational/Metadata/Internal/TableBase.cs b/src/EFCore.Relational/Metadata/Internal/TableBase.cs index 6ad0dffb774..7f865d21740 100644 --- a/src/EFCore.Relational/Metadata/Internal/TableBase.cs +++ b/src/EFCore.Relational/Metadata/Internal/TableBase.cs @@ -31,10 +31,10 @@ public TableBase([NotNull] string name, [CanBeNull] string schema, [NotNull] Rel Model = model; } - /// + /// public virtual string Schema { get; } - /// + /// public virtual string Name { get; } /// @@ -45,7 +45,7 @@ public TableBase([NotNull] string name, [CanBeNull] string schema, [NotNull] Rel /// public virtual RelationalModel Model { get; } - /// + /// public virtual bool IsShared { get; set; } /// @@ -66,13 +66,13 @@ public TableBase([NotNull] string name, [CanBeNull] string schema, [NotNull] Rel public virtual SortedDictionary Columns { get; [param: NotNull] protected set; } = new SortedDictionary(StringComparer.Ordinal); - /// + /// public virtual IColumnBase FindColumn(string name) => Columns.TryGetValue(name, out var column) ? column : null; - /// + /// public virtual IColumnBase FindColumn(IProperty property) => property.GetDefaultColumnMappings() .FirstOrDefault(cm => cm.TableMapping.Table == this) @@ -92,7 +92,11 @@ public virtual IColumnBase FindColumn(IProperty property) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual SortedDictionary> ReferencingRowInternalForeignKeys { get; [param: NotNull] set; } + public virtual SortedDictionary> ReferencingRowInternalForeignKeys + { + get; + [param: NotNull] set; + } /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -102,44 +106,47 @@ public virtual IColumnBase FindColumn(IProperty property) /// public virtual Dictionary OptionalEntityTypes { get; [param: NotNull] set; } - /// + /// public virtual bool IsOptional(IEntityType entityType) => OptionalEntityTypes == null - ? GetMappedEntityType(entityType) == null - : !OptionalEntityTypes.TryGetValue(entityType, out var optional) - ? throw new InvalidOperationException(RelationalStrings.TableNotMappedEntityType(entityType.DisplayName(), Name)) - : optional; + ? GetMappedEntityType(entityType) == null + : !OptionalEntityTypes.TryGetValue(entityType, out var optional) + ? throw new InvalidOperationException(RelationalStrings.TableNotMappedEntityType(entityType.DisplayName(), Name)) + : optional; private IEntityType GetMappedEntityType(IEntityType entityType) => EntityTypeMappings.Any(m => m.EntityType == entityType) ? entityType : throw new InvalidOperationException(RelationalStrings.TableNotMappedEntityType(entityType.DisplayName(), Name)); - /// - IRelationalModel ITableBase.Model => Model; + /// + IRelationalModel ITableBase.Model + => Model; - /// - IEnumerable ITableBase.EntityTypeMappings => EntityTypeMappings; + /// + IEnumerable ITableBase.EntityTypeMappings + => EntityTypeMappings; - /// - IEnumerable ITableBase.Columns => Columns.Values; + /// + IEnumerable ITableBase.Columns + => Columns.Values; - /// + /// IEnumerable ITableBase.GetRowInternalForeignKeys(IEntityType entityType) => RowInternalForeignKeys != null && RowInternalForeignKeys.TryGetValue(entityType, out var foreignKeys) - ? foreignKeys - : (GetMappedEntityType(entityType) == null) - ? null - : Enumerable.Empty(); + ? foreignKeys + : (GetMappedEntityType(entityType) == null) + ? null + : Enumerable.Empty(); - /// + /// IEnumerable ITableBase.GetReferencingRowInternalForeignKeys(IEntityType entityType) => ReferencingRowInternalForeignKeys != null && ReferencingRowInternalForeignKeys.TryGetValue(entityType, out var foreignKeys) - ? foreignKeys - : (GetMappedEntityType(entityType) == null) - ? null - : Enumerable.Empty(); + ? foreignKeys + : (GetMappedEntityType(entityType) == null) + ? null + : Enumerable.Empty(); } } diff --git a/src/EFCore.Relational/Metadata/Internal/TableIndex.cs b/src/EFCore.Relational/Metadata/Internal/TableIndex.cs index 33e55a84055..b58ec1de38f 100644 --- a/src/EFCore.Relational/Metadata/Internal/TableIndex.cs +++ b/src/EFCore.Relational/Metadata/Internal/TableIndex.cs @@ -69,13 +69,16 @@ public TableIndex( public virtual string Filter { get; } /// - ITable ITableIndex.Table => Table; + ITable ITableIndex.Table + => Table; /// - IReadOnlyList ITableIndex.Columns => Columns; + IReadOnlyList ITableIndex.Columns + => Columns; /// - IEnumerable ITableIndex.MappedIndexes => MappedIndexes; + IEnumerable ITableIndex.MappedIndexes + => MappedIndexes; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -83,6 +86,7 @@ public TableIndex( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); } } diff --git a/src/EFCore.Relational/Metadata/Internal/TableMapping.cs b/src/EFCore.Relational/Metadata/Internal/TableMapping.cs index a20360fedda..60ba5327263 100644 --- a/src/EFCore.Relational/Metadata/Internal/TableMapping.cs +++ b/src/EFCore.Relational/Metadata/Internal/TableMapping.cs @@ -31,8 +31,9 @@ public TableMapping( { } - /// - public new virtual ITable Table => (ITable)base.Table; + /// + public new virtual ITable Table + => (ITable)base.Table; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -40,16 +41,17 @@ public TableMapping( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// ITableBase ITableMappingBase.Table { [DebuggerStepThrough] get => Table; } - /// + /// IEnumerable ITableMapping.ColumnMappings { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/TableMappingBase.cs b/src/EFCore.Relational/Metadata/Internal/TableMappingBase.cs index b440ac9874d..31bc4ae9412 100644 --- a/src/EFCore.Relational/Metadata/Internal/TableMappingBase.cs +++ b/src/EFCore.Relational/Metadata/Internal/TableMappingBase.cs @@ -32,10 +32,10 @@ public TableMappingBase( IncludesDerivedTypes = includesDerivedTypes; } - /// + /// public virtual IEntityType EntityType { get; } - /// + /// public virtual ITableBase Table { get; } /// @@ -47,13 +47,13 @@ public TableMappingBase( public virtual SortedSet ColumnMappings { get; } = new SortedSet(ColumnMappingBaseComparer.Instance); - /// + /// public virtual bool IncludesDerivedTypes { get; } - /// + /// public virtual bool IsSharedTablePrincipal { get; set; } - /// + /// public virtual bool IsSplitEntityTypePrincipal { get; set; } IEnumerable ITableMappingBase.ColumnMappings diff --git a/src/EFCore.Relational/Metadata/Internal/TableMappingBaseComparer.cs b/src/EFCore.Relational/Metadata/Internal/TableMappingBaseComparer.cs index 23bc174a8d2..f5c56acc36b 100644 --- a/src/EFCore.Relational/Metadata/Internal/TableMappingBaseComparer.cs +++ b/src/EFCore.Relational/Metadata/Internal/TableMappingBaseComparer.cs @@ -78,11 +78,12 @@ public int Compare(ITableMappingBase x, ITableMappingBase y) return result; } - return x.ColumnMappings.Zip(y.ColumnMappings, (xc, yc) => - { - var columnResult = StringComparer.Ordinal.Compare(xc.Property.Name, yc.Property.Name); - return columnResult != 0 ? columnResult : StringComparer.Ordinal.Compare(xc.Column.Name, yc.Column.Name); - }) + return x.ColumnMappings.Zip( + y.ColumnMappings, (xc, yc) => + { + var columnResult = StringComparer.Ordinal.Compare(xc.Property.Name, yc.Property.Name); + return columnResult != 0 ? columnResult : StringComparer.Ordinal.Compare(xc.Column.Name, yc.Column.Name); + }) .FirstOrDefault(r => r != 0); } @@ -115,6 +116,7 @@ public int GetHashCode(ITableMappingBase obj) hashCode.Add(columnMapping.Property.Name); hashCode.Add(columnMapping.Column.Name); } + hashCode.Add(obj.IncludesDerivedTypes); return hashCode.ToHashCode(); } diff --git a/src/EFCore.Relational/Metadata/Internal/UniqueConstraint.cs b/src/EFCore.Relational/Metadata/Internal/UniqueConstraint.cs index ca657b00b54..fb25f3f83ff 100644 --- a/src/EFCore.Relational/Metadata/Internal/UniqueConstraint.cs +++ b/src/EFCore.Relational/Metadata/Internal/UniqueConstraint.cs @@ -59,13 +59,16 @@ public UniqueConstraint( public virtual IReadOnlyList Columns { get; } /// - ITable IUniqueConstraint.Table => Table; + ITable IUniqueConstraint.Table + => Table; /// - IReadOnlyList IUniqueConstraint.Columns => Columns; + IReadOnlyList IUniqueConstraint.Columns + => Columns; /// - IEnumerable IUniqueConstraint.MappedKeys => MappedKeys; + IEnumerable IUniqueConstraint.MappedKeys + => MappedKeys; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -73,6 +76,7 @@ public UniqueConstraint( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); } } diff --git a/src/EFCore.Relational/Metadata/Internal/View.cs b/src/EFCore.Relational/Metadata/Internal/View.cs index ddae4c3fc5e..5d9c96d2ef2 100644 --- a/src/EFCore.Relational/Metadata/Internal/View.cs +++ b/src/EFCore.Relational/Metadata/Internal/View.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -29,11 +28,12 @@ public View([NotNull] string name, [CanBeNull] string schema, [NotNull] Relation { } - /// + /// public virtual string ViewDefinitionSql - => (string)EntityTypeMappings.Select(m => m.EntityType[RelationalAnnotationNames.ViewDefinitionSql]).FirstOrDefault(d => d != null); + => (string)EntityTypeMappings.Select(m => m.EntityType[RelationalAnnotationNames.ViewDefinitionSql]) + .FirstOrDefault(d => d != null); - /// + /// public override IColumnBase FindColumn(IProperty property) => property.GetViewColumnMappings() .FirstOrDefault(cm => cm.TableMapping.Table == this) @@ -45,28 +45,29 @@ public override IColumnBase FindColumn(IProperty property) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IEnumerable IView.EntityTypeMappings { [DebuggerStepThrough] get => EntityTypeMappings.Cast(); } - /// + /// IEnumerable IView.Columns { [DebuggerStepThrough] get => Columns.Values.Cast(); } - /// + /// [DebuggerStepThrough] IViewColumn IView.FindColumn(string name) => (IViewColumn)base.FindColumn(name); - /// + /// [DebuggerStepThrough] IViewColumn IView.FindColumn(IProperty property) => (IViewColumn)FindColumn(property); diff --git a/src/EFCore.Relational/Metadata/Internal/ViewColumn.cs b/src/EFCore.Relational/Metadata/Internal/ViewColumn.cs index 64c3103d727..16af9e670f1 100644 --- a/src/EFCore.Relational/Metadata/Internal/ViewColumn.cs +++ b/src/EFCore.Relational/Metadata/Internal/ViewColumn.cs @@ -28,8 +28,9 @@ public ViewColumn([NotNull] string name, [NotNull] string type, [NotNull] View v { } - /// - public virtual IView View => (IView)Table; + /// + public virtual IView View + => (IView)Table; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -37,9 +38,10 @@ public ViewColumn([NotNull] string name, [NotNull] string type, [NotNull] View v /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IEnumerable IViewColumn.PropertyMappings { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/ViewColumnMapping.cs b/src/EFCore.Relational/Metadata/Internal/ViewColumnMapping.cs index 69c5c8e1cf8..e43ba46b24c 100644 --- a/src/EFCore.Relational/Metadata/Internal/ViewColumnMapping.cs +++ b/src/EFCore.Relational/Metadata/Internal/ViewColumnMapping.cs @@ -31,8 +31,9 @@ public ViewColumnMapping( { } - /// - public virtual IViewMapping ViewMapping => (IViewMapping)TableMapping; + /// + public virtual IViewMapping ViewMapping + => (IViewMapping)TableMapping; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -40,9 +41,10 @@ public ViewColumnMapping( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IViewColumn IViewColumnMapping.Column { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/Internal/ViewMapping.cs b/src/EFCore.Relational/Metadata/Internal/ViewMapping.cs index dc80725a543..0454158bb64 100644 --- a/src/EFCore.Relational/Metadata/Internal/ViewMapping.cs +++ b/src/EFCore.Relational/Metadata/Internal/ViewMapping.cs @@ -31,8 +31,9 @@ public ViewMapping( { } - /// - public virtual IView View => (IView)base.Table; + /// + public virtual IView View + => (IView)base.Table; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -40,9 +41,10 @@ public ViewMapping( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string ToString() => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); + public override string ToString() + => this.ToDebugString(MetadataDebugStringOptions.SingleLineDefault); - /// + /// IEnumerable IViewMapping.ColumnMappings { [DebuggerStepThrough] diff --git a/src/EFCore.Relational/Metadata/RelationalAnnotationProvider.cs b/src/EFCore.Relational/Metadata/RelationalAnnotationProvider.cs index e7b46520904..d651788bf35 100644 --- a/src/EFCore.Relational/Metadata/RelationalAnnotationProvider.cs +++ b/src/EFCore.Relational/Metadata/RelationalAnnotationProvider.cs @@ -33,45 +33,59 @@ public RelationalAnnotationProvider([NotNull] RelationalAnnotationProviderDepend } /// - public virtual IEnumerable For(IRelationalModel model) => Enumerable.Empty(); + public virtual IEnumerable For(IRelationalModel model) + => Enumerable.Empty(); /// - public virtual IEnumerable For(ITable table) => Enumerable.Empty(); + public virtual IEnumerable For(ITable table) + => Enumerable.Empty(); /// - public virtual IEnumerable For(IColumn column) => Enumerable.Empty(); + public virtual IEnumerable For(IColumn column) + => Enumerable.Empty(); /// - public virtual IEnumerable For(IView view) => Enumerable.Empty(); + public virtual IEnumerable For(IView view) + => Enumerable.Empty(); /// - public virtual IEnumerable For(IViewColumn column) => Enumerable.Empty(); + public virtual IEnumerable For(IViewColumn column) + => Enumerable.Empty(); /// - public virtual IEnumerable For(ISqlQuery sqlQuery) => Enumerable.Empty(); + public virtual IEnumerable For(ISqlQuery sqlQuery) + => Enumerable.Empty(); /// - public virtual IEnumerable For(ISqlQueryColumn column) => Enumerable.Empty(); + public virtual IEnumerable For(ISqlQueryColumn column) + => Enumerable.Empty(); /// - public virtual IEnumerable For(IStoreFunction function) => Enumerable.Empty(); + public virtual IEnumerable For(IStoreFunction function) + => Enumerable.Empty(); /// - public virtual IEnumerable For(IFunctionColumn column) => Enumerable.Empty(); + public virtual IEnumerable For(IFunctionColumn column) + => Enumerable.Empty(); /// - public virtual IEnumerable For(IForeignKeyConstraint foreignKey) => Enumerable.Empty(); + public virtual IEnumerable For(IForeignKeyConstraint foreignKey) + => Enumerable.Empty(); /// - public virtual IEnumerable For(ITableIndex index) => Enumerable.Empty(); + public virtual IEnumerable For(ITableIndex index) + => Enumerable.Empty(); /// - public virtual IEnumerable For(IUniqueConstraint constraint) => Enumerable.Empty(); + public virtual IEnumerable For(IUniqueConstraint constraint) + => Enumerable.Empty(); /// - public virtual IEnumerable For(ISequence sequence) => Enumerable.Empty(); + public virtual IEnumerable For(ISequence sequence) + => Enumerable.Empty(); /// - public virtual IEnumerable For(ICheckConstraint checkConstraint) => Enumerable.Empty(); + public virtual IEnumerable For(ICheckConstraint checkConstraint) + => Enumerable.Empty(); } } diff --git a/src/EFCore.Relational/Metadata/SqlQueryColumnExtensions.cs b/src/EFCore.Relational/Metadata/SqlQueryColumnExtensions.cs index aa2dbb63f11..12bbf7d1c8d 100644 --- a/src/EFCore.Relational/Metadata/SqlQueryColumnExtensions.cs +++ b/src/EFCore.Relational/Metadata/SqlQueryColumnExtensions.cs @@ -56,8 +56,7 @@ public static string ToDebugString( builder.Append(")"); - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(column.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/SqlQueryColumnMappingExtensions.cs b/src/EFCore.Relational/Metadata/SqlQueryColumnMappingExtensions.cs index 08765e0776b..f320d06a632 100644 --- a/src/EFCore.Relational/Metadata/SqlQueryColumnMappingExtensions.cs +++ b/src/EFCore.Relational/Metadata/SqlQueryColumnMappingExtensions.cs @@ -38,15 +38,14 @@ public static string ToDebugString( var singleLine = (options & MetadataDebugStringOptions.SingleLine) != 0; if (singleLine) { - builder.Append($"SqlQueryColumnMapping: "); + builder.Append("SqlQueryColumnMapping: "); } builder.Append(columnMapping.Property.Name).Append(" - "); builder.Append(columnMapping.Column.Name); - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(columnMapping.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/SqlQueryMappingExtensions.cs b/src/EFCore.Relational/Metadata/SqlQueryMappingExtensions.cs index 04c48656892..dbdcd3d04ba 100644 --- a/src/EFCore.Relational/Metadata/SqlQueryMappingExtensions.cs +++ b/src/EFCore.Relational/Metadata/SqlQueryMappingExtensions.cs @@ -38,7 +38,7 @@ public static string ToDebugString( var singleLine = (options & MetadataDebugStringOptions.SingleLine) != 0; if (singleLine) { - builder.Append($"SqlQueryMapping: "); + builder.Append("SqlQueryMapping: "); } builder.Append(sqlQueryMapping.EntityType.Name).Append(" - "); @@ -47,11 +47,10 @@ public static string ToDebugString( if (sqlQueryMapping.IncludesDerivedTypes) { - builder.Append($" IncludesDerivedTypes"); + builder.Append(" IncludesDerivedTypes"); } - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(sqlQueryMapping.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/StoreObjectIdentifier.cs b/src/EFCore.Relational/Metadata/StoreObjectIdentifier.cs index ca4cc93d01f..fab8fe1ecfc 100644 --- a/src/EFCore.Relational/Metadata/StoreObjectIdentifier.cs +++ b/src/EFCore.Relational/Metadata/StoreObjectIdentifier.cs @@ -146,10 +146,12 @@ public int CompareTo(StoreObjectIdentifier other) /// /// Gets the friendly display name for the store object. /// - public string DisplayName() => Schema == null ? Name : Schema + "." + Name; + public string DisplayName() + => Schema == null ? Name : Schema + "." + Name; /// - public override string ToString() => StoreObjectType.ToString() + " " + DisplayName(); + public override string ToString() + => StoreObjectType + " " + DisplayName(); /// public override bool Equals(object obj) @@ -157,9 +159,7 @@ public override bool Equals(object obj) /// public bool Equals(StoreObjectIdentifier other) - => StoreObjectType == other.StoreObjectType && - Name == other.Name && - Schema == other.Schema; + => StoreObjectType == other.StoreObjectType && Name == other.Name && Schema == other.Schema; /// public override int GetHashCode() @@ -170,7 +170,7 @@ public override int GetHashCode() /// /// The first id. /// The second id. - /// if they represent the same store object; otherwise. + /// if they represent the same store object; otherwise. public static bool operator ==(StoreObjectIdentifier left, StoreObjectIdentifier right) => left.Equals(right); @@ -179,7 +179,7 @@ public override int GetHashCode() /// /// The first id. /// The second id. - /// if they represent the same store object; otherwise. + /// if they represent the same store object; otherwise. public static bool operator !=(StoreObjectIdentifier left, StoreObjectIdentifier right) => !(left == right); } diff --git a/src/EFCore.Relational/Metadata/TableIndexExtensions.cs b/src/EFCore.Relational/Metadata/TableIndexExtensions.cs index a95eeae1678..7fefd245dbf 100644 --- a/src/EFCore.Relational/Metadata/TableIndexExtensions.cs +++ b/src/EFCore.Relational/Metadata/TableIndexExtensions.cs @@ -58,8 +58,7 @@ public static string ToDebugString( .Append(" Filtered"); } - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(index.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/TableMappingExtensions.cs b/src/EFCore.Relational/Metadata/TableMappingExtensions.cs index 01b12ea36fb..f71c48ec74c 100644 --- a/src/EFCore.Relational/Metadata/TableMappingExtensions.cs +++ b/src/EFCore.Relational/Metadata/TableMappingExtensions.cs @@ -38,7 +38,7 @@ public static string ToDebugString( var singleLine = (options & MetadataDebugStringOptions.SingleLine) != 0; if (singleLine) { - builder.Append($"TableMapping: "); + builder.Append("TableMapping: "); } builder.Append(tableMapping.EntityType.Name).Append(" - "); @@ -47,11 +47,10 @@ public static string ToDebugString( if (tableMapping.IncludesDerivedTypes) { - builder.Append($" IncludesDerivedTypes"); + builder.Append(" IncludesDerivedTypes"); } - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(tableMapping.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/UniqueConstraintExtensions.cs b/src/EFCore.Relational/Metadata/UniqueConstraintExtensions.cs index eba53370902..c08a4819b15 100644 --- a/src/EFCore.Relational/Metadata/UniqueConstraintExtensions.cs +++ b/src/EFCore.Relational/Metadata/UniqueConstraintExtensions.cs @@ -17,7 +17,7 @@ public static class UniqueConstraintExtensions /// Gets a value indicating whether this constraint is the primary key. /// /// The metadata item. - /// if the constraint is the primary key + /// if the constraint is the primary key public static bool GetIsPrimaryKey([NotNull] this IUniqueConstraint uniqueConstraint) => uniqueConstraint.Table.PrimaryKey == uniqueConstraint; @@ -59,8 +59,7 @@ public static string ToDebugString( builder.Append(" PrimaryKey"); } - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(uniqueConstraint.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/ViewColumnExtensions.cs b/src/EFCore.Relational/Metadata/ViewColumnExtensions.cs index 9a902af7bd4..dd3b5a507c6 100644 --- a/src/EFCore.Relational/Metadata/ViewColumnExtensions.cs +++ b/src/EFCore.Relational/Metadata/ViewColumnExtensions.cs @@ -56,8 +56,7 @@ public static string ToDebugString( builder.Append(")"); - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(column.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/ViewColumnMappingExtensions.cs b/src/EFCore.Relational/Metadata/ViewColumnMappingExtensions.cs index 2d821df1f18..388f83530c5 100644 --- a/src/EFCore.Relational/Metadata/ViewColumnMappingExtensions.cs +++ b/src/EFCore.Relational/Metadata/ViewColumnMappingExtensions.cs @@ -38,15 +38,14 @@ public static string ToDebugString( var singleLine = (options & MetadataDebugStringOptions.SingleLine) != 0; if (singleLine) { - builder.Append($"ViewColumnMapping: "); + builder.Append("ViewColumnMapping: "); } builder.Append(columnMapping.Property.Name).Append(" - "); builder.Append(columnMapping.Column.Name); - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(columnMapping.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Metadata/ViewMappingExtensions.cs b/src/EFCore.Relational/Metadata/ViewMappingExtensions.cs index c49ee97bd35..b8432732b3c 100644 --- a/src/EFCore.Relational/Metadata/ViewMappingExtensions.cs +++ b/src/EFCore.Relational/Metadata/ViewMappingExtensions.cs @@ -38,7 +38,7 @@ public static string ToDebugString( var singleLine = (options & MetadataDebugStringOptions.SingleLine) != 0; if (singleLine) { - builder.Append($"ViewMapping: "); + builder.Append("ViewMapping: "); } builder.Append(viewMapping.EntityType.Name).Append(" - "); @@ -47,11 +47,10 @@ public static string ToDebugString( if (viewMapping.IncludesDerivedTypes) { - builder.Append($" IncludesDerivedTypes"); + builder.Append(" IncludesDerivedTypes"); } - if (!singleLine && - (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) + if (!singleLine && (options & MetadataDebugStringOptions.IncludeAnnotations) != 0) { builder.Append(viewMapping.AnnotationsToDebugString(indent + 2)); } diff --git a/src/EFCore.Relational/Migrations/HistoryRepository.cs b/src/EFCore.Relational/Migrations/HistoryRepository.cs index 67bc565e2a3..1ce51551309 100644 --- a/src/EFCore.Relational/Migrations/HistoryRepository.cs +++ b/src/EFCore.Relational/Migrations/HistoryRepository.cs @@ -68,7 +68,8 @@ protected HistoryRepository([NotNull] HistoryRepositoryDependencies dependencies /// /// A helper class for generation of SQL. /// - protected virtual ISqlGenerationHelper SqlGenerationHelper => Dependencies.SqlGenerationHelper; + protected virtual ISqlGenerationHelper SqlGenerationHelper + => Dependencies.SqlGenerationHelper; /// /// THe history table name. diff --git a/src/EFCore.Relational/Migrations/IMigrationsAnnotationProvider.cs b/src/EFCore.Relational/Migrations/IMigrationsAnnotationProvider.cs index a7f94fce55c..549617c3d75 100644 --- a/src/EFCore.Relational/Migrations/IMigrationsAnnotationProvider.cs +++ b/src/EFCore.Relational/Migrations/IMigrationsAnnotationProvider.cs @@ -13,7 +13,7 @@ namespace Microsoft.EntityFrameworkCore.Migrations /// /// A service typically implemented by database providers that gives access to annotations used by EF Core Migrations /// when generating removal operations for various elements of the . The annotations - /// stored in the relational model are provided by . + /// stored in the relational model are provided by . /// /// /// The service lifetime is . This means a single instance diff --git a/src/EFCore.Relational/Migrations/IMigrator.cs b/src/EFCore.Relational/Migrations/IMigrator.cs index ad7889661ca..87acae3680d 100644 --- a/src/EFCore.Relational/Migrations/IMigrator.cs +++ b/src/EFCore.Relational/Migrations/IMigrator.cs @@ -58,6 +58,9 @@ Task MigrateAsync( /// The options to use when generating SQL for migrations. /// /// The generated script. - string GenerateScript([CanBeNull] string fromMigration = null, [CanBeNull] string toMigration = null, MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default); + string GenerateScript( + [CanBeNull] string fromMigration = null, + [CanBeNull] string toMigration = null, + MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default); } } diff --git a/src/EFCore.Relational/Migrations/Internal/MigrationsIdGenerator.cs b/src/EFCore.Relational/Migrations/Internal/MigrationsIdGenerator.cs index be749275a5d..18bf7464f9d 100644 --- a/src/EFCore.Relational/Migrations/Internal/MigrationsIdGenerator.cs +++ b/src/EFCore.Relational/Migrations/Internal/MigrationsIdGenerator.cs @@ -34,7 +34,8 @@ public class MigrationsIdGenerator : IMigrationsIdGenerator /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual string GetName(string id) => id.Substring(Format.Length + 1); + public virtual string GetName(string id) + => id.Substring(Format.Length + 1); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to diff --git a/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs b/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs index d3bf4cc1526..522d9f47851 100644 --- a/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs +++ b/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs @@ -13,7 +13,6 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Migrations.Operations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; @@ -63,13 +62,12 @@ public class MigrationsModelDiffer : IMigrationsModelDiffer private static readonly Type[] _constraintOperationTypes = { - typeof(AddForeignKeyOperation), - typeof(CreateIndexOperation), - typeof(AddCheckConstraintOperation) + typeof(AddForeignKeyOperation), typeof(CreateIndexOperation), typeof(AddCheckConstraintOperation) }; private IUpdateAdapter _sourceUpdateAdapter; private IUpdateAdapter _targetUpdateAdapter; + private readonly Dictionary _sourceSharedIdentityEntryMaps = new Dictionary(); @@ -389,8 +387,7 @@ protected virtual IEnumerable Diff( { var alterDatabaseOperation = new AlterDatabaseOperation { - Collation = target.Collation, - OldDatabase = { Collation = source.Collation } + Collation = target.Collation, OldDatabase = { Collation = source.Collation } }; alterDatabaseOperation.AddAnnotations(targetMigrationsAnnotations); @@ -497,7 +494,9 @@ protected virtual IEnumerable Remove([NotNull] IRelationalMo /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected virtual IEnumerable Diff( - [NotNull] IEnumerable source, [NotNull] IEnumerable target, [NotNull] DiffContext diffContext) + [NotNull] IEnumerable source, + [NotNull] IEnumerable target, + [NotNull] DiffContext diffContext) => DiffCollection( source, target, @@ -514,7 +513,9 @@ protected virtual IEnumerable Diff( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected virtual IEnumerable Diff( - [NotNull] string source, [NotNull] string target, [NotNull] DiffContext diffContext) + [NotNull] string source, + [NotNull] string target, + [NotNull] DiffContext diffContext) => Enumerable.Empty(); /// @@ -642,7 +643,8 @@ protected virtual IEnumerable Diff( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected virtual IEnumerable Add( - [NotNull] ITable target, [NotNull] DiffContext diffContext) + [NotNull] ITable target, + [NotNull] DiffContext diffContext) { if (target.IsExcludedFromMigrations) { @@ -689,7 +691,8 @@ protected virtual IEnumerable Add( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected virtual IEnumerable Remove( - [NotNull] ITable source, [NotNull] DiffContext diffContext) + [NotNull] ITable source, + [NotNull] DiffContext diffContext) { if (source.IsExcludedFromMigrations) { @@ -836,10 +839,16 @@ private static IEnumerable GetSortedProperties(IEntityType entityType .Select(pi => primaryKeyPropertyGroups.ContainsKey(pi) ? primaryKeyPropertyGroups[pi] : null) .Where(e => e != null) .Concat(leastPriorityPrimaryKeyProperties) - .Concat(sortedPropertyInfos.Where(pi => !primaryKeyPropertyGroups.ContainsKey(pi) && entityType.ClrType.IsAssignableFrom(pi.DeclaringType)).SelectMany(p => groups[p])) + .Concat( + sortedPropertyInfos + .Where(pi => !primaryKeyPropertyGroups.ContainsKey(pi) && entityType.ClrType.IsAssignableFrom(pi.DeclaringType)) + .SelectMany(p => groups[p])) .Concat(leastPriorityProperties) .Concat(entityType.GetDirectlyDerivedTypes().SelectMany(et => GetSortedProperties(et, table))) - .Concat(sortedPropertyInfos.Where(pi => !primaryKeyPropertyGroups.ContainsKey(pi) && !entityType.ClrType.IsAssignableFrom(pi.DeclaringType)).SelectMany(p => groups[p])); + .Concat( + sortedPropertyInfos + .Where(pi => !primaryKeyPropertyGroups.ContainsKey(pi) && !entityType.ClrType.IsAssignableFrom(pi.DeclaringType)) + .SelectMany(p => groups[p])); } private sealed class PropertyInfoEqualityComparer : IEqualityComparer @@ -879,18 +888,24 @@ protected virtual IEnumerable Diff( (t, c) => Add(t, c), Remove, (s, t, c) => string.Equals(s.Name, t.Name, StringComparison.OrdinalIgnoreCase), - (s, t, c) => s.PropertyMappings.Any(sm => - t.PropertyMappings.Any(tm => - string.Equals(sm.Property.Name, tm.Property.Name, StringComparison.OrdinalIgnoreCase) - && EntityTypePathEquals(sm.Property.DeclaringEntityType, tm.Property.DeclaringEntityType, c))), - (s, t, c) => s.PropertyMappings.Any(sm => - t.PropertyMappings.Any(tm => - string.Equals(sm.Property.Name, tm.Property.Name, StringComparison.OrdinalIgnoreCase))), - (s, t, c) => ColumnStructureEquals(s, t) - && s.PropertyMappings.Any(sm => - t.PropertyMappings.Any(tm => - string.Equals(sm.Property.Name, tm.Property.Name, StringComparison.OrdinalIgnoreCase) + (s, t, c) => s.PropertyMappings.Any( + sm => + t.PropertyMappings.Any( + tm => + string.Equals(sm.Property.Name, tm.Property.Name, StringComparison.OrdinalIgnoreCase) && EntityTypePathEquals(sm.Property.DeclaringEntityType, tm.Property.DeclaringEntityType, c))), + (s, t, c) => s.PropertyMappings.Any( + sm => + t.PropertyMappings.Any( + tm => + string.Equals(sm.Property.Name, tm.Property.Name, StringComparison.OrdinalIgnoreCase))), + (s, t, c) => ColumnStructureEquals(s, t) + && s.PropertyMappings.Any( + sm => + t.PropertyMappings.Any( + tm => + string.Equals(sm.Property.Name, tm.Property.Name, StringComparison.OrdinalIgnoreCase) + && EntityTypePathEquals(sm.Property.DeclaringEntityType, tm.Property.DeclaringEntityType, c))), (s, t, c) => ColumnStructureEquals(s, t)); private bool ColumnStructureEquals(IColumn source, IColumn target) @@ -935,7 +950,8 @@ private static bool EntityTypePathEquals(IEntityType source, IEntityType target, var nextSource = source.DefiningEntityType; var nextTarget = target.DefiningEntityType; return (nextSource == null && nextTarget == null) - || (nextSource != null && nextTarget != null + || (nextSource != null + && nextTarget != null && EntityTypePathEquals(nextSource, nextTarget, diffContext)); } @@ -968,7 +984,9 @@ private static string GetDefiningNavigationName(IEntityType entityType) /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected virtual IEnumerable Diff( - [NotNull] IColumn source, [NotNull] IColumn target, [NotNull] DiffContext diffContext) + [NotNull] IColumn source, + [NotNull] IColumn target, + [NotNull] DiffContext diffContext) { var sourceMapping = source.PropertyMappings.First(); var targetMapping = target.PropertyMappings.First(); @@ -1097,6 +1115,7 @@ private void Initialize( column.Name, (column.Table.Name, column.Table.Schema).FormatTable())); } + if (column.DefaultValueSql?.Length == 0) { throw new InvalidOperationException( @@ -1104,6 +1123,7 @@ private void Initialize( column.Name, (column.Table.Name, column.Table.Schema).FormatTable())); } + if (column.ComputedColumnSql?.Length == 0) { throw new InvalidOperationException( @@ -1269,7 +1289,9 @@ protected virtual IEnumerable Diff( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected virtual IEnumerable Diff( - [NotNull] IForeignKeyConstraint source, [NotNull] IForeignKeyConstraint target, [NotNull] DiffContext diffContext) + [NotNull] IForeignKeyConstraint source, + [NotNull] IForeignKeyConstraint target, + [NotNull] DiffContext diffContext) => Enumerable.Empty(); /// @@ -1449,7 +1471,9 @@ protected virtual IEnumerable Diff( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected virtual IEnumerable Diff( - [NotNull] ICheckConstraint source, [NotNull] ICheckConstraint target, [NotNull] DiffContext diffContext) + [NotNull] ICheckConstraint source, + [NotNull] ICheckConstraint target, + [NotNull] DiffContext diffContext) => Enumerable.Empty(); /// @@ -1518,7 +1542,9 @@ protected virtual IEnumerable Diff( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected virtual IEnumerable Diff( - [NotNull] ISequence source, [NotNull] ISequence target, [NotNull] DiffContext diffContext) + [NotNull] ISequence source, + [NotNull] ISequence target, + [NotNull] DiffContext diffContext) { if (source.Schema != target.Schema || source.Name != target.Name) @@ -1672,9 +1698,9 @@ protected virtual void TrackData( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected virtual Dictionary> DiffData( - [CanBeNull] IRelationalModel source, - [CanBeNull] IRelationalModel target, - [NotNull] DiffContext diffContext) + [CanBeNull] IRelationalModel source, + [CanBeNull] IRelationalModel target, + [NotNull] DiffContext diffContext) { Check.NotNull(diffContext, nameof(diffContext)); @@ -1806,14 +1832,16 @@ protected virtual Dictionary> DiffData( { break; } + continue; } var targetTable = diffContext.FindTarget(sourceTable); var removedMapping = true; if (targetTable != null - && targetKeyMap.Keys.Any(k => k.Item2 == targetTable - && k.Item1.DeclaringEntityType.GetTableMappings().First().Table == firstTargetTable)) + && targetKeyMap.Keys.Any( + k => k.Item2 == targetTable + && k.Item1.DeclaringEntityType.GetTableMappings().First().Table == firstTargetTable)) { removedMapping = false; } @@ -2018,7 +2046,9 @@ var modelValuesChanged } private static IUpdateEntry GetEntry( - IDictionary sourceSeed, IEntityType sourceEntityType, IUpdateAdapter updateAdapter) + IDictionary sourceSeed, + IEntityType sourceEntityType, + IUpdateAdapter updateAdapter) { var key = sourceEntityType.FindPrimaryKey(); var keyValues = new object[key.Properties.Count]; @@ -2037,7 +2067,9 @@ private static IUpdateEntry GetEntry( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// protected virtual IEnumerable GetDataOperations( - [NotNull] IRelationalModel source, [NotNull] IRelationalModel target, [NotNull] DiffContext diffContext) + [NotNull] IRelationalModel source, + [NotNull] IRelationalModel target, + [NotNull] DiffContext diffContext) { TrackData(source, target, diffContext); @@ -2191,8 +2223,9 @@ private IEnumerable GetDataOperations( break; } - if (command.Entries.Any(en => changedTableMappings.TryGetValue(en.EntityType, out var newTables) - && newTables.Any(t => t.Name == command.TableName && t.Schema == command.Schema))) + if (command.Entries.Any( + en => changedTableMappings.TryGetValue(en.EntityType, out var newTables) + && newTables.Any(t => t.Name == command.TableName && t.Schema == command.Schema))) { // If the entity type uses TPT add the rows to the new tables to which the entity has been mapped goto case EntityState.Added; @@ -2223,8 +2256,9 @@ private IEnumerable GetDataOperations( // If the entity type used TPT delete the rows in the tables to which the entity is no longer mapped if (command.Entries.Any(en => entriesWithRemovedMappings.Contains(en)) - && !command.Entries.Any(en => changedTableMappings.TryGetValue(en.EntityType, out var removedTables) - && removedTables.Any(t => t.Name == command.TableName && t.Schema == command.Schema))) + && !command.Entries.Any( + en => changedTableMappings.TryGetValue(en.EntityType, out var removedTables) + && removedTables.Any(t => t.Name == command.TableName && t.Schema == command.Schema))) { break; } @@ -2456,6 +2490,7 @@ private sealed class EntryMapping private sealed class SharedIdentityMap { private readonly IUpdateAdapter _updateAdapter; + private readonly Dictionary _entryValueMap = new Dictionary(); @@ -2470,7 +2505,8 @@ public SharedIdentityMap(IUpdateAdapter updateAdapter) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public IEnumerable Values => _entryValueMap.Values; + public IEnumerable Values + => _entryValueMap.Values; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to diff --git a/src/EFCore.Relational/Migrations/Internal/Migrator.cs b/src/EFCore.Relational/Migrations/Internal/Migrator.cs index 565ff797938..506ecc6bb98 100644 --- a/src/EFCore.Relational/Migrations/Internal/Migrator.cs +++ b/src/EFCore.Relational/Migrations/Internal/Migrator.cs @@ -158,13 +158,13 @@ public virtual async Task MigrateAsync( _historyRepository.GetCreateScript()); await command.ExecuteNonQueryAsync( - new RelationalCommandParameterObject( - _connection, - null, - null, - _currentContext.Context, - _commandLogger), - cancellationToken) + new RelationalCommandParameterObject( + _connection, + null, + null, + _currentContext.Context, + _commandLogger), + cancellationToken) .ConfigureAwait(false); } @@ -363,6 +363,7 @@ public virtual string GenerateScript( .Append(_sqlGenerationHelper.BatchTerminator); transactionStarted = true; } + if (transactionStarted && command.TransactionSuppressed) { builder @@ -414,6 +415,7 @@ public virtual string GenerateScript( .Append(_sqlGenerationHelper.BatchTerminator); transactionStarted = true; } + if (transactionStarted && command.TransactionSuppressed) { builder @@ -459,7 +461,8 @@ public virtual string GenerateScript( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - protected virtual IReadOnlyList GenerateUpSql([NotNull] Migration migration, + protected virtual IReadOnlyList GenerateUpSql( + [NotNull] Migration migration, MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default) { Check.NotNull(migration, nameof(migration)); @@ -507,7 +510,8 @@ private IModel FinalizeModel(IModel model) typeMappingConvention.ProcessModelFinalizing(conventionModel.Builder, null); } - var relationalModelConvention = conventionSet.ModelFinalizedConventions.OfType().FirstOrDefault(); + var relationalModelConvention = + conventionSet.ModelFinalizedConventions.OfType().FirstOrDefault(); if (relationalModelConvention != null) { relationalModelConvention.ProcessModelFinalized(conventionModel); diff --git a/src/EFCore.Relational/Migrations/Migration.cs b/src/EFCore.Relational/Migrations/Migration.cs index 453113f4d03..759a83dea96 100644 --- a/src/EFCore.Relational/Migrations/Migration.cs +++ b/src/EFCore.Relational/Migrations/Migration.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Migrations.Operations; namespace Microsoft.EntityFrameworkCore.Migrations diff --git a/src/EFCore.Relational/Migrations/MigrationBuilder.cs b/src/EFCore.Relational/Migrations/MigrationBuilder.cs index 8561cf96b2f..653bb5fdb04 100644 --- a/src/EFCore.Relational/Migrations/MigrationBuilder.cs +++ b/src/EFCore.Relational/Migrations/MigrationBuilder.cs @@ -329,13 +329,15 @@ public virtual OperationBuilder AddUniqueConstrain /// The SQL expression to use for the column's default constraint. /// The SQL expression to use to compute the column value. /// - /// The CLR type that the column was previously mapped to. Can be , in which case previous value is considered unknown. + /// The CLR type that the column was previously mapped to. Can be , in which case previous value is considered + /// unknown. /// /// /// The previous store/database type of the column. Can be , in which case previous value is considered unknown. /// /// - /// Indicates whether or not the column could previously contain Unicode data, or if not specified or not applicable. + /// Indicates whether or not the column could previously contain Unicode data, or if not specified or not + /// applicable. /// /// /// The previous maximum length of data that can be stored in the column, or if not specified or not applicable. @@ -345,18 +347,21 @@ public virtual OperationBuilder AddUniqueConstrain /// in SQL Server. Can be , in which case previous value is considered unknown. /// /// - /// Indicates whether or not the column could previously store values. Can be , in which case previous value is + /// Indicates whether or not the column could previously store values. Can be , in which + /// case previous value is /// considered unknown. /// /// /// The previous default value for the column. Can be , in which case previous value is considered unknown. /// /// - /// The previous SQL expression used for the column's default constraint. Can be , in which case previous value is considered + /// The previous SQL expression used for the column's default constraint. Can be , in which case previous value is + /// considered /// unknown. /// /// - /// The previous SQL expression used to compute the column value. Can be , in which case previous value is considered unknown. + /// The previous SQL expression used to compute the column value. Can be , in which case previous value is + /// considered unknown. /// /// Indicates whether or not the column is constrained to fixed-length data. /// Indicates whether or not the column was previously constrained to fixed-length data. @@ -374,7 +379,8 @@ public virtual OperationBuilder AddUniqueConstrain /// The maximum number of decimal places that is allowed in this column, or if not specified or not applicable. /// /// - /// The previous maximum number of decimal places that is allowed in this column, or if not specified or not applicable. + /// The previous maximum number of decimal places that is allowed in this column, or if not specified or not + /// applicable. /// /// Whether the value of the computed column is stored in the database or not. /// Whether the value of the previous computed column was stored in the database or not. @@ -471,10 +477,7 @@ public virtual AlterOperationBuilder AlterDatabase( [CanBeNull] string collation = null, [CanBeNull] string oldCollation = null) { - var operation = new AlterDatabaseOperation - { - Collation = collation - }; + var operation = new AlterDatabaseOperation { Collation = collation }; Operations.Add(operation); return new AlterOperationBuilder(operation); @@ -696,7 +699,7 @@ public virtual OperationBuilder CreateSequence( /// /// - /// Warning, this API is obsolete. Use instead. + /// Warning, this API is obsolete. Use instead. /// /// /// Builds an to create a new check constraint. @@ -1588,22 +1591,25 @@ public virtual OperationBuilder UpdateData( /// /// A string that represents the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override string ToString() => base.ToString(); + public override string ToString() + => base.ToString(); /// /// Determines whether the specified object is equal to the current object. /// /// The object to compare with the current object. - /// if the specified object is equal to the current object; otherwise, . + /// if the specified object is equal to the current object; otherwise, . [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object obj) + => base.Equals(obj); /// /// Serves as the default hash function. /// /// A hash code for the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); #endregion } diff --git a/src/EFCore.Relational/Migrations/MigrationCommand.cs b/src/EFCore.Relational/Migrations/MigrationCommand.cs index a4819c0a1b4..aded7a3b5da 100644 --- a/src/EFCore.Relational/Migrations/MigrationCommand.cs +++ b/src/EFCore.Relational/Migrations/MigrationCommand.cs @@ -48,7 +48,8 @@ public MigrationCommand( /// /// The SQL command text that will be executed against the database. /// - public virtual string CommandText => _relationalCommand.CommandText; + public virtual string CommandText + => _relationalCommand.CommandText; /// /// The associated command logger. diff --git a/src/EFCore.Relational/Migrations/MigrationCommandListBuilder.cs b/src/EFCore.Relational/Migrations/MigrationCommandListBuilder.cs index cabaef37580..abb2a65d002 100644 --- a/src/EFCore.Relational/Migrations/MigrationCommandListBuilder.cs +++ b/src/EFCore.Relational/Migrations/MigrationCommandListBuilder.cs @@ -37,7 +37,8 @@ public MigrationCommandListBuilder( /// Gets the list of built commands. /// /// The s that have been built. - public virtual IReadOnlyList GetCommandList() => _commands; + public virtual IReadOnlyList GetCommandList() + => _commands; /// /// Ends the building of the current command and adds it to the list of built commands. @@ -124,7 +125,8 @@ public virtual MigrationCommandListBuilder AppendLines([NotNull] string value) /// block is disposed will be indented one level more than the current level. /// /// The object to dispose to indicate that the indentation should go back up a level. - public virtual IDisposable Indent() => _commandBuilder.Indent(); + public virtual IDisposable Indent() + => _commandBuilder.Indent(); /// /// Increases the current indentation by one level. diff --git a/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs b/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs index 6e504a37ae7..597aa92ef92 100644 --- a/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs +++ b/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs @@ -963,22 +963,25 @@ protected virtual IEnumerable GenerateModificationCommands( { if (operation.Columns.Length != operation.Values.GetLength(1)) { - throw new InvalidOperationException(RelationalStrings.InsertDataOperationValuesCountMismatch( - operation.Values.GetLength(1), operation.Columns.Length, FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.InsertDataOperationValuesCountMismatch( + operation.Values.GetLength(1), operation.Columns.Length, FormatTable(operation.Table, operation.Schema))); } if (operation.ColumnTypes != null && operation.Columns.Length != operation.ColumnTypes.Length) { - throw new InvalidOperationException(RelationalStrings.InsertDataOperationTypesCountMismatch( - operation.ColumnTypes.Length, operation.Columns.Length, FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.InsertDataOperationTypesCountMismatch( + operation.ColumnTypes.Length, operation.Columns.Length, FormatTable(operation.Table, operation.Schema))); } if (operation.ColumnTypes == null && model == null) { - throw new InvalidOperationException(RelationalStrings.InsertDataOperationNoModel( - FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.InsertDataOperationNoModel( + FormatTable(operation.Table, operation.Schema))); } var propertyMappings = operation.ColumnTypes == null @@ -1006,7 +1009,8 @@ protected virtual IEnumerable GenerateModificationCommands( SensitiveLoggingEnabled, propertyMapping?.Column.IsNullable); } - yield return new ModificationCommand(operation.Table, operation.Schema, modifications, sensitiveLoggingEnabled: SensitiveLoggingEnabled); + yield return new ModificationCommand( + operation.Table, operation.Schema, modifications, sensitiveLoggingEnabled: SensitiveLoggingEnabled); } } @@ -1050,22 +1054,25 @@ protected virtual IEnumerable GenerateModificationCommands( { if (operation.KeyColumns.Length != operation.KeyValues.GetLength(1)) { - throw new InvalidOperationException(RelationalStrings.DeleteDataOperationValuesCountMismatch( - operation.KeyValues.GetLength(1), operation.KeyColumns.Length, FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.DeleteDataOperationValuesCountMismatch( + operation.KeyValues.GetLength(1), operation.KeyColumns.Length, FormatTable(operation.Table, operation.Schema))); } if (operation.KeyColumnTypes != null && operation.KeyColumns.Length != operation.KeyColumnTypes.Length) { - throw new InvalidOperationException(RelationalStrings.DeleteDataOperationTypesCountMismatch( - operation.KeyColumnTypes.Length, operation.KeyColumns.Length, FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.DeleteDataOperationTypesCountMismatch( + operation.KeyColumnTypes.Length, operation.KeyColumns.Length, FormatTable(operation.Table, operation.Schema))); } if (operation.KeyColumnTypes == null && model == null) { - throw new InvalidOperationException(RelationalStrings.DeleteDataOperationNoModel( - FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.DeleteDataOperationNoModel( + FormatTable(operation.Table, operation.Schema))); } var keypropertyMappings = operation.KeyColumnTypes == null @@ -1093,7 +1100,8 @@ protected virtual IEnumerable GenerateModificationCommands( SensitiveLoggingEnabled, propertyMapping?.Column.IsNullable); } - yield return new ModificationCommand(operation.Table, operation.Schema, modifications, sensitiveLoggingEnabled: SensitiveLoggingEnabled); + yield return new ModificationCommand( + operation.Table, operation.Schema, modifications, sensitiveLoggingEnabled: SensitiveLoggingEnabled); } } @@ -1132,45 +1140,52 @@ protected virtual void Generate( /// The model. /// The commands that correspond to the given operation. protected virtual IEnumerable GenerateModificationCommands( - [NotNull] UpdateDataOperation operation, [CanBeNull] IModel model) + [NotNull] UpdateDataOperation operation, + [CanBeNull] IModel model) { if (operation.KeyColumns.Length != operation.KeyValues.GetLength(1)) { - throw new InvalidOperationException(RelationalStrings.UpdateDataOperationKeyValuesCountMismatch( - operation.KeyValues.GetLength(1), operation.KeyColumns.Length, FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.UpdateDataOperationKeyValuesCountMismatch( + operation.KeyValues.GetLength(1), operation.KeyColumns.Length, FormatTable(operation.Table, operation.Schema))); } if (operation.Columns.Length != operation.Values.GetLength(1)) { - throw new InvalidOperationException(RelationalStrings.UpdateDataOperationValuesCountMismatch( - operation.Values.GetLength(1), operation.Columns.Length, FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.UpdateDataOperationValuesCountMismatch( + operation.Values.GetLength(1), operation.Columns.Length, FormatTable(operation.Table, operation.Schema))); } if (operation.KeyValues.GetLength(0) != operation.Values.GetLength(0)) { - throw new InvalidOperationException(RelationalStrings.UpdateDataOperationRowCountMismatch( - operation.Values.GetLength(0), operation.KeyValues.GetLength(0), FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.UpdateDataOperationRowCountMismatch( + operation.Values.GetLength(0), operation.KeyValues.GetLength(0), FormatTable(operation.Table, operation.Schema))); } if (operation.KeyColumnTypes != null && operation.KeyColumns.Length != operation.KeyColumnTypes.Length) { - throw new InvalidOperationException(RelationalStrings.UpdateDataOperationKeyTypesCountMismatch( - operation.KeyColumnTypes.Length, operation.KeyColumns.Length, FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.UpdateDataOperationKeyTypesCountMismatch( + operation.KeyColumnTypes.Length, operation.KeyColumns.Length, FormatTable(operation.Table, operation.Schema))); } if (operation.ColumnTypes != null && operation.Columns.Length != operation.ColumnTypes.Length) { - throw new InvalidOperationException(RelationalStrings.UpdateDataOperationTypesCountMismatch( - operation.ColumnTypes.Length, operation.Columns.Length, FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.UpdateDataOperationTypesCountMismatch( + operation.ColumnTypes.Length, operation.Columns.Length, FormatTable(operation.Table, operation.Schema))); } if (operation.KeyColumnTypes == null && model == null) { - throw new InvalidOperationException(RelationalStrings.UpdateDataOperationNoModel( - FormatTable(operation.Table, operation.Schema))); + throw new InvalidOperationException( + RelationalStrings.UpdateDataOperationNoModel( + FormatTable(operation.Table, operation.Schema))); } var keyPropertyMappings = operation.KeyColumnTypes == null @@ -1220,7 +1235,9 @@ protected virtual IEnumerable GenerateModificationCommands( SensitiveLoggingEnabled, propertyMapping?.Column.IsNullable); } - yield return new ModificationCommand(operation.Table, operation.Schema, keys.Concat(modifications).ToArray(), sensitiveLoggingEnabled: SensitiveLoggingEnabled); + yield return new ModificationCommand( + operation.Table, operation.Schema, keys.Concat(modifications).ToArray(), + sensitiveLoggingEnabled: SensitiveLoggingEnabled); } } @@ -1228,13 +1245,17 @@ private static string FormatTable(string table, string schema) => schema == null ? table : schema + "." + table; private static IColumnMapping[] GetPropertyMappings( - [NotNull] string[] names, [NotNull] string tableName, [CanBeNull] string schema, [NotNull] IModel model) + [NotNull] string[] names, + [NotNull] string tableName, + [CanBeNull] string schema, + [NotNull] IModel model) { var table = model.GetRelationalModel().FindTable(tableName, schema); if (table == null) { - throw new InvalidOperationException(RelationalStrings.DataOperationNoTable( - FormatTable(tableName, schema))); + throw new InvalidOperationException( + RelationalStrings.DataOperationNoTable( + FormatTable(tableName, schema))); } var properties = new IColumnMapping[names.Length]; @@ -1244,8 +1265,9 @@ private static IColumnMapping[] GetPropertyMappings( var column = table.FindColumn(name); if (column == null) { - throw new InvalidOperationException(RelationalStrings.DataOperationNoProperty( - FormatTable(tableName, schema), name)); + throw new InvalidOperationException( + RelationalStrings.DataOperationNoProperty( + FormatTable(tableName, schema), name)); } properties[i] = column.PropertyMappings.First(); @@ -1885,10 +1907,10 @@ protected virtual IEnumerable FindEntityTypes( /// The property found, or if no property maps to the given column. [Obsolete("Use model?.GetRelationalModel().FindTable().FindColumn()")] protected virtual IProperty FindProperty( - [CanBeNull] IModel model, - [CanBeNull] string schema, - [NotNull] string tableName, - [NotNull] string columnName) + [CanBeNull] IModel model, + [CanBeNull] string schema, + [NotNull] string tableName, + [NotNull] string columnName) => model?.GetRelationalModel().FindTable(Check.NotEmpty(tableName, nameof(tableName)), schema) .Columns.FirstOrDefault(c => c.Name == columnName)?.PropertyMappings.First().Property; @@ -1923,7 +1945,8 @@ protected virtual string ColumnList([NotNull] string[] columns) /// /// The target model which may be if the operations exist without a model. /// - /// If the model was generated by EF Core 1.1 or later; if the model is , has + /// If the model was generated by EF Core 1.1 or later; if the model is + /// , has /// no version specified, or was generated by an EF Core version prior to 1.1. /// protected virtual bool IsOldColumnSupported([CanBeNull] IModel model) @@ -1934,7 +1957,7 @@ protected virtual bool IsOldColumnSupported([CanBeNull] IModel model) /// the legacy behavior of setting the new name and schema to null when unchanged. /// /// The target model. - /// if the legacy behavior is used. + /// if the legacy behavior is used. protected virtual bool HasLegacyRenameOperations([CanBeNull] IModel model) => !TryGetVersion(model, out var version) || VersionComparer.Compare(version, "2.1.0") < 0; @@ -1944,7 +1967,7 @@ protected virtual bool HasLegacyRenameOperations([CanBeNull] IModel model) /// /// The target model. /// The version. - /// if the version could be retrieved. + /// if the version could be retrieved. protected virtual bool TryGetVersion([CanBeNull] IModel model, out string version) { if (!(model?.GetProductVersion() is string versionString)) diff --git a/src/EFCore.Relational/Migrations/Operations/AddCheckConstraintOperation.cs b/src/EFCore.Relational/Migrations/Operations/AddCheckConstraintOperation.cs index e66a57c83f8..06e18ce1556 100644 --- a/src/EFCore.Relational/Migrations/Operations/AddCheckConstraintOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/AddCheckConstraintOperation.cs @@ -38,7 +38,7 @@ public class AddCheckConstraintOperation : MigrationOperation, ITableMigrationOp public virtual string Sql { get; [param: NotNull] set; } /// - /// Creates a new from the specified check constraint. + /// Creates a new from the specified check constraint. /// /// The check constraint. /// The operation. diff --git a/src/EFCore.Relational/Migrations/Operations/AddForeignKeyOperation.cs b/src/EFCore.Relational/Migrations/Operations/AddForeignKeyOperation.cs index d4c60d7bd52..e2e8a8ca7c2 100644 --- a/src/EFCore.Relational/Migrations/Operations/AddForeignKeyOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/AddForeignKeyOperation.cs @@ -62,7 +62,7 @@ public class AddForeignKeyOperation : MigrationOperation, ITableMigrationOperati public virtual ReferentialAction OnDelete { get; set; } /// - /// Creates a new from the specified foreign key. + /// Creates a new from the specified foreign key. /// /// The foreign key. /// The operation. diff --git a/src/EFCore.Relational/Migrations/Operations/AddPrimaryKeyOperation.cs b/src/EFCore.Relational/Migrations/Operations/AddPrimaryKeyOperation.cs index dfb58c2a9ce..462ffb64c37 100644 --- a/src/EFCore.Relational/Migrations/Operations/AddPrimaryKeyOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/AddPrimaryKeyOperation.cs @@ -36,7 +36,7 @@ public class AddPrimaryKeyOperation : MigrationOperation, ITableMigrationOperati public virtual string[] Columns { get; [param: NotNull] set; } /// - /// Creates a new from the specified primary key. + /// Creates a new from the specified primary key. /// /// The primary key. /// The operation. diff --git a/src/EFCore.Relational/Migrations/Operations/AddUniqueConstraintOperation.cs b/src/EFCore.Relational/Migrations/Operations/AddUniqueConstraintOperation.cs index 2be8d188854..f8d98924801 100644 --- a/src/EFCore.Relational/Migrations/Operations/AddUniqueConstraintOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/AddUniqueConstraintOperation.cs @@ -36,7 +36,7 @@ public class AddUniqueConstraintOperation : MigrationOperation, ITableMigrationO public virtual string[] Columns { get; [param: NotNull] set; } /// - /// Creates a new from the specified unique constraint. + /// Creates a new from the specified unique constraint. /// /// The unique constraint. /// The operation. diff --git a/src/EFCore.Relational/Migrations/Operations/AlterColumnOperation.cs b/src/EFCore.Relational/Migrations/Operations/AlterColumnOperation.cs index 17e53901c51..cbe2b5c18ce 100644 --- a/src/EFCore.Relational/Migrations/Operations/AlterColumnOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/AlterColumnOperation.cs @@ -19,6 +19,7 @@ public class AlterColumnOperation : ColumnOperation, IAlterMigrationOperation public virtual ColumnOperation OldColumn { get; [param: NotNull] set; } = new AddColumnOperation(); /// - IMutableAnnotatable IAlterMigrationOperation.OldAnnotations => OldColumn; + IMutableAnnotatable IAlterMigrationOperation.OldAnnotations + => OldColumn; } } diff --git a/src/EFCore.Relational/Migrations/Operations/AlterDatabaseOperation.cs b/src/EFCore.Relational/Migrations/Operations/AlterDatabaseOperation.cs index 853fdf932e2..06788b549ad 100644 --- a/src/EFCore.Relational/Migrations/Operations/AlterDatabaseOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/AlterDatabaseOperation.cs @@ -18,7 +18,8 @@ public class AlterDatabaseOperation : DatabaseOperation, IAlterMigrationOperatio public virtual DatabaseOperation OldDatabase { get; } = new CreateDatabaseOperation(); /// - IMutableAnnotatable IAlterMigrationOperation.OldAnnotations => OldDatabase; + IMutableAnnotatable IAlterMigrationOperation.OldAnnotations + => OldDatabase; private sealed class CreateDatabaseOperation : DatabaseOperation { diff --git a/src/EFCore.Relational/Migrations/Operations/AlterSequenceOperation.cs b/src/EFCore.Relational/Migrations/Operations/AlterSequenceOperation.cs index d12d3ad6534..426744b2095 100644 --- a/src/EFCore.Relational/Migrations/Operations/AlterSequenceOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/AlterSequenceOperation.cs @@ -29,6 +29,7 @@ public class AlterSequenceOperation : SequenceOperation, IAlterMigrationOperatio public virtual SequenceOperation OldSequence { get; [param: NotNull] set; } = new CreateSequenceOperation(); /// - IMutableAnnotatable IAlterMigrationOperation.OldAnnotations => OldSequence; + IMutableAnnotatable IAlterMigrationOperation.OldAnnotations + => OldSequence; } } diff --git a/src/EFCore.Relational/Migrations/Operations/AlterTableOperation.cs b/src/EFCore.Relational/Migrations/Operations/AlterTableOperation.cs index 4561d18ec1f..93b0fe155f3 100644 --- a/src/EFCore.Relational/Migrations/Operations/AlterTableOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/AlterTableOperation.cs @@ -19,6 +19,7 @@ public class AlterTableOperation : TableOperation, IAlterMigrationOperation public virtual TableOperation OldTable { get; [param: NotNull] set; } = new CreateTableOperation(); /// - IMutableAnnotatable IAlterMigrationOperation.OldAnnotations => OldTable; + IMutableAnnotatable IAlterMigrationOperation.OldAnnotations + => OldTable; } } diff --git a/src/EFCore.Relational/Migrations/Operations/Builders/ColumnsBuilder.cs b/src/EFCore.Relational/Migrations/Operations/Builders/ColumnsBuilder.cs index 1b9926aa62e..04f6d8b654d 100644 --- a/src/EFCore.Relational/Migrations/Operations/Builders/ColumnsBuilder.cs +++ b/src/EFCore.Relational/Migrations/Operations/Builders/ColumnsBuilder.cs @@ -100,22 +100,25 @@ public virtual OperationBuilder Column( /// /// A string that represents the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override string ToString() => base.ToString(); + public override string ToString() + => base.ToString(); /// /// Determines whether the specified object is equal to the current object. /// /// The object to compare with the current object. - /// if the specified object is equal to the current object; otherwise, . + /// if the specified object is equal to the current object; otherwise, . [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object obj) + => base.Equals(obj); /// /// Serves as the default hash function. /// /// A hash code for the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); #endregion } diff --git a/src/EFCore.Relational/Migrations/Operations/Builders/OperationBuilder.cs b/src/EFCore.Relational/Migrations/Operations/Builders/OperationBuilder.cs index 6fa5567362d..5d934d34b3a 100644 --- a/src/EFCore.Relational/Migrations/Operations/Builders/OperationBuilder.cs +++ b/src/EFCore.Relational/Migrations/Operations/Builders/OperationBuilder.cs @@ -31,7 +31,8 @@ public OperationBuilder([NotNull] TOperation operation) /// protected virtual TOperation Operation { get; } - TOperation IInfrastructure.Instance => Operation; + TOperation IInfrastructure.Instance + => Operation; /// /// Annotates the operation with the given name/value pair. @@ -58,22 +59,25 @@ public virtual OperationBuilder Annotation( /// /// A string that represents the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override string ToString() => base.ToString(); + public override string ToString() + => base.ToString(); /// /// Determines whether the specified object is equal to the current object. /// /// The object to compare with the current object. - /// if the specified object is equal to the current object; otherwise, . + /// if the specified object is equal to the current object; otherwise, . [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object obj) + => base.Equals(obj); /// /// Serves as the default hash function. /// /// A hash code for the current object. [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); #endregion } diff --git a/src/EFCore.Relational/Migrations/Operations/CreateIndexOperation.cs b/src/EFCore.Relational/Migrations/Operations/CreateIndexOperation.cs index 5eac851ab79..60e31c06861 100644 --- a/src/EFCore.Relational/Migrations/Operations/CreateIndexOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/CreateIndexOperation.cs @@ -46,7 +46,7 @@ public class CreateIndexOperation : MigrationOperation, ITableMigrationOperation public virtual string Filter { get; [param: CanBeNull] set; } /// - /// Creates a new from the specified index. + /// Creates a new from the specified index. /// /// The index. /// The operation. diff --git a/src/EFCore.Relational/Migrations/Operations/DropColumnOperation.cs b/src/EFCore.Relational/Migrations/Operations/DropColumnOperation.cs index 5f6e94a9193..0e34977afb7 100644 --- a/src/EFCore.Relational/Migrations/Operations/DropColumnOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/DropColumnOperation.cs @@ -16,7 +16,8 @@ public class DropColumnOperation : MigrationOperation, ITableMigrationOperation /// Creates a new instance of the . /// // ReSharper disable once VirtualMemberCallInConstructor - public DropColumnOperation() => IsDestructiveChange = true; + public DropColumnOperation() + => IsDestructiveChange = true; /// /// The name of the column. diff --git a/src/EFCore.Relational/Migrations/Operations/DropTableOperation.cs b/src/EFCore.Relational/Migrations/Operations/DropTableOperation.cs index c12669227f2..b67dc4610b2 100644 --- a/src/EFCore.Relational/Migrations/Operations/DropTableOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/DropTableOperation.cs @@ -16,7 +16,8 @@ public class DropTableOperation : MigrationOperation, ITableMigrationOperation /// Creates a new . /// // ReSharper disable once VirtualMemberCallInConstructor - public DropTableOperation() => IsDestructiveChange = true; + public DropTableOperation() + => IsDestructiveChange = true; /// /// The name of the table. @@ -29,6 +30,7 @@ public class DropTableOperation : MigrationOperation, ITableMigrationOperation public virtual string Schema { get; [param: CanBeNull] set; } /// - string ITableMigrationOperation.Table => Name; + string ITableMigrationOperation.Table + => Name; } } diff --git a/src/EFCore.Relational/Migrations/Operations/RenameTableOperation.cs b/src/EFCore.Relational/Migrations/Operations/RenameTableOperation.cs index c0d73c37228..05415587d5a 100644 --- a/src/EFCore.Relational/Migrations/Operations/RenameTableOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/RenameTableOperation.cs @@ -33,6 +33,7 @@ public class RenameTableOperation : MigrationOperation, ITableMigrationOperation public virtual string NewName { get; [param: CanBeNull] set; } /// - string ITableMigrationOperation.Table => Name; + string ITableMigrationOperation.Table + => Name; } } diff --git a/src/EFCore.Relational/Migrations/Operations/TableOperation.cs b/src/EFCore.Relational/Migrations/Operations/TableOperation.cs index 60f0f50300a..a1fcf71a15e 100644 --- a/src/EFCore.Relational/Migrations/Operations/TableOperation.cs +++ b/src/EFCore.Relational/Migrations/Operations/TableOperation.cs @@ -27,6 +27,7 @@ public abstract class TableOperation : MigrationOperation, ITableMigrationOperat public virtual string Comment { get; [param: CanBeNull] set; } /// - string ITableMigrationOperation.Table => Name; + string ITableMigrationOperation.Table + => Name; } } diff --git a/src/EFCore.Relational/Properties/InternalsVisibleTo.cs b/src/EFCore.Relational/Properties/InternalsVisibleTo.cs index ea405af814f..9a8716509c4 100644 --- a/src/EFCore.Relational/Properties/InternalsVisibleTo.cs +++ b/src/EFCore.Relational/Properties/InternalsVisibleTo.cs @@ -3,4 +3,6 @@ using System.Runtime.CompilerServices; -[assembly: InternalsVisibleTo("Microsoft.EntityFrameworkCore.Relational.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] +[assembly: + InternalsVisibleTo( + "Microsoft.EntityFrameworkCore.Relational.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] diff --git a/src/EFCore.Relational/Query/EntityProjectionExpression.cs b/src/EFCore.Relational/Query/EntityProjectionExpression.cs index 25463476742..0fa62473ac4 100644 --- a/src/EFCore.Relational/Query/EntityProjectionExpression.cs +++ b/src/EFCore.Relational/Query/EntityProjectionExpression.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; -using System.Runtime.InteropServices; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Metadata; @@ -17,7 +16,7 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// An expression that represents an entity in the projection of . + /// An expression that represents an entity in the projection of . /// /// /// This type is typically used by database providers (and other extensions). It is generally @@ -27,6 +26,7 @@ namespace Microsoft.EntityFrameworkCore.Query public class EntityProjectionExpression : Expression { private readonly IDictionary _propertyExpressionMap = new Dictionary(); + private readonly IDictionary _ownedNavigationMap = new Dictionary(); @@ -47,7 +47,7 @@ public EntityProjectionExpression([NotNull] IEntityType entityType, [NotNull] Ta /// /// The entity type to shape. /// A dictionary of column expressions corresponding to properties of the entity type. - /// A to generate discriminator for each concrete entity type in hierarchy. + /// A to generate discriminator for each concrete entity type in hierarchy. public EntityProjectionExpression( [NotNull] IEntityType entityType, [NotNull] IDictionary propertyExpressionMap, @@ -65,14 +65,19 @@ public EntityProjectionExpression( /// The entity type being projected out. /// public virtual IEntityType EntityType { get; } + /// - /// A to generate discriminator for entity type. + /// A to generate discriminator for entity type. /// public virtual SqlExpression DiscriminatorExpression { get; } + /// - public sealed override ExpressionType NodeType => ExpressionType.Extension; + public sealed override ExpressionType NodeType + => ExpressionType.Extension; + /// - public override Type Type => EntityType.ClrType; + public override Type Type + => EntityType.ClrType; /// protected override Expression VisitChildren(ExpressionVisitor visitor) @@ -124,8 +129,9 @@ public virtual EntityProjectionExpression UpdateEntityType([NotNull] IEntityType if (!derivedType.GetAllBaseTypes().Contains(EntityType)) { - throw new InvalidOperationException(RelationalStrings.InvalidDerivedTypeInEntityProjection( - derivedType.DisplayName(), EntityType.DisplayName())); + throw new InvalidOperationException( + RelationalStrings.InvalidDerivedTypeInEntityProjection( + derivedType.DisplayName(), EntityType.DisplayName())); } var propertyExpressionMap = new Dictionary(); @@ -194,7 +200,7 @@ public virtual void AddNavigationBinding([NotNull] INavigation navigation, [NotN /// /// Binds a navigation with this entity projection to get entity shaper for the target entity type of the navigation which was - /// previously added using method. + /// previously added using method. /// /// A navigation to bind. /// An entity shaper expression for the target entity type of the navigation. diff --git a/src/EFCore.Relational/Query/ExpressionExtensions.cs b/src/EFCore.Relational/Query/ExpressionExtensions.cs index 82825e2e0ea..7de532f65d1 100644 --- a/src/EFCore.Relational/Query/ExpressionExtensions.cs +++ b/src/EFCore.Relational/Query/ExpressionExtensions.cs @@ -21,7 +21,7 @@ namespace Microsoft.EntityFrameworkCore.Query public static class ExpressionExtensions { /// - /// Infers type mapping from given s. + /// Infers type mapping from given s. /// /// Expressions to search for to find the type mapping. /// A relational type mapping inferred from the expressions. diff --git a/src/EFCore.Relational/Query/IMemberTranslator.cs b/src/EFCore.Relational/Query/IMemberTranslator.cs index a81ee61a085..8f8d93f660a 100644 --- a/src/EFCore.Relational/Query/IMemberTranslator.cs +++ b/src/EFCore.Relational/Query/IMemberTranslator.cs @@ -22,13 +22,13 @@ namespace Microsoft.EntityFrameworkCore.Query public interface IMemberTranslator { /// - /// Translates a LINQ to a SQL equivalent. + /// Translates a LINQ to a SQL equivalent. /// - /// A SQL representation of . - /// The member info from . - /// The return type from . + /// A SQL representation of . + /// The member info from . + /// The return type from . /// The query logger to use. - /// A SQL translation of the . + /// A SQL translation of the . SqlExpression Translate( [CanBeNull] SqlExpression instance, [NotNull] MemberInfo member, diff --git a/src/EFCore.Relational/Query/IMemberTranslatorPlugin.cs b/src/EFCore.Relational/Query/IMemberTranslatorPlugin.cs index 1c966fa8bb1..7929bd72612 100644 --- a/src/EFCore.Relational/Query/IMemberTranslatorPlugin.cs +++ b/src/EFCore.Relational/Query/IMemberTranslatorPlugin.cs @@ -8,7 +8,7 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// Represents plugin for . + /// Represents plugin for . /// /// /// The service lifetime is and multiple registrations diff --git a/src/EFCore.Relational/Query/IMemberTranslatorProvider.cs b/src/EFCore.Relational/Query/IMemberTranslatorProvider.cs index 9791f59c817..e7472f9c75e 100644 --- a/src/EFCore.Relational/Query/IMemberTranslatorProvider.cs +++ b/src/EFCore.Relational/Query/IMemberTranslatorProvider.cs @@ -24,13 +24,13 @@ namespace Microsoft.EntityFrameworkCore.Query public interface IMemberTranslatorProvider { /// - /// Translates a LINQ to a SQL equivalent. + /// Translates a LINQ to a SQL equivalent. /// - /// A SQL representation of . - /// The member info from . - /// The return type from . + /// A SQL representation of . + /// The member info from . + /// The return type from . /// The query logger to use. - /// A SQL translation of the . + /// A SQL translation of the . SqlExpression Translate( [CanBeNull] SqlExpression instance, [NotNull] MemberInfo member, diff --git a/src/EFCore.Relational/Query/IMethodCallTranslator.cs b/src/EFCore.Relational/Query/IMethodCallTranslator.cs index d2e0abe0d35..0397812c0fc 100644 --- a/src/EFCore.Relational/Query/IMethodCallTranslator.cs +++ b/src/EFCore.Relational/Query/IMethodCallTranslator.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; @@ -23,13 +22,13 @@ namespace Microsoft.EntityFrameworkCore.Query public interface IMethodCallTranslator { /// - /// Translates a LINQ to a SQL equivalent. + /// Translates a LINQ to a SQL equivalent. /// - /// A SQL representation of . - /// The method info from . - /// SQL representations of . + /// A SQL representation of . + /// The method info from . + /// SQL representations of . /// The query logger to use. - /// A SQL translation of the . + /// A SQL translation of the . SqlExpression Translate( [CanBeNull] SqlExpression instance, [NotNull] MethodInfo method, diff --git a/src/EFCore.Relational/Query/IMethodCallTranslatorPlugin.cs b/src/EFCore.Relational/Query/IMethodCallTranslatorPlugin.cs index 2fa68c47519..456373b8714 100644 --- a/src/EFCore.Relational/Query/IMethodCallTranslatorPlugin.cs +++ b/src/EFCore.Relational/Query/IMethodCallTranslatorPlugin.cs @@ -8,7 +8,7 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// Represents plugin for . + /// Represents plugin for . /// /// /// The service lifetime is and multiple registrations diff --git a/src/EFCore.Relational/Query/IMethodCallTranslatorProvider.cs b/src/EFCore.Relational/Query/IMethodCallTranslatorProvider.cs index 358d4f83d9f..ae1c8f1e503 100644 --- a/src/EFCore.Relational/Query/IMethodCallTranslatorProvider.cs +++ b/src/EFCore.Relational/Query/IMethodCallTranslatorProvider.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; @@ -15,7 +14,7 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// Provides translations for LINQ expressions. + /// Provides translations for LINQ expressions. /// /// /// The service lifetime is . This means a single instance @@ -26,14 +25,14 @@ namespace Microsoft.EntityFrameworkCore.Query public interface IMethodCallTranslatorProvider { /// - /// Translates a LINQ to a SQL equivalent. + /// Translates a LINQ to a SQL equivalent. /// /// A model to use for translation. - /// A SQL representation of . - /// The method info from . - /// SQL representations of . + /// A SQL representation of . + /// The method info from . + /// SQL representations of . /// The query logger to use. - /// A SQL translation of the . + /// A SQL translation of the . SqlExpression Translate( [NotNull] IModel model, [CanBeNull] SqlExpression instance, diff --git a/src/EFCore.Relational/Query/IQuerySqlGeneratorFactory.cs b/src/EFCore.Relational/Query/IQuerySqlGeneratorFactory.cs index 79f5d1a62b9..2f440247de3 100644 --- a/src/EFCore.Relational/Query/IQuerySqlGeneratorFactory.cs +++ b/src/EFCore.Relational/Query/IQuerySqlGeneratorFactory.cs @@ -18,7 +18,7 @@ namespace Microsoft.EntityFrameworkCore.Query public interface IQuerySqlGeneratorFactory { /// - /// Creates a new . + /// Creates a new . /// /// A SQL generator. QuerySqlGenerator Create(); diff --git a/src/EFCore.Relational/Query/IRelationalParameterBasedSqlProcessorFactory.cs b/src/EFCore.Relational/Query/IRelationalParameterBasedSqlProcessorFactory.cs index 8c90a0ffb9f..668ca42505f 100644 --- a/src/EFCore.Relational/Query/IRelationalParameterBasedSqlProcessorFactory.cs +++ b/src/EFCore.Relational/Query/IRelationalParameterBasedSqlProcessorFactory.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using Microsoft.EntityFrameworkCore.Query.SqlExpressions; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.EntityFrameworkCore.Query @@ -19,7 +18,7 @@ namespace Microsoft.EntityFrameworkCore.Query public interface IRelationalParameterBasedSqlProcessorFactory { /// - /// Creates a new . + /// Creates a new . /// /// A bool value indicating if relational nulls should be used. /// A relational parameter based sql processor. diff --git a/src/EFCore.Relational/Query/IRelationalSqlTranslatingExpressionVisitorFactory.cs b/src/EFCore.Relational/Query/IRelationalSqlTranslatingExpressionVisitorFactory.cs index b8a62d8554a..78911f96a93 100644 --- a/src/EFCore.Relational/Query/IRelationalSqlTranslatingExpressionVisitorFactory.cs +++ b/src/EFCore.Relational/Query/IRelationalSqlTranslatingExpressionVisitorFactory.cs @@ -19,7 +19,7 @@ namespace Microsoft.EntityFrameworkCore.Query public interface IRelationalSqlTranslatingExpressionVisitorFactory { /// - /// Creates a new . + /// Creates a new . /// /// The query compilation context to use. /// The visitor to use to translate subqueries. diff --git a/src/EFCore.Relational/Query/ISqlExpressionFactory.cs b/src/EFCore.Relational/Query/ISqlExpressionFactory.cs index 3f4bf69802b..d233cc655d7 100644 --- a/src/EFCore.Relational/Query/ISqlExpressionFactory.cs +++ b/src/EFCore.Relational/Query/ISqlExpressionFactory.cs @@ -31,6 +31,7 @@ public interface ISqlExpressionFactory /// The type mapping to be used. [Obsolete("Use IRelationalTypeMappingSource directly.")] RelationalTypeMapping GetTypeMappingForValue([CanBeNull] object value); + /// /// Finds the type mapping for a given . /// @@ -38,28 +39,30 @@ public interface ISqlExpressionFactory /// The type mapping, or if none was found. [Obsolete("Use IRelationalTypeMappingSource directly.")] RelationalTypeMapping FindMapping([NotNull] Type type); + /// - /// Applies type mapping to the given . + /// Applies type mapping to the given . /// /// A SQL expression to apply type mapping. /// A type mapping to apply. /// A SQL expression with given type mapping applied. SqlExpression ApplyTypeMapping([CanBeNull] SqlExpression sqlExpression, [CanBeNull] RelationalTypeMapping typeMapping); + /// - /// Applies default type mapping to given . + /// Applies default type mapping to given . /// /// A SQL Expression to apply default type mapping. /// A SQL expression with default type mapping applied. SqlExpression ApplyDefaultTypeMapping([CanBeNull] SqlExpression sqlExpression); /// - /// Creates a new with the given arguments. + /// Creates a new with the given arguments. /// - /// An reprenting SQL unary operator. - /// A to apply unary operator on. + /// An reprenting SQL unary operator. + /// A to apply unary operator on. /// The type of the created expression. /// A type mapping to be assigned to the created expression. - /// A with the given arguments. + /// A with the given arguments. SqlUnaryExpression MakeUnary( ExpressionType operatorType, [NotNull] SqlExpression operand, @@ -67,13 +70,13 @@ SqlUnaryExpression MakeUnary( [CanBeNull] RelationalTypeMapping typeMapping = null); /// - /// Creates a new with the given arguments. + /// Creates a new with the given arguments. /// - /// An reprenting SQL unary operator. + /// An reprenting SQL unary operator. /// The left operand of binary operation. /// The right operand of binary operation. /// A type mapping to be assigned to the created expression. - /// A with the given arguments. + /// A with the given arguments. SqlBinaryExpression MakeBinary( ExpressionType operatorType, [NotNull] SqlExpression left, @@ -82,7 +85,7 @@ SqlBinaryExpression MakeBinary( // Comparison /// - /// Creates a which represents an equality comparison. + /// Creates a which represents an equality comparison. /// /// The left operand. /// The right operand. @@ -90,7 +93,7 @@ SqlBinaryExpression MakeBinary( SqlBinaryExpression Equal([NotNull] SqlExpression left, [NotNull] SqlExpression right); /// - /// Creates a which represents an inequality comparison. + /// Creates a which represents an inequality comparison. /// /// The left operand. /// The right operand. @@ -98,7 +101,7 @@ SqlBinaryExpression MakeBinary( SqlBinaryExpression NotEqual([NotNull] SqlExpression left, [NotNull] SqlExpression right); /// - /// Creates a which represents a greater than comparison. + /// Creates a which represents a greater than comparison. /// /// The left operand. /// The right operand. @@ -106,7 +109,7 @@ SqlBinaryExpression MakeBinary( SqlBinaryExpression GreaterThan([NotNull] SqlExpression left, [NotNull] SqlExpression right); /// - /// Creates a which represents a greater than or equal comparison. + /// Creates a which represents a greater than or equal comparison. /// /// The left operand. /// The right operand. @@ -114,7 +117,7 @@ SqlBinaryExpression MakeBinary( SqlBinaryExpression GreaterThanOrEqual([NotNull] SqlExpression left, [NotNull] SqlExpression right); /// - /// Creates a which represents a less than comparison. + /// Creates a which represents a less than comparison. /// /// The left operand. /// The right operand. @@ -122,7 +125,7 @@ SqlBinaryExpression MakeBinary( SqlBinaryExpression LessThan([NotNull] SqlExpression left, [NotNull] SqlExpression right); /// - /// Creates a which represents a less than or equal comparison. + /// Creates a which represents a less than or equal comparison. /// /// The left operand. /// The right operand. @@ -131,7 +134,7 @@ SqlBinaryExpression MakeBinary( // Logical /// - /// Creates a which represents a logical AND operation. + /// Creates a which represents a logical AND operation. /// /// The left operand. /// The right operand. @@ -139,7 +142,7 @@ SqlBinaryExpression MakeBinary( SqlBinaryExpression AndAlso([NotNull] SqlExpression left, [NotNull] SqlExpression right); /// - /// Creates a which represents a logical OR operation. + /// Creates a which represents a logical OR operation. /// /// The left operand. /// The right operand. @@ -148,148 +151,169 @@ SqlBinaryExpression MakeBinary( // Arithmetic /// - /// Creates a which represents an addition. + /// Creates a which represents an addition. /// /// The left operand. /// The right operand. /// A type mapping to be assigned to the created expression. /// An expression representing a SQL addition. SqlBinaryExpression Add( - [NotNull] SqlExpression left, [NotNull] SqlExpression right, [CanBeNull] RelationalTypeMapping typeMapping = null); + [NotNull] SqlExpression left, + [NotNull] SqlExpression right, + [CanBeNull] RelationalTypeMapping typeMapping = null); /// - /// Creates a which represents a subtraction. + /// Creates a which represents a subtraction. /// /// The left operand. /// The right operand. /// A type mapping to be assigned to the created expression. /// An expression representing a SQL subtraction. SqlBinaryExpression Subtract( - [NotNull] SqlExpression left, [NotNull] SqlExpression right, [CanBeNull] RelationalTypeMapping typeMapping = null); + [NotNull] SqlExpression left, + [NotNull] SqlExpression right, + [CanBeNull] RelationalTypeMapping typeMapping = null); /// - /// Creates a which represents a multiplication. + /// Creates a which represents a multiplication. /// /// The left operand. /// The right operand. /// A type mapping to be assigned to the created expression. /// An expression representing a SQL multiplication. SqlBinaryExpression Multiply( - [NotNull] SqlExpression left, [NotNull] SqlExpression right, [CanBeNull] RelationalTypeMapping typeMapping = null); + [NotNull] SqlExpression left, + [NotNull] SqlExpression right, + [CanBeNull] RelationalTypeMapping typeMapping = null); /// - /// Creates a which represents a division. + /// Creates a which represents a division. /// /// The left operand. /// The right operand. /// A type mapping to be assigned to the created expression. /// An expression representing a SQL division. SqlBinaryExpression Divide( - [NotNull] SqlExpression left, [NotNull] SqlExpression right, [CanBeNull] RelationalTypeMapping typeMapping = null); + [NotNull] SqlExpression left, + [NotNull] SqlExpression right, + [CanBeNull] RelationalTypeMapping typeMapping = null); /// - /// Creates a which represents a modulo operation. + /// Creates a which represents a modulo operation. /// /// The left operand. /// The right operand. /// A type mapping to be assigned to the created expression. /// An expression representing a SQL modulo operation. SqlBinaryExpression Modulo( - [NotNull] SqlExpression left, [NotNull] SqlExpression right, [CanBeNull] RelationalTypeMapping typeMapping = null); + [NotNull] SqlExpression left, + [NotNull] SqlExpression right, + [CanBeNull] RelationalTypeMapping typeMapping = null); // Bitwise /// - /// Creates a which represents a bitwise AND operation. + /// Creates a which represents a bitwise AND operation. /// /// The left operand. /// The right operand. /// A type mapping to be assigned to the created expression. /// An expression representing a SQL bitwise AND operation. SqlBinaryExpression And( - [NotNull] SqlExpression left, [NotNull] SqlExpression right, [CanBeNull] RelationalTypeMapping typeMapping = null); + [NotNull] SqlExpression left, + [NotNull] SqlExpression right, + [CanBeNull] RelationalTypeMapping typeMapping = null); /// - /// Creates a which represents a bitwise OR operation. + /// Creates a which represents a bitwise OR operation. /// /// The left operand. /// The right operand. /// A type mapping to be assigned to the created expression. /// An expression representing a SQL bitwise OR operation. SqlBinaryExpression Or( - [NotNull] SqlExpression left, [NotNull] SqlExpression right, [CanBeNull] RelationalTypeMapping typeMapping = null); + [NotNull] SqlExpression left, + [NotNull] SqlExpression right, + [CanBeNull] RelationalTypeMapping typeMapping = null); // Other /// - /// Creates a which represents a bitwise OR operation. + /// Creates a which represents a bitwise OR operation. /// /// The left operand. /// The right operand. /// A type mapping to be assigned to the created expression. /// An expression representing a SQL bitwise OR operation. SqlFunctionExpression Coalesce( - [NotNull] SqlExpression left, [NotNull] SqlExpression right, [CanBeNull] RelationalTypeMapping typeMapping = null); + [NotNull] SqlExpression left, + [NotNull] SqlExpression right, + [CanBeNull] RelationalTypeMapping typeMapping = null); /// - /// Creates a new which represent equality to null. + /// Creates a new which represent equality to null. /// - /// A to compare to null. + /// A to compare to null. /// An expression representing IS NULL construct in a SQL tree. SqlUnaryExpression IsNull([NotNull] SqlExpression operand); /// - /// Creates a new which represent inequality to null. + /// Creates a new which represent inequality to null. /// - /// A to compare to non null. + /// A to compare to non null. /// An expression representing IS NOT NULL construct in a SQL tree. SqlUnaryExpression IsNotNull([NotNull] SqlExpression operand); /// - /// Creates a new which represent casting a SQL expression to different type. + /// Creates a new which represent casting a SQL expression to different type. /// - /// A to cast. + /// A to cast. /// The return type of the expression after cast. /// A relational type mapping to use for conversion. /// An expression representing cast operation in a SQL tree. SqlUnaryExpression Convert( - [NotNull] SqlExpression operand, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping = null); + [NotNull] SqlExpression operand, + [NotNull] Type type, + [CanBeNull] RelationalTypeMapping typeMapping = null); /// - /// Creates a new which represent a NOT operation in a SQL tree. + /// Creates a new which represent a NOT operation in a SQL tree. /// - /// A to apply NOT on. + /// A to apply NOT on. /// An expression representing a NOT operation in a SQL tree. SqlUnaryExpression Not([NotNull] SqlExpression operand); /// - /// Creates a new which represent a negation operation in a SQL tree. + /// Creates a new which represent a negation operation in a SQL tree. /// - /// A to apply NOT on. + /// A to apply NOT on. /// An expression representing a negation operation in a SQL tree. SqlUnaryExpression Negate([NotNull] SqlExpression operand); /// - /// Creates a new which represent a CASE statement in a SQL tree. + /// Creates a new which represent a CASE statement in a SQL tree. /// - /// An expression to compare with in . - /// A list of to compare and get result from. + /// An expression to compare with in . + /// A list of to compare and get result from. /// An expression representing a CASE statement in a SQL tree. [Obsolete("Use overload which takes IReadOnlyList instead of params")] CaseExpression Case([NotNull] SqlExpression operand, [NotNull] params CaseWhenClause[] whenClauses); /// - /// Creates a new which represent a CASE statement in a SQL tree. + /// Creates a new which represent a CASE statement in a SQL tree. /// - /// An expression to compare with in . - /// A list of to compare and get result from. - /// A value to return if no matches, if any. + /// An expression to compare with in . + /// A list of to compare and get result from. + /// A value to return if no matches, if any. /// An expression representing a CASE statement in a SQL tree. - CaseExpression Case([NotNull] SqlExpression operand, [NotNull] IReadOnlyList whenClauses, [CanBeNull] SqlExpression elseResult); + CaseExpression Case( + [NotNull] SqlExpression operand, + [NotNull] IReadOnlyList whenClauses, + [CanBeNull] SqlExpression elseResult); /// - /// Creates a new which represent a CASE statement in a SQL tree. + /// Creates a new which represent a CASE statement in a SQL tree. /// - /// A list of to evaluate condition and get result from. - /// A value to return if no matches, if any. + /// A list of to evaluate condition and get result from. + /// A value to return if no matches, if any. /// An expression representing a CASE statement in a SQL tree. CaseExpression Case([NotNull] IReadOnlyList whenClauses, [CanBeNull] SqlExpression elseResult); @@ -298,8 +322,8 @@ SqlUnaryExpression Convert( /// /// The name of the function. /// The arguments of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. [Obsolete("Use overload that explicitly specifies value for 'argumentsPropagateNullability' argument.")] SqlFunctionExpression Function( @@ -314,8 +338,8 @@ SqlFunctionExpression Function( /// The schema in which the function is defined. /// The name of the function. /// The arguments of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. [Obsolete("Use overload that explicitly specifies value for 'argumentsPropagateNullability' argument.")] SqlFunctionExpression Function( @@ -331,10 +355,11 @@ SqlFunctionExpression Function( /// An expression on which the function is applied. /// The name of the function. /// The arguments of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. - [Obsolete("Use overload that explicitly specifies value for 'instancePropagatesNullability' and 'argumentsPropagateNullability' arguments.")] + [Obsolete( + "Use overload that explicitly specifies value for 'instancePropagatesNullability' and 'argumentsPropagateNullability' arguments.")] SqlFunctionExpression Function( [NotNull] SqlExpression instance, [NotNull] string name, @@ -346,8 +371,8 @@ SqlFunctionExpression Function( /// Creates a new which represents a function call in a SQL tree. /// /// The name of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. [Obsolete("Use NiladicFunction method.")] SqlFunctionExpression Function( @@ -360,8 +385,8 @@ SqlFunctionExpression Function( /// /// The schema in which the function is defined. /// The name of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. [Obsolete("Use NiladicFunction method.")] SqlFunctionExpression Function( @@ -375,8 +400,8 @@ SqlFunctionExpression Function( /// /// An expression on which the function is applied. /// The name of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. [Obsolete("Use NiladicFunction method.")] SqlFunctionExpression Function( @@ -392,8 +417,8 @@ SqlFunctionExpression Function( /// The arguments of the function. /// A bool value indicating whether this function can return null. /// A list of bool values indicating whether individual arguments propagate null to result. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. SqlFunctionExpression Function( [NotNull] string name, @@ -411,8 +436,8 @@ SqlFunctionExpression Function( /// The arguments of the function. /// A bool value indicating whether this function can return null. /// A list of bool values indicating whether individual arguments propagate null to result. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. SqlFunctionExpression Function( [NotNull] string schema, @@ -432,8 +457,8 @@ SqlFunctionExpression Function( /// A bool value indicating whether this function can return null. /// A value indicating if instance propagates null to result. /// A list of bool values indicating whether individual arguments propagate null to result. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. SqlFunctionExpression Function( [NotNull] SqlExpression instance, @@ -450,8 +475,8 @@ SqlFunctionExpression Function( /// /// The name of the function. /// A bool value indicating whether this function can return null. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. SqlFunctionExpression NiladicFunction( [NotNull] string name, @@ -465,8 +490,8 @@ SqlFunctionExpression NiladicFunction( /// The schema in which the function is defined. /// The name of the function. /// A bool value indicating whether this function can return null. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. SqlFunctionExpression NiladicFunction( [NotNull] string schema, @@ -482,8 +507,8 @@ SqlFunctionExpression NiladicFunction( /// The name of the function. /// A bool value indicating whether this function can return null. /// A value indicating if instance propagates null to result. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. /// An expression representing a function call in a SQL tree. SqlFunctionExpression NiladicFunction( [NotNull] SqlExpression instance, @@ -532,7 +557,7 @@ SqlFunctionExpression NiladicFunction( /// Creates a new which represents a constant in a SQL tree. /// /// A value. - /// The associated with the expression. + /// The associated with the expression. /// An expression representing a LIKE in a SQL tree. SqlConstantExpression Constant([NotNull] object value, [CanBeNull] RelationalTypeMapping typeMapping = null); @@ -544,10 +569,10 @@ SqlFunctionExpression NiladicFunction( SqlFragmentExpression Fragment([NotNull] string sql); /// - /// Creates a new which represents a SELECT in a SQL tree projecting a + /// Creates a new which represents a SELECT in a SQL tree projecting a /// or 1 from no table and without any composition. /// - /// A to project. + /// A to project. /// An expression representing a SELECT in a SQL tree. SelectExpression Select([CanBeNull] SqlExpression projection); diff --git a/src/EFCore.Relational/Query/Internal/BufferedDataReader.cs b/src/EFCore.Relational/Query/Internal/BufferedDataReader.cs index b34b4a815b2..3c028eaf7bd 100644 --- a/src/EFCore.Relational/Query/Internal/BufferedDataReader.cs +++ b/src/EFCore.Relational/Query/Internal/BufferedDataReader.cs @@ -50,7 +50,8 @@ public BufferedDataReader([NotNull] DbDataReader reader) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override int RecordsAffected => _recordsAffected; + public override int RecordsAffected + => _recordsAffected; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -58,7 +59,8 @@ public BufferedDataReader([NotNull] DbDataReader reader) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override object this[string name] => throw new NotSupportedException(); + public override object this[string name] + => throw new NotSupportedException(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -66,7 +68,8 @@ public BufferedDataReader([NotNull] DbDataReader reader) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override object this[int ordinal] => throw new NotSupportedException(); + public override object this[int ordinal] + => throw new NotSupportedException(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -74,7 +77,8 @@ public BufferedDataReader([NotNull] DbDataReader reader) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override int Depth => throw new NotSupportedException(); + public override int Depth + => throw new NotSupportedException(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -112,7 +116,8 @@ public override bool HasRows /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override bool IsClosed => _isClosed; + public override bool IsClosed + => _isClosed; [Conditional("DEBUG")] private void AssertReaderIsOpen() @@ -191,7 +196,8 @@ public virtual BufferedDataReader Initialize([NotNull] IReadOnlyList public virtual async Task InitializeAsync( - [NotNull] IReadOnlyList columns, CancellationToken cancellationToken) + [NotNull] IReadOnlyList columns, + CancellationToken cancellationToken) { if (_underlyingReader == null) { @@ -576,7 +582,8 @@ public override Task IsDBNullAsync(int ordinal, CancellationToken cancella /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override IEnumerator GetEnumerator() => throw new NotSupportedException(); + public override IEnumerator GetEnumerator() + => throw new NotSupportedException(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -584,7 +591,8 @@ public override Task IsDBNullAsync(int ordinal, CancellationToken cancella /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override DataTable GetSchemaTable() => throw new NotSupportedException(); + public override DataTable GetSchemaTable() + => throw new NotSupportedException(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -700,17 +708,23 @@ private sealed class BufferedDataRecord public bool IsDataReady { get; private set; } - public bool HasRows => _rowCount > 0; + public bool HasRows + => _rowCount > 0; - public int FieldCount => _fieldTypes.Length; + public int FieldCount + => _fieldTypes.Length; - public string GetDataTypeName(int ordinal) => _dataTypeNames[ordinal]; + public string GetDataTypeName(int ordinal) + => _dataTypeNames[ordinal]; - public Type GetFieldType(int ordinal) => _fieldTypes[ordinal]; + public Type GetFieldType(int ordinal) + => _fieldTypes[ordinal]; - public string GetName(int ordinal) => _columnNames[ordinal]; + public string GetName(int ordinal) + => _columnNames[ordinal]; - public int GetOrdinal(string name) => _fieldNameLookup.Value[name]; + public int GetOrdinal(string name) + => _fieldNameLookup.Value[name]; public bool GetBoolean(int ordinal) => _columnTypeCases[ordinal] == TypeCase.Bool @@ -844,13 +858,17 @@ public T GetFieldValue(int ordinal) public Task GetFieldValueAsync(int ordinal, CancellationToken cancellationToken) => Task.FromResult(GetFieldValue(ordinal)); - public bool IsDBNull(int ordinal) => _nulls[_currentRowNumber * _nullCount + _nullOrdinalToIndexMap[ordinal]]; + public bool IsDBNull(int ordinal) + => _nulls[_currentRowNumber * _nullCount + _nullOrdinalToIndexMap[ordinal]]; - public Task IsDBNullAsync(int ordinal, CancellationToken cancellationToken) => Task.FromResult(IsDBNull(ordinal)); + public Task IsDBNullAsync(int ordinal, CancellationToken cancellationToken) + => Task.FromResult(IsDBNull(ordinal)); - public bool Read() => IsDataReady = ++_currentRowNumber < _rowCount; + public bool Read() + => IsDataReady = ++_currentRowNumber < _rowCount; - public Task ReadAsync(CancellationToken cancellationToken) => Task.FromResult(Read()); + public Task ReadAsync(CancellationToken cancellationToken) + => Task.FromResult(Read()); public BufferedDataRecord Initialize([NotNull] DbDataReader reader, [NotNull] IReadOnlyList columns) { @@ -878,7 +896,9 @@ public BufferedDataRecord Initialize([NotNull] DbDataReader reader, [NotNull] IR } public async Task InitializeAsync( - [NotNull] DbDataReader reader, [NotNull] IReadOnlyList columns, CancellationToken cancellationToken) + [NotNull] DbDataReader reader, + [NotNull] IReadOnlyList columns, + CancellationToken cancellationToken) { _underlyingReader = reader; _columns = columns; @@ -1232,6 +1252,7 @@ private void InitializeFields() { newColumnMap[i] = _columns[i]; } + _columns = newColumnMap; } diff --git a/src/EFCore.Relational/Query/Internal/ByteArraySequenceEqualTranslator.cs b/src/EFCore.Relational/Query/Internal/ByteArraySequenceEqualTranslator.cs index fbe3e918304..9d354385890 100644 --- a/src/EFCore.Relational/Query/Internal/ByteArraySequenceEqualTranslator.cs +++ b/src/EFCore.Relational/Query/Internal/ByteArraySequenceEqualTranslator.cs @@ -16,7 +16,7 @@ namespace Microsoft.EntityFrameworkCore.Query.Internal /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public class ByteArraySequenceEqualTranslator: IMethodCallTranslator + public class ByteArraySequenceEqualTranslator : IMethodCallTranslator { private readonly ISqlExpressionFactory _sqlExpressionFactory; diff --git a/src/EFCore.Relational/Query/Internal/CollectionJoinApplyingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/CollectionJoinApplyingExpressionVisitor.cs index 6d8617c0252..2cce355400d 100644 --- a/src/EFCore.Relational/Query/Internal/CollectionJoinApplyingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/CollectionJoinApplyingExpressionVisitor.cs @@ -82,10 +82,11 @@ protected override Expression VisitExtension(Expression extensionExpression) if (_splitQuery && collectionJoin == null) { - throw new InvalidOperationException(RelationalStrings.UnableToSplitCollectionProjectionInSplitQuery( - $"{nameof(QuerySplittingBehavior)}.{QuerySplittingBehavior.SplitQuery}", - nameof(RelationalQueryableExtensions.AsSplitQuery), - nameof(RelationalQueryableExtensions.AsSingleQuery))); + throw new InvalidOperationException( + RelationalStrings.UnableToSplitCollectionProjectionInSplitQuery( + $"{nameof(QuerySplittingBehavior)}.{QuerySplittingBehavior.SplitQuery}", + nameof(RelationalQueryableExtensions.AsSplitQuery), + nameof(RelationalQueryableExtensions.AsSingleQuery))); } return collectionJoin; diff --git a/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs b/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs index 89528ca4dd1..66a6e6169d4 100644 --- a/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs +++ b/src/EFCore.Relational/Query/Internal/ContainsTranslator.cs @@ -72,7 +72,7 @@ private SqlExpression RemoveObjectConvert(SqlExpression expression) => expression is SqlUnaryExpression sqlUnaryExpression && sqlUnaryExpression.OperatorType == ExpressionType.Convert && sqlUnaryExpression.Type == typeof(object) - ? sqlUnaryExpression.Operand - : expression; + ? sqlUnaryExpression.Operand + : expression; } } diff --git a/src/EFCore.Relational/Query/Internal/EqualsTranslator.cs b/src/EFCore.Relational/Query/Internal/EqualsTranslator.cs index d47cfae56f9..23cbfc6ce91 100644 --- a/src/EFCore.Relational/Query/Internal/EqualsTranslator.cs +++ b/src/EFCore.Relational/Query/Internal/EqualsTranslator.cs @@ -1,9 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; -using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; diff --git a/src/EFCore.Relational/Query/Internal/FromSqlParameterExpandingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/FromSqlParameterExpandingExpressionVisitor.cs index bcb943cdef3..a0aafb5a51f 100644 --- a/src/EFCore.Relational/Query/Internal/FromSqlParameterExpandingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/FromSqlParameterExpandingExpressionVisitor.cs @@ -56,7 +56,9 @@ public FromSqlParameterExpandingExpressionVisitor( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual SelectExpression Expand( - [NotNull] SelectExpression selectExpression, [NotNull] IReadOnlyDictionary parameterValues, out bool canCache) + [NotNull] SelectExpression selectExpression, + [NotNull] IReadOnlyDictionary parameterValues, + out bool canCache) { Check.NotNull(selectExpression, nameof(selectExpression)); Check.NotNull(parameterValues, nameof(parameterValues)); @@ -119,7 +121,8 @@ public override Expression Visit(Expression expression) } } - updatedFromSql = fromSql.Update(Expression.Constant(new CompositeRelationalParameter(parameterExpression.Name, subParameters))); + updatedFromSql = fromSql.Update( + Expression.Constant(new CompositeRelationalParameter(parameterExpression.Name, subParameters))); _visitedFromSqlExpressions[fromSql] = updatedFromSql; break; diff --git a/src/EFCore.Relational/Query/Internal/FromSqlQueryRootExpression.cs b/src/EFCore.Relational/Query/Internal/FromSqlQueryRootExpression.cs index e8ced000d99..6fb91b1586b 100644 --- a/src/EFCore.Relational/Query/Internal/FromSqlQueryRootExpression.cs +++ b/src/EFCore.Relational/Query/Internal/FromSqlQueryRootExpression.cs @@ -24,7 +24,10 @@ public class FromSqlQueryRootExpression : QueryRootExpression /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public FromSqlQueryRootExpression( - [NotNull] IAsyncQueryProvider queryProvider, [NotNull] IEntityType entityType, [NotNull] string sql, [NotNull] Expression argument) + [NotNull] IAsyncQueryProvider queryProvider, + [NotNull] IEntityType entityType, + [NotNull] string sql, + [NotNull] Expression argument) : base(queryProvider, entityType) { Check.NotEmpty(sql, nameof(sql)); @@ -41,7 +44,9 @@ public FromSqlQueryRootExpression( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public FromSqlQueryRootExpression( - [NotNull] IEntityType entityType, [NotNull] string sql, [NotNull] Expression argument) + [NotNull] IEntityType entityType, + [NotNull] string sql, + [NotNull] Expression argument) : base(entityType) { Check.NotEmpty(sql, nameof(sql)); @@ -58,6 +63,7 @@ public FromSqlQueryRootExpression( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual string Sql { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -72,7 +78,8 @@ public FromSqlQueryRootExpression( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override Expression DetachQueryProvider() => new FromSqlQueryRootExpression(EntityType, Sql, Argument); + public override Expression DetachQueryProvider() + => new FromSqlQueryRootExpression(EntityType, Sql, Argument); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to diff --git a/src/EFCore.Relational/Query/Internal/FromSqlQueryingEnumerable.cs b/src/EFCore.Relational/Query/Internal/FromSqlQueryingEnumerable.cs index 9b8be9102cf..d6e7d04e3de 100644 --- a/src/EFCore.Relational/Query/Internal/FromSqlQueryingEnumerable.cs +++ b/src/EFCore.Relational/Query/Internal/FromSqlQueryingEnumerable.cs @@ -69,7 +69,8 @@ public virtual IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancella /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual IEnumerator GetEnumerator() => new Enumerator(this); + public virtual IEnumerator GetEnumerator() + => new Enumerator(this); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -77,7 +78,8 @@ public virtual IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancella /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + => GetEnumerator(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -159,7 +161,8 @@ public Enumerator(FromSqlQueryingEnumerable queryingEnumerable) public T Current { get; private set; } - object IEnumerator.Current => Current; + object IEnumerator.Current + => Current; public bool MoveNext() { @@ -218,7 +221,8 @@ public void Dispose() _dataReader = null; } - public void Reset() => throw new NotImplementedException(); + public void Reset() + => throw new NotImplementedException(); } private sealed class AsyncEnumerator : IAsyncEnumerator @@ -288,14 +292,14 @@ private async Task InitializeReaderAsync(DbContext _, bool result, Cancell _dataReader = await relationalCommand.ExecuteReaderAsync( - new RelationalCommandParameterObject( - _relationalQueryContext.Connection, - _relationalQueryContext.ParameterValues, - _relationalCommandCache.ReaderColumns, - _relationalQueryContext.Context, - _relationalQueryContext.CommandLogger), - cancellationToken) - .ConfigureAwait(false); + new RelationalCommandParameterObject( + _relationalQueryContext.Connection, + _relationalQueryContext.ParameterValues, + _relationalCommandCache.ReaderColumns, + _relationalQueryContext.Context, + _relationalQueryContext.CommandLogger), + cancellationToken) + .ConfigureAwait(false); _indexMap = BuildIndexMap(_columnNames, _dataReader.DbDataReader); diff --git a/src/EFCore.Relational/Query/Internal/GetValueOrDefaultTranslator.cs b/src/EFCore.Relational/Query/Internal/GetValueOrDefaultTranslator.cs index 2820847d952..a89ca66c151 100644 --- a/src/EFCore.Relational/Query/Internal/GetValueOrDefaultTranslator.cs +++ b/src/EFCore.Relational/Query/Internal/GetValueOrDefaultTranslator.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; diff --git a/src/EFCore.Relational/Query/Internal/NullableMemberTranslator.cs b/src/EFCore.Relational/Query/Internal/NullableMemberTranslator.cs index f093453569e..fbd4176fd09 100644 --- a/src/EFCore.Relational/Query/Internal/NullableMemberTranslator.cs +++ b/src/EFCore.Relational/Query/Internal/NullableMemberTranslator.cs @@ -38,7 +38,10 @@ public NullableMemberTranslator([NotNull] ISqlExpressionFactory sqlExpressionFac /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual SqlExpression Translate( - SqlExpression instance, MemberInfo member, Type returnType, IDiagnosticsLogger logger) + SqlExpression instance, + MemberInfo member, + Type returnType, + IDiagnosticsLogger logger) { Check.NotNull(member, nameof(member)); Check.NotNull(returnType, nameof(returnType)); diff --git a/src/EFCore.Relational/Query/Internal/RelationalCommandCache.cs b/src/EFCore.Relational/Query/Internal/RelationalCommandCache.cs index 7a891bc16b4..0a8e9a23692 100644 --- a/src/EFCore.Relational/Query/Internal/RelationalCommandCache.cs +++ b/src/EFCore.Relational/Query/Internal/RelationalCommandCache.cs @@ -168,7 +168,8 @@ public bool Equals(CommandCacheKey commandCacheKey) return true; } - public override int GetHashCode() => 0; + public override int GetHashCode() + => 0; } } } diff --git a/src/EFCore.Relational/Query/Internal/RelationalParameterBasedSqlProcessorFactory.cs b/src/EFCore.Relational/Query/Internal/RelationalParameterBasedSqlProcessorFactory.cs index a8d97b7381a..e0568526184 100644 --- a/src/EFCore.Relational/Query/Internal/RelationalParameterBasedSqlProcessorFactory.cs +++ b/src/EFCore.Relational/Query/Internal/RelationalParameterBasedSqlProcessorFactory.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using JetBrains.Annotations; -using Microsoft.EntityFrameworkCore.Query.SqlExpressions; using Microsoft.EntityFrameworkCore.Utilities; using Microsoft.Extensions.DependencyInjection; diff --git a/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs index 34c41454752..79907a9b2fc 100644 --- a/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/RelationalProjectionBindingExpressionVisitor.cs @@ -148,7 +148,8 @@ public override Expression Visit(Expression expression) throw new InvalidOperationException(CoreStrings.TranslationFailed(projectionBindingExpression.Print())); case ParameterExpression parameterExpression: - if (parameterExpression.Name?.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal) == true) + if (parameterExpression.Name?.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal) + == true) { return Expression.Call( _getParameterValueMethodInfo.MakeGenericMethod(parameterExpression.Type), @@ -328,7 +329,8 @@ protected override Expression VisitExtension(Expression extensionExpression) if (_clientEval) { return entityShaperExpression.Update( - new ProjectionBindingExpression(_selectExpression, _selectExpression.AddToProjection(entityProjectionExpression))); + new ProjectionBindingExpression( + _selectExpression, _selectExpression.AddToProjection(entityProjectionExpression))); } _projectionMapping[_projectionMembers.Peek()] = entityProjectionExpression; @@ -562,10 +564,10 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) var operand = Visit(unaryExpression.Operand); return (unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked) + || unaryExpression.NodeType == ExpressionType.ConvertChecked) && unaryExpression.Type == operand.Type - ? operand - : unaryExpression.Update(MatchTypes(operand, unaryExpression.Operand.Type)); + ? operand + : unaryExpression.Update(MatchTypes(operand, unaryExpression.Operand.Type)); } // TODO: Debugging @@ -608,7 +610,8 @@ public bool ContainsInclude(Expression expression) return _containsInclude; } - public override Expression Visit(Expression expression) => _containsInclude ? expression : base.Visit(expression); + public override Expression Visit(Expression expression) + => _containsInclude ? expression : base.Visit(expression); protected override Expression VisitExtension(Expression extensionExpression) { diff --git a/src/EFCore.Relational/Query/Internal/RelationalQueryCompilationContextFactory.cs b/src/EFCore.Relational/Query/Internal/RelationalQueryCompilationContextFactory.cs index 2023a6dcb1c..58803ae45ee 100644 --- a/src/EFCore.Relational/Query/Internal/RelationalQueryCompilationContextFactory.cs +++ b/src/EFCore.Relational/Query/Internal/RelationalQueryCompilationContextFactory.cs @@ -53,4 +53,3 @@ public virtual QueryCompilationContext Create(bool async) => new RelationalQueryCompilationContext(_dependencies, _relationalDependencies, async); } } - diff --git a/src/EFCore.Relational/Query/Internal/RelationalQueryMetadataExtractingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/RelationalQueryMetadataExtractingExpressionVisitor.cs index 7214819f364..474d5fb1565 100644 --- a/src/EFCore.Relational/Query/Internal/RelationalQueryMetadataExtractingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/RelationalQueryMetadataExtractingExpressionVisitor.cs @@ -23,7 +23,8 @@ public class RelationalQueryMetadataExtractingExpressionVisitor : ExpressionVisi /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public RelationalQueryMetadataExtractingExpressionVisitor([NotNull] RelationalQueryCompilationContext relationalQueryCompilationContext) + public RelationalQueryMetadataExtractingExpressionVisitor( + [NotNull] RelationalQueryCompilationContext relationalQueryCompilationContext) { Check.NotNull(relationalQueryCompilationContext, nameof(relationalQueryCompilationContext)); diff --git a/src/EFCore.Relational/Query/Internal/SingleQueryCollectionContext.cs b/src/EFCore.Relational/Query/Internal/SingleQueryCollectionContext.cs index 79d197fba5a..bd764db8394 100644 --- a/src/EFCore.Relational/Query/Internal/SingleQueryCollectionContext.cs +++ b/src/EFCore.Relational/Query/Internal/SingleQueryCollectionContext.cs @@ -39,6 +39,7 @@ public SingleQueryCollectionContext( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual ResultContext ResultContext { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -46,6 +47,7 @@ public SingleQueryCollectionContext( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual object Parent { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -53,6 +55,7 @@ public SingleQueryCollectionContext( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual object Collection { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -60,6 +63,7 @@ public SingleQueryCollectionContext( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual object[] ParentIdentifier { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -67,6 +71,7 @@ public SingleQueryCollectionContext( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual object[] OuterIdentifier { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in diff --git a/src/EFCore.Relational/Query/Internal/SingleQueryResultCoordinator.cs b/src/EFCore.Relational/Query/Internal/SingleQueryResultCoordinator.cs index 7896802af69..f23908c949a 100644 --- a/src/EFCore.Relational/Query/Internal/SingleQueryResultCoordinator.cs +++ b/src/EFCore.Relational/Query/Internal/SingleQueryResultCoordinator.cs @@ -32,6 +32,7 @@ public SingleQueryResultCoordinator() /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual ResultContext ResultContext { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -39,6 +40,7 @@ public SingleQueryResultCoordinator() /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual bool ResultReady { get; set; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -46,6 +48,7 @@ public SingleQueryResultCoordinator() /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual bool? HasNext { get; set; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -61,7 +64,8 @@ public SingleQueryResultCoordinator() /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual void SetSingleQueryCollectionContext( - int collectionId, [NotNull] SingleQueryCollectionContext singleQueryCollectionContext) + int collectionId, + [NotNull] SingleQueryCollectionContext singleQueryCollectionContext) { while (Collections.Count <= collectionId) { diff --git a/src/EFCore.Relational/Query/Internal/SingleQueryingEnumerable.cs b/src/EFCore.Relational/Query/Internal/SingleQueryingEnumerable.cs index 4df26672b7d..49c4722f993 100644 --- a/src/EFCore.Relational/Query/Internal/SingleQueryingEnumerable.cs +++ b/src/EFCore.Relational/Query/Internal/SingleQueryingEnumerable.cs @@ -65,7 +65,8 @@ public virtual IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancella /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual IEnumerator GetEnumerator() => new Enumerator(this); + public virtual IEnumerator GetEnumerator() + => new Enumerator(this); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -73,7 +74,8 @@ public virtual IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancella /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + => GetEnumerator(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -127,7 +129,8 @@ public Enumerator(SingleQueryingEnumerable queryingEnumerable) public T Current { get; private set; } - object IEnumerator.Current => Current; + object IEnumerator.Current + => Current; public bool MoveNext() { @@ -151,7 +154,8 @@ public bool MoveNext() _resultCoordinator.ResultReady = true; _resultCoordinator.HasNext = null; Current = _shaper( - _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); + _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, + _resultCoordinator); if (_resultCoordinator.ResultReady) { // We generated a result so null out previously stored values @@ -165,7 +169,8 @@ public bool MoveNext() // Enumeration has ended, materialize last element _resultCoordinator.ResultReady = true; Current = _shaper( - _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); + _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, + _resultCoordinator); break; } @@ -211,7 +216,8 @@ public void Dispose() _dataReader = null; } - public void Reset() => throw new NotImplementedException(); + public void Reset() + => throw new NotImplementedException(); } private sealed class AsyncEnumerator : IAsyncEnumerator @@ -265,7 +271,8 @@ await _relationalQueryContext.ExecutionStrategyFactory.Create() _resultCoordinator.ResultReady = true; _resultCoordinator.HasNext = null; Current = _shaper( - _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); + _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, + _resultCoordinator); if (_resultCoordinator.ResultReady) { // We generated a result so null out previously stored values @@ -279,7 +286,8 @@ await _relationalQueryContext.ExecutionStrategyFactory.Create() // Enumeration has ended, materialize last element _resultCoordinator.ResultReady = true; Current = _shaper( - _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); + _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, + _resultCoordinator); break; } @@ -305,13 +313,13 @@ private async Task InitializeReaderAsync(DbContext _, bool result, Cancell _dataReader = await relationalCommand.ExecuteReaderAsync( - new RelationalCommandParameterObject( - _relationalQueryContext.Connection, - _relationalQueryContext.ParameterValues, - _relationalCommandCache.ReaderColumns, - _relationalQueryContext.Context, - _relationalQueryContext.CommandLogger), - cancellationToken) + new RelationalCommandParameterObject( + _relationalQueryContext.Connection, + _relationalQueryContext.ParameterValues, + _relationalCommandCache.ReaderColumns, + _relationalQueryContext.Context, + _relationalQueryContext.CommandLogger), + cancellationToken) .ConfigureAwait(false); _resultCoordinator = new SingleQueryResultCoordinator(); diff --git a/src/EFCore.Relational/Query/Internal/SplitIncludeRewritingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/SplitIncludeRewritingExpressionVisitor.cs index 9ac6e86b60f..d0775af8709 100644 --- a/src/EFCore.Relational/Query/Internal/SplitIncludeRewritingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/SplitIncludeRewritingExpressionVisitor.cs @@ -16,16 +16,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Internal /// public class SplitIncludeRewritingExpressionVisitor : ExpressionVisitor { - /// - /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to - /// the same compatibility standards as public APIs. It may be changed or removed without notice in - /// any release. You should only use it directly in your code with extreme caution and knowing that - /// doing so can result in application failures when updating to a new Entity Framework Core release. - /// - public SplitIncludeRewritingExpressionVisitor() - { - } - /// protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { @@ -59,15 +49,12 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp && selectMethodCall.Method.GetGenericMethodDefinition() == QueryableMethods.Select) { var selector = RewriteCollectionInclude( - selectMethodCall.Arguments[0], selectMethodCall.Arguments[1].UnwrapLambdaFromQuote(), singleResult, reverseOrdering); + selectMethodCall.Arguments[0], selectMethodCall.Arguments[1].UnwrapLambdaFromQuote(), singleResult, + reverseOrdering); source = selectMethodCall.Update( selectMethodCall.Object, - new[] - { - selectMethodCall.Arguments[0], - Expression.Quote(selector) - }); + new[] { selectMethodCall.Arguments[0], Expression.Quote(selector) }); if (singleResult) { @@ -81,7 +68,11 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp return base.VisitMethodCall(methodCallExpression); } - private LambdaExpression RewriteCollectionInclude(Expression source, LambdaExpression selector, bool singleResult, bool reverseOrdering) + private LambdaExpression RewriteCollectionInclude( + Expression source, + LambdaExpression selector, + bool singleResult, + bool reverseOrdering) { var selectorParameter = selector.Parameters[0]; var selectorBody = selector.Body; @@ -115,8 +106,11 @@ private sealed class CollectionSelectManyInjectingExpressionVisitor : Expression private readonly Type _sourceElementType; private readonly ParameterExpression _parameterExpression; - public CollectionSelectManyInjectingExpressionVisitor(SplitIncludeRewritingExpressionVisitor parentVisitor, - Expression parentQuery, Type sourceElementType, ParameterExpression parameterExpression) + public CollectionSelectManyInjectingExpressionVisitor( + SplitIncludeRewritingExpressionVisitor parentVisitor, + Expression parentQuery, + Type sourceElementType, + ParameterExpression parameterExpression) { _parentQuery = new CloningExpressionVisitor().Visit(parentQuery); _parentVisitor = parentVisitor; diff --git a/src/EFCore.Relational/Query/Internal/SplitQueryCollectionContext.cs b/src/EFCore.Relational/Query/Internal/SplitQueryCollectionContext.cs index 061ce23933a..4a20f14237b 100644 --- a/src/EFCore.Relational/Query/Internal/SplitQueryCollectionContext.cs +++ b/src/EFCore.Relational/Query/Internal/SplitQueryCollectionContext.cs @@ -29,6 +29,7 @@ public SplitQueryCollectionContext( ParentIdentifier = parentIdentifier; ResultContext = new ResultContext(); } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -36,6 +37,7 @@ public SplitQueryCollectionContext( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual ResultContext ResultContext { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -43,6 +45,7 @@ public SplitQueryCollectionContext( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual object Parent { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in @@ -50,6 +53,7 @@ public SplitQueryCollectionContext( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual object Collection { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in diff --git a/src/EFCore.Relational/Query/Internal/SplitQueryDataReaderContext.cs b/src/EFCore.Relational/Query/Internal/SplitQueryDataReaderContext.cs index e9c05e8bbea..16d38476f8a 100644 --- a/src/EFCore.Relational/Query/Internal/SplitQueryDataReaderContext.cs +++ b/src/EFCore.Relational/Query/Internal/SplitQueryDataReaderContext.cs @@ -33,6 +33,7 @@ public SplitQueryDataReaderContext( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual bool? HasNext { get; set; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in diff --git a/src/EFCore.Relational/Query/Internal/SplitQueryResultCoordinator.cs b/src/EFCore.Relational/Query/Internal/SplitQueryResultCoordinator.cs index ab46d32bbaa..ecf50d062ed 100644 --- a/src/EFCore.Relational/Query/Internal/SplitQueryResultCoordinator.cs +++ b/src/EFCore.Relational/Query/Internal/SplitQueryResultCoordinator.cs @@ -57,7 +57,8 @@ public SplitQueryResultCoordinator() /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual void SetDataReader( - int collectionId, [NotNull] RelationalDataReader relationalDataReader) + int collectionId, + [NotNull] RelationalDataReader relationalDataReader) { while (DataReaders.Count <= collectionId) { @@ -74,7 +75,8 @@ public virtual void SetDataReader( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual void SetSplitQueryCollectionContext( - int collectionId, [NotNull] SplitQueryCollectionContext splitQueryCollectionContext) + int collectionId, + [NotNull] SplitQueryCollectionContext splitQueryCollectionContext) { while (Collections.Count <= collectionId) { diff --git a/src/EFCore.Relational/Query/Internal/SplitQueryingEnumerable.cs b/src/EFCore.Relational/Query/Internal/SplitQueryingEnumerable.cs index 3016e71cf55..eac68f8c378 100644 --- a/src/EFCore.Relational/Query/Internal/SplitQueryingEnumerable.cs +++ b/src/EFCore.Relational/Query/Internal/SplitQueryingEnumerable.cs @@ -75,7 +75,8 @@ public virtual IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancella /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual IEnumerator GetEnumerator() => new Enumerator(this); + public virtual IEnumerator GetEnumerator() + => new Enumerator(this); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -83,7 +84,8 @@ public virtual IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancella /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() + => GetEnumerator(); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -140,7 +142,8 @@ public Enumerator(SplitQueryingEnumerable queryingEnumerable) public T Current { get; private set; } - object IEnumerator.Current => Current; + object IEnumerator.Current + => Current; public bool MoveNext() { @@ -164,7 +167,8 @@ public bool MoveNext() if (hasNext) { _resultCoordinator.ResultContext.Values = null; - _shaper(_relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); + _shaper( + _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); _relatedDataLoaders?.Invoke(_relationalQueryContext, _executionStrategy, _resultCoordinator); Current = _shaper( _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); @@ -210,12 +214,14 @@ public void Dispose() { dataReader?.DataReader.Dispose(); } + _resultCoordinator.DataReaders.Clear(); _dataReader = null; } - public void Reset() => throw new NotImplementedException(); + public void Reset() + => throw new NotImplementedException(); } private sealed class AsyncEnumerator : IAsyncEnumerator @@ -258,7 +264,8 @@ public async ValueTask MoveNextAsync() _executionStrategy = _relationalQueryContext.ExecutionStrategyFactory.Create(); } - await _executionStrategy.ExecuteAsync(true, InitializeReaderAsync, null, _relationalQueryContext.CancellationToken).ConfigureAwait(false); + await _executionStrategy.ExecuteAsync( + true, InitializeReaderAsync, null, _relationalQueryContext.CancellationToken).ConfigureAwait(false); } var hasNext = await _dataReader.ReadAsync().ConfigureAwait(false); @@ -267,11 +274,14 @@ public async ValueTask MoveNextAsync() if (hasNext) { _resultCoordinator.ResultContext.Values = null; - _shaper(_relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); + _shaper( + _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); if (_relatedDataLoaders != null) { - await _relatedDataLoaders(_relationalQueryContext, _executionStrategy, _resultCoordinator).ConfigureAwait(false); + await _relatedDataLoaders(_relationalQueryContext, _executionStrategy, _resultCoordinator) + .ConfigureAwait(false); } + Current = _shaper( _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); } @@ -295,14 +305,14 @@ private async Task InitializeReaderAsync(DbContext _, bool result, Cancell _dataReader = await relationalCommand.ExecuteReaderAsync( - new RelationalCommandParameterObject( - _relationalQueryContext.Connection, - _relationalQueryContext.ParameterValues, - _relationalCommandCache.ReaderColumns, - _relationalQueryContext.Context, - _relationalQueryContext.CommandLogger), - cancellationToken) - .ConfigureAwait(false); + new RelationalCommandParameterObject( + _relationalQueryContext.Connection, + _relationalQueryContext.ParameterValues, + _relationalCommandCache.ReaderColumns, + _relationalQueryContext.Context, + _relationalQueryContext.CommandLogger), + cancellationToken) + .ConfigureAwait(false); _resultCoordinator = new SplitQueryResultCoordinator(); @@ -323,6 +333,7 @@ public async ValueTask DisposeAsync() await dataReader.DataReader.DisposeAsync().ConfigureAwait(false); } } + _resultCoordinator.DataReaders.Clear(); _dataReader = null; diff --git a/src/EFCore.Relational/Query/Internal/SqlExpressionOptimizingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/SqlExpressionOptimizingExpressionVisitor.cs index 45dc54c4bbf..c4575af10cb 100644 --- a/src/EFCore.Relational/Query/Internal/SqlExpressionOptimizingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/SqlExpressionOptimizingExpressionVisitor.cs @@ -83,7 +83,9 @@ protected override Expression VisitExtension(Expression extensionExpression) default: return base.VisitExtension(extensionExpression); - }; + } + + ; } private Expression VisitSelect(SelectExpression selectExpression) @@ -148,7 +150,7 @@ private SqlExpression SimplifyUnaryExpression( switch (operatorType) { case ExpressionType.Not - when type == typeof(bool): + when type == typeof(bool): { switch (operand) { @@ -212,8 +214,9 @@ private SqlExpression SimplifyUnaryExpression( binaryOperand.TypeMapping); } } - break; + break; } + break; } @@ -249,7 +252,7 @@ private SqlExpression SimplifyNullNotNullExpression( typeMapping); case ColumnExpression columnOperand - when !columnOperand.IsNullable: + when !columnOperand.IsNullable: return _sqlExpressionFactory.Constant(operatorType == ExpressionType.NotEqual, typeMapping); case SqlUnaryExpression sqlUnaryOperand: @@ -271,6 +274,7 @@ private SqlExpression SimplifyNullNotNullExpression( // (a is not null) is not null -> true return _sqlExpressionFactory.Constant(operatorType == ExpressionType.NotEqual, typeMapping); } + break; case SqlBinaryExpression sqlBinaryOperand: @@ -284,20 +288,22 @@ private SqlExpression SimplifyNullNotNullExpression( && sqlBinaryOperand.OperatorType != ExpressionType.OrElse) { var newLeft = SimplifyNullNotNullExpression(operatorType, sqlBinaryOperand.Left, typeof(bool), typeMapping); - var newRight = SimplifyNullNotNullExpression(operatorType, sqlBinaryOperand.Right, typeof(bool), typeMapping); + var newRight = SimplifyNullNotNullExpression( + operatorType, sqlBinaryOperand.Right, typeof(bool), typeMapping); return SimplifyLogicalSqlBinaryExpression( - operatorType == ExpressionType.Equal - ? ExpressionType.OrElse - : ExpressionType.AndAlso, - newLeft, - newRight, - typeMapping); + operatorType == ExpressionType.Equal + ? ExpressionType.OrElse + : ExpressionType.AndAlso, + newLeft, + newRight, + typeMapping); } + break; case SqlFunctionExpression sqlFunctionExpression - when sqlFunctionExpression.IsBuiltIn + when sqlFunctionExpression.IsBuiltIn && string.Equals("COALESCE", sqlFunctionExpression.Name, StringComparison.OrdinalIgnoreCase): // for coalesce: // (a ?? b) == null -> a == null && b == null @@ -311,10 +317,11 @@ when sqlFunctionExpression.IsBuiltIn operatorType == ExpressionType.Equal ? ExpressionType.AndAlso : ExpressionType.OrElse, - leftArgument, - rightArgument, - typeMapping); + leftArgument, + rightArgument, + typeMapping); } + break; } @@ -402,7 +409,7 @@ private SqlExpression SimplifyBinaryExpression( // a == a -> true // a != a -> false if ((left is LikeExpression - || left is ColumnExpression columnExpression && !columnExpression.IsNullable) + || left is ColumnExpression columnExpression && !columnExpression.IsNullable) && left.Equals(right)) { return _sqlExpressionFactory.Constant(operatorType == ExpressionType.Equal, typeMapping); @@ -497,11 +504,11 @@ private SqlExpression SimplifyBoolConstantComparisonExpression( static bool CanOptimize(SqlExpression operand) => operand is LikeExpression - || (operand is SqlUnaryExpression sqlUnary - && (sqlUnary.OperatorType == ExpressionType.Equal - || sqlUnary.OperatorType == ExpressionType.NotEqual - // TODO: #18689 - /*|| sqlUnary.OperatorType == ExpressionType.Not*/)); + || (operand is SqlUnaryExpression sqlUnary + && (sqlUnary.OperatorType == ExpressionType.Equal + || sqlUnary.OperatorType == ExpressionType.NotEqual + // TODO: #18689 + /*|| sqlUnary.OperatorType == ExpressionType.Not*/)); } private SqlExpression SimplifyLogicalSqlBinaryExpression( @@ -524,7 +531,8 @@ private SqlExpression SimplifyLogicalSqlBinaryExpression( ? newLeftConstant : right; } - else if (right is SqlConstantExpression newRightConstant) + + if (right is SqlConstantExpression newRightConstant) { // a && true -> a // a || true -> true diff --git a/src/EFCore.Relational/Query/Internal/SqlExpressionSimplifyingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/SqlExpressionSimplifyingExpressionVisitor.cs index 3e933d13fd9..e7f06449104 100644 --- a/src/EFCore.Relational/Query/Internal/SqlExpressionSimplifyingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/SqlExpressionSimplifyingExpressionVisitor.cs @@ -54,9 +54,10 @@ protected override Expression VisitExtension(Expression extensionExpression) && caseExpression.ElseResult is CaseExpression nestedCaseExpression && nestedCaseExpression.Operand == null) { - return VisitExtension(_sqlExpressionFactory.Case( - caseExpression.WhenClauses.Union(nestedCaseExpression.WhenClauses).ToList(), - nestedCaseExpression.ElseResult)); + return VisitExtension( + _sqlExpressionFactory.Case( + caseExpression.WhenClauses.Union(nestedCaseExpression.WhenClauses).ToList(), + nestedCaseExpression.ElseResult)); } if (extensionExpression is SqlBinaryExpression sqlBinaryExpression) @@ -73,15 +74,13 @@ private bool IsCompareTo(CaseExpression caseExpression) && caseExpression.Operand == null && caseExpression.ElseResult == null && caseExpression.WhenClauses.Count == 3 - && caseExpression.WhenClauses.All(c => c.Test is SqlBinaryExpression - && c.Result is SqlConstantExpression constant - && constant.Value is int)) + && caseExpression.WhenClauses.All( + c => c.Test is SqlBinaryExpression + && c.Result is SqlConstantExpression constant + && constant.Value is int)) { - var whenClauses = caseExpression.WhenClauses.Select(c => new - { - test = (SqlBinaryExpression)c.Test, - resultValue = (int)((SqlConstantExpression)c.Result).Value - }).ToList(); + var whenClauses = caseExpression.WhenClauses.Select( + c => new { test = (SqlBinaryExpression)c.Test, resultValue = (int)((SqlConstantExpression)c.Result).Value }).ToList(); if (whenClauses[0].test.Left.Equals(whenClauses[1].test.Left) && whenClauses[1].test.Left.Equals(whenClauses[2].test.Left) @@ -125,63 +124,71 @@ private SqlExpression OptimizeCompareTo( // CompareTo(a, b) != 1 -> a <= b // CompareTo(a, b) != -1 -> a >= b case ExpressionType.NotEqual: - return (SqlExpression)Visit(intValue switch - { - 0 => _sqlExpressionFactory.NotEqual(testLeft, testRight), - 1 => _sqlExpressionFactory.LessThanOrEqual(testLeft, testRight), - _ => _sqlExpressionFactory.GreaterThanOrEqual(testLeft, testRight), - }); + return (SqlExpression)Visit( + intValue switch + { + 0 => _sqlExpressionFactory.NotEqual(testLeft, testRight), + 1 => _sqlExpressionFactory.LessThanOrEqual(testLeft, testRight), + _ => _sqlExpressionFactory.GreaterThanOrEqual(testLeft, testRight), + }); // CompareTo(a, b) > 0 -> a > b // CompareTo(a, b) > 1 -> false // CompareTo(a, b) > -1 -> a >= b case ExpressionType.GreaterThan: - return (SqlExpression)Visit(intValue switch - { - 0 => _sqlExpressionFactory.GreaterThan(testLeft, testRight), - 1 => _sqlExpressionFactory.Constant(false, sqlBinaryExpression.TypeMapping), - _ => _sqlExpressionFactory.GreaterThanOrEqual(testLeft, testRight), - }); + return (SqlExpression)Visit( + intValue switch + { + 0 => _sqlExpressionFactory.GreaterThan(testLeft, testRight), + 1 => _sqlExpressionFactory.Constant(false, sqlBinaryExpression.TypeMapping), + _ => _sqlExpressionFactory.GreaterThanOrEqual(testLeft, testRight), + }); // CompareTo(a, b) >= 0 -> a >= b // CompareTo(a, b) >= 1 -> a > b // CompareTo(a, b) >= -1 -> true case ExpressionType.GreaterThanOrEqual: - return (SqlExpression)Visit(intValue switch - { - 0 => _sqlExpressionFactory.GreaterThanOrEqual(testLeft, testRight), - 1 => _sqlExpressionFactory.GreaterThan(testLeft, testRight), - _ => _sqlExpressionFactory.Constant(true, sqlBinaryExpression.TypeMapping), - }); + return (SqlExpression)Visit( + intValue switch + { + 0 => _sqlExpressionFactory.GreaterThanOrEqual(testLeft, testRight), + 1 => _sqlExpressionFactory.GreaterThan(testLeft, testRight), + _ => _sqlExpressionFactory.Constant(true, sqlBinaryExpression.TypeMapping), + }); // CompareTo(a, b) < 0 -> a < b // CompareTo(a, b) < 1 -> a <= b // CompareTo(a, b) < -1 -> false case ExpressionType.LessThan: - return (SqlExpression)Visit(intValue switch - { - 0 => _sqlExpressionFactory.LessThan(testLeft, testRight), - 1 => _sqlExpressionFactory.LessThanOrEqual(testLeft, testRight), - _ => _sqlExpressionFactory.Constant(false, sqlBinaryExpression.TypeMapping), - }); + return (SqlExpression)Visit( + intValue switch + { + 0 => _sqlExpressionFactory.LessThan(testLeft, testRight), + 1 => _sqlExpressionFactory.LessThanOrEqual(testLeft, testRight), + _ => _sqlExpressionFactory.Constant(false, sqlBinaryExpression.TypeMapping), + }); // operatorType == ExpressionType.LessThanOrEqual // CompareTo(a, b) <= 0 -> a <= b // CompareTo(a, b) <= 1 -> true // CompareTo(a, b) <= -1 -> a < b default: - return (SqlExpression)Visit(intValue switch - { - 0 => _sqlExpressionFactory.LessThanOrEqual(testLeft, testRight), - 1 => _sqlExpressionFactory.Constant(true, sqlBinaryExpression.TypeMapping), - _ => _sqlExpressionFactory.LessThan(testLeft, testRight), - }); - }; + return (SqlExpression)Visit( + intValue switch + { + 0 => _sqlExpressionFactory.LessThanOrEqual(testLeft, testRight), + 1 => _sqlExpressionFactory.Constant(true, sqlBinaryExpression.TypeMapping), + _ => _sqlExpressionFactory.LessThan(testLeft, testRight), + }); + } + + ; } private Expression SimplifySqlBinary(SqlBinaryExpression sqlBinaryExpression) { - var sqlConstantComponent = sqlBinaryExpression.Left as SqlConstantExpression ?? sqlBinaryExpression.Right as SqlConstantExpression; + var sqlConstantComponent = + sqlBinaryExpression.Left as SqlConstantExpression ?? sqlBinaryExpression.Right as SqlConstantExpression; var caseComponent = sqlBinaryExpression.Left as CaseExpression ?? sqlBinaryExpression.Right as CaseExpression; // generic CASE statement comparison optimization: @@ -224,11 +231,12 @@ private Expression SimplifySqlBinary(SqlBinaryExpression sqlBinaryExpression) var right = (SqlExpression)Visit(sqlBinaryExpression.Right); if (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso - || sqlBinaryExpression.OperatorType == ExpressionType.OrElse) + || sqlBinaryExpression.OperatorType == ExpressionType.OrElse) { var leftCandidateInfo = GetInExressionCandidateInfo(left); var rightCandidateInfo = GetInExressionCandidateInfo(right); - if (leftCandidateInfo.OptimizeCandidate && rightCandidateInfo.OptimizeCandidate + if (leftCandidateInfo.OptimizeCandidate + && rightCandidateInfo.OptimizeCandidate && leftCandidateInfo.ColumnExpression == rightCandidateInfo.ColumnExpression && leftCandidateInfo.OperationType == rightCandidateInfo.OperationType) { @@ -240,8 +248,10 @@ private Expression SimplifySqlBinary(SqlBinaryExpression sqlBinaryExpression) && !(rightCandidateInfo.ConstantValue is string) && !(rightCandidateInfo.ConstantValue is byte[]); - if ((leftCandidateInfo.OperationType == ExpressionType.Equal && sqlBinaryExpression.OperatorType == ExpressionType.OrElse) - || (leftCandidateInfo.OperationType == ExpressionType.NotEqual && sqlBinaryExpression.OperatorType == ExpressionType.AndAlso)) + if ((leftCandidateInfo.OperationType == ExpressionType.Equal + && sqlBinaryExpression.OperatorType == ExpressionType.OrElse) + || (leftCandidateInfo.OperationType == ExpressionType.NotEqual + && sqlBinaryExpression.OperatorType == ExpressionType.AndAlso)) { object leftValue; object rightValue; @@ -281,7 +291,8 @@ private Expression SimplifySqlBinary(SqlBinaryExpression sqlBinaryExpression) _sqlExpressionFactory.Constant(resultArray, leftCandidateInfo.TypeMapping), leftCandidateInfo.OperationType == ExpressionType.NotEqual); } - else if (leftConstantIsEnumerable && rightConstantIsEnumerable) + + if (leftConstantIsEnumerable && rightConstantIsEnumerable) { // a IN (1, 2, 3) && a IN (2, 3, 4) -> a IN (2, 3) // a NOT IN (1, 2, 3) || a NOT IN (2, 3, 4) -> a NOT IN (2, 3) @@ -290,9 +301,9 @@ private Expression SimplifySqlBinary(SqlBinaryExpression sqlBinaryExpression) (IEnumerable)rightCandidateInfo.ConstantValue); return _sqlExpressionFactory.In( - leftCandidateInfo.ColumnExpression, - _sqlExpressionFactory.Constant(resultArray, leftCandidateInfo.TypeMapping), - leftCandidateInfo.OperationType == ExpressionType.NotEqual); + leftCandidateInfo.ColumnExpression, + _sqlExpressionFactory.Constant(resultArray, leftCandidateInfo.TypeMapping), + leftCandidateInfo.OperationType == ExpressionType.NotEqual); } } } @@ -363,7 +374,8 @@ private List BuildListFromEnumerable(IEnumerable collection) return result; } - private (bool OptimizeCandidate, ColumnExpression ColumnExpression, object ConstantValue, RelationalTypeMapping TypeMapping, ExpressionType OperationType) GetInExressionCandidateInfo(SqlExpression sqlExpression) + private (bool OptimizeCandidate, ColumnExpression ColumnExpression, object ConstantValue, RelationalTypeMapping TypeMapping, + ExpressionType OperationType) GetInExressionCandidateInfo(SqlExpression sqlExpression) { if (sqlExpression is SqlUnaryExpression sqlUnaryExpression && sqlUnaryExpression.OperatorType == ExpressionType.Not) diff --git a/src/EFCore.Relational/Query/Internal/TableValuedFunctionQueryRootExpression.cs b/src/EFCore.Relational/Query/Internal/TableValuedFunctionQueryRootExpression.cs index c1408e248fd..f5dc38a7437 100644 --- a/src/EFCore.Relational/Query/Internal/TableValuedFunctionQueryRootExpression.cs +++ b/src/EFCore.Relational/Query/Internal/TableValuedFunctionQueryRootExpression.cs @@ -27,7 +27,9 @@ public class TableValuedFunctionQueryRootExpression : QueryRootExpression /// //Since this is always generated while compiling there is no query provider associated public TableValuedFunctionQueryRootExpression( - [NotNull] IEntityType entityType, [NotNull] IStoreFunction function, [NotNull] IReadOnlyCollection arguments) + [NotNull] IEntityType entityType, + [NotNull] IStoreFunction function, + [NotNull] IReadOnlyCollection arguments) : base(entityType) { Check.NotNull(function, nameof(function)); @@ -44,6 +46,7 @@ public TableValuedFunctionQueryRootExpression( /// doing so can result in application failures when updating to a new Entity Framework Core release. /// public virtual IStoreFunction Function { get; } + /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in diff --git a/src/EFCore.Relational/Query/Internal/TableValuedFunctionToQueryRootConvertingExpressionVisitor.cs b/src/EFCore.Relational/Query/Internal/TableValuedFunctionToQueryRootConvertingExpressionVisitor.cs index 6ee0952e92f..5eb954193ce 100644 --- a/src/EFCore.Relational/Query/Internal/TableValuedFunctionToQueryRootConvertingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Internal/TableValuedFunctionToQueryRootConvertingExpressionVisitor.cs @@ -49,7 +49,8 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp } private Expression CreateTableValuedFunctionQueryRootExpression( - IStoreFunction function, IReadOnlyCollection arguments) + IStoreFunction function, + IReadOnlyCollection arguments) // See issue #19970 => new TableValuedFunctionQueryRootExpression(function.EntityTypeMappings.Single().EntityType, function, arguments); } diff --git a/src/EFCore.Relational/Query/QuerySqlGenerator.cs b/src/EFCore.Relational/Query/QuerySqlGenerator.cs index cc62ddfa1fb..0abb1f29936 100644 --- a/src/EFCore.Relational/Query/QuerySqlGenerator.cs +++ b/src/EFCore.Relational/Query/QuerySqlGenerator.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; -using System.Text.RegularExpressions; -using System.Threading; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; @@ -18,7 +16,7 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// A query SQL generator to get for given . + /// A query SQL generator to get for given . /// /// /// This type is typically used by database providers (and other extensions). It is generally @@ -70,7 +68,7 @@ public QuerySqlGenerator([NotNull] QuerySqlGeneratorDependencies dependencies) protected virtual QuerySqlGeneratorDependencies Dependencies { get; } /// - /// Gets a relational command for a . + /// Gets a relational command for a . /// /// A select expression to print in command text. /// A relational command with a SQL represented by the select expression. @@ -102,7 +100,8 @@ public virtual IRelationalCommand GetCommand([NotNull] SelectExpression selectEx /// /// The current SQL command builder. /// - protected virtual IRelationalCommandBuilder Sql => _relationalCommandBuilder; + protected virtual IRelationalCommandBuilder Sql + => _relationalCommandBuilder; /// /// Generates the head comment for tags. @@ -481,12 +480,12 @@ protected virtual void CheckComposableSql([NotNull] string sql) continue; } - if (char.ToLowerInvariant(c) == 's' && - char.ToLowerInvariant(NextChar()) == 'e' && - char.ToLowerInvariant(NextChar()) == 'l' && - char.ToLowerInvariant(NextChar()) == 'e' && - char.ToLowerInvariant(NextChar()) == 'c' && - char.ToLowerInvariant(NextChar()) == 't') + if (char.ToLowerInvariant(c) == 's' + && char.ToLowerInvariant(NextChar()) == 'e' + && char.ToLowerInvariant(NextChar()) == 'l' + && char.ToLowerInvariant(NextChar()) == 'e' + && char.ToLowerInvariant(NextChar()) == 'c' + && char.ToLowerInvariant(NextChar()) == 't') { var (c1, c2) = (NextChar(), NextChar()); if (char.IsWhiteSpace(c1) @@ -761,6 +760,7 @@ protected override Expression VisitSqlUnary(SqlUnaryExpression sqlUnaryExpressio { _relationalCommandBuilder.Append(")"); } + break; } } @@ -1048,13 +1048,14 @@ protected virtual void GenerateSetOperation([NotNull] SetOperationBase setOperat _relationalCommandBuilder.AppendLine($"{GetSetOperation(setOperation)}{(setOperation.IsDistinct ? "" : " ALL")}"); GenerateSetOperationOperand(setOperation, setOperation.Source2); - static string GetSetOperation(SetOperationBase operation) => operation switch - { - ExceptExpression _ => "EXCEPT", - IntersectExpression _ => "INTERSECT", - UnionExpression _ => "UNION", - _ => throw new InvalidOperationException(CoreStrings.UnknownEntity("SetOperationType")), - }; + static string GetSetOperation(SetOperationBase operation) + => operation switch + { + ExceptExpression _ => "EXCEPT", + IntersectExpression _ => "INTERSECT", + UnionExpression _ => "UNION", + _ => throw new InvalidOperationException(CoreStrings.UnknownEntity("SetOperationType")), + }; } /// diff --git a/src/EFCore.Relational/Query/RelationalCollectionShaperExpression.cs b/src/EFCore.Relational/Query/RelationalCollectionShaperExpression.cs index 7e5b28feb73..1b36d90cb37 100644 --- a/src/EFCore.Relational/Query/RelationalCollectionShaperExpression.cs +++ b/src/EFCore.Relational/Query/RelationalCollectionShaperExpression.cs @@ -13,7 +13,8 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// An expression that represents creation of a collection for relational provider in . + /// An expression that represents creation of a collection for relational provider in + /// . /// /// /// This type is typically used by database providers (and other extensions). It is generally @@ -41,8 +42,9 @@ public RelationalCollectionShaperExpression( [NotNull] Expression innerShaper, [CanBeNull] INavigation navigation, [NotNull] Type elementType) - : this(collectionId, parentIdentifier, outerIdentifier, selfIdentifier, - null, null, null, innerShaper, navigation, elementType) + : this( + collectionId, parentIdentifier, outerIdentifier, selfIdentifier, + null, null, null, innerShaper, navigation, elementType) { } @@ -93,26 +95,32 @@ public RelationalCollectionShaperExpression( /// A unique id for this collection shaper. /// public virtual int CollectionId { get; } + /// /// The identifier for the parent element. /// public virtual Expression ParentIdentifier { get; } + /// /// The identifier for the outer element. /// public virtual Expression OuterIdentifier { get; } + /// /// The identifier for the element in the collection. /// public virtual Expression SelfIdentifier { get; } + /// /// The list of value comparers to compare parent identifier. /// public virtual IReadOnlyList ParentIdentifierValueComparers { get; } + /// /// The list of value comparers to compare outer identifier. /// public virtual IReadOnlyList OuterIdentifierValueComparers { get; } + /// /// The list of value comparers to compare self identifier. /// @@ -122,19 +130,24 @@ public RelationalCollectionShaperExpression( /// The expression to create inner elements. /// public virtual Expression InnerShaper { get; } + /// - /// The navigation if associated with the collection. + /// The navigation if associated with the collection. /// public virtual INavigationBase Navigation { get; } + /// /// The clr type of elements of the collection. /// public virtual Type ElementType { get; } /// - public override Type Type => Navigation?.ClrType ?? typeof(List<>).MakeGenericType(ElementType); + public override Type Type + => Navigation?.ClrType ?? typeof(List<>).MakeGenericType(ElementType); + /// - public sealed override ExpressionType NodeType => ExpressionType.Extension; + public sealed override ExpressionType NodeType + => ExpressionType.Extension; /// protected override Expression VisitChildren(ExpressionVisitor visitor) @@ -153,10 +166,10 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual RelationalCollectionShaperExpression Update( [NotNull] Expression parentIdentifier, diff --git a/src/EFCore.Relational/Query/RelationalCompiledQueryCacheKeyGenerator.cs b/src/EFCore.Relational/Query/RelationalCompiledQueryCacheKeyGenerator.cs index dd2aa4ec272..fc445de8776 100644 --- a/src/EFCore.Relational/Query/RelationalCompiledQueryCacheKeyGenerator.cs +++ b/src/EFCore.Relational/Query/RelationalCompiledQueryCacheKeyGenerator.cs @@ -63,7 +63,8 @@ public override object GenerateCacheKey(Expression query, bool async) /// The query to get the cache key for. /// A value indicating whether the query will be executed asynchronously. /// The cache key. - protected new RelationalCompiledQueryCacheKey GenerateCacheKeyCore([NotNull] Expression query, bool async) // Intentionally non-virtual + protected new RelationalCompiledQueryCacheKey + GenerateCacheKeyCore([NotNull] Expression query, bool async) // Intentionally non-virtual { var relationalOptions = RelationalOptionsExtension.Extract(RelationalDependencies.ContextOptions); @@ -96,11 +97,13 @@ public override object GenerateCacheKey(Expression query, bool async) /// /// The non-relational cache key. /// True to use relational null logic. - /// to use when loading related collections. - /// if the query should be buffered. + /// to use when loading related collections. + /// if the query should be buffered. public RelationalCompiledQueryCacheKey( - CompiledQueryCacheKey compiledQueryCacheKey, bool useRelationalNulls, - QuerySplittingBehavior? querySplittingBehavior, bool shouldBuffer) + CompiledQueryCacheKey compiledQueryCacheKey, + bool useRelationalNulls, + QuerySplittingBehavior? querySplittingBehavior, + bool shouldBuffer) { _compiledQueryCacheKey = compiledQueryCacheKey; _useRelationalNulls = useRelationalNulls; @@ -115,8 +118,8 @@ public RelationalCompiledQueryCacheKey( /// The object to compare this key to. /// /// - /// if the object is a and is for the same query, - /// otherwise . + /// if the object is a and is for the same query, + /// otherwise . /// public override bool Equals(object obj) => obj is RelationalCompiledQueryCacheKey key @@ -143,8 +146,9 @@ public bool Equals(RelationalCompiledQueryCacheKey other) /// /// The hash code for the key. /// - public override int GetHashCode() => HashCode.Combine( - _compiledQueryCacheKey, _useRelationalNulls, _querySplittingBehavior, _shouldBuffer); + public override int GetHashCode() + => HashCode.Combine( + _compiledQueryCacheKey, _useRelationalNulls, _querySplittingBehavior, _shouldBuffer); } } } diff --git a/src/EFCore.Relational/Query/RelationalEntityShaperExpression.cs b/src/EFCore.Relational/Query/RelationalEntityShaperExpression.cs index 8685a259319..9f4abd8edcd 100644 --- a/src/EFCore.Relational/Query/RelationalEntityShaperExpression.cs +++ b/src/EFCore.Relational/Query/RelationalEntityShaperExpression.cs @@ -6,7 +6,6 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; -using System.Runtime.CompilerServices; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -19,7 +18,8 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// An expression that represents creation of an entity instance for a relational provider in . + /// An expression that represents creation of an entity instance for a relational provider in + /// . /// /// /// This type is typically used by database providers (and other extensions). It is generally @@ -29,8 +29,8 @@ namespace Microsoft.EntityFrameworkCore.Query public class RelationalEntityShaperExpression : EntityShaperExpression { private static readonly MethodInfo _createUnableToIdentifyConcreteTypeException - = typeof(RelationalEntityShaperExpression).GetTypeInfo() - .GetDeclaredMethod(nameof(CreateUnableToIdentifyConcreteTypeException)); + = typeof(RelationalEntityShaperExpression).GetTypeInfo() + .GetDeclaredMethod(nameof(CreateUnableToIdentifyConcreteTypeException)); [UsedImplicitly] private static Exception CreateUnableToIdentifyConcreteTypeException() @@ -53,7 +53,10 @@ public RelationalEntityShaperExpression([NotNull] IEntityType entityType, [NotNu /// The entity type to shape. /// An expression of ValueBuffer to get values for properties of the entity. /// Whether this entity instance can be null. - /// An expression of to determine which entity type to materialize. + /// + /// An expression of to determine which entity type to + /// materialize. + /// protected RelationalEntityShaperExpression( [NotNull] IEntityType entityType, [NotNull] Expression valueBufferExpression, @@ -116,9 +119,10 @@ protected override LambdaExpression GenerateMaterializationCondition(IEntityType if (requiredNonPkProperties.Count > 0) { condition = requiredNonPkProperties - .Select(p => NotEqual( - valueBufferParameter.CreateValueBufferReadValueExpression(typeof(object), p.GetIndex(), p), - Constant(null))) + .Select( + p => NotEqual( + valueBufferParameter.CreateValueBufferReadValueExpression(typeof(object), p.GetIndex(), p), + Constant(null))) .Aggregate((a, b) => AndAlso(a, b)); } @@ -128,9 +132,10 @@ protected override LambdaExpression GenerateMaterializationCondition(IEntityType { var allNonSharedNullableProperties = allNonSharedProperties.Where(p => p.IsNullable).ToList(); var atLeastOneNonNullValueInNullablePropertyCondition = allNonSharedNullableProperties - .Select(p => NotEqual( - valueBufferParameter.CreateValueBufferReadValueExpression(typeof(object), p.GetIndex(), p), - Constant(null))) + .Select( + p => NotEqual( + valueBufferParameter.CreateValueBufferReadValueExpression(typeof(object), p.GetIndex(), p), + Constant(null))) .Aggregate((a, b) => OrElse(a, b)); condition = condition == null diff --git a/src/EFCore.Relational/Query/RelationalEvaluatableExpressionFilter.cs b/src/EFCore.Relational/Query/RelationalEvaluatableExpressionFilter.cs index 2d3d6c5ba97..9f7397a7b88 100644 --- a/src/EFCore.Relational/Query/RelationalEvaluatableExpressionFilter.cs +++ b/src/EFCore.Relational/Query/RelationalEvaluatableExpressionFilter.cs @@ -52,7 +52,7 @@ public RelationalEvaluatableExpressionFilter( /// /// The expression. /// The model. - /// if the expression can be evaluated; otherwise. + /// if the expression can be evaluated; otherwise. public override bool IsEvaluatableExpression(Expression expression, IModel model) { Check.NotNull(expression, nameof(expression)); diff --git a/src/EFCore.Relational/Query/RelationalMemberTranslatorProvider.cs b/src/EFCore.Relational/Query/RelationalMemberTranslatorProvider.cs index ff3f735c14a..9dabcb3d67a 100644 --- a/src/EFCore.Relational/Query/RelationalMemberTranslatorProvider.cs +++ b/src/EFCore.Relational/Query/RelationalMemberTranslatorProvider.cs @@ -17,7 +17,8 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// Provides translations for LINQ expressions by dispatching to multiple specialized member translators. + /// Provides translations for LINQ expressions by dispatching to multiple specialized member + /// translators. /// /// /// The service lifetime is . This means a single instance @@ -46,7 +47,10 @@ public RelationalMemberTranslatorProvider([NotNull] RelationalMemberTranslatorPr /// public virtual SqlExpression Translate( - SqlExpression instance, MemberInfo member, Type returnType, IDiagnosticsLogger logger) + SqlExpression instance, + MemberInfo member, + Type returnType, + IDiagnosticsLogger logger) { Check.NotNull(member, nameof(member)); Check.NotNull(returnType, nameof(returnType)); diff --git a/src/EFCore.Relational/Query/RelationalMethodCallTranslatorProvider.cs b/src/EFCore.Relational/Query/RelationalMethodCallTranslatorProvider.cs index 8ec56ddb1bb..021106267e1 100644 --- a/src/EFCore.Relational/Query/RelationalMethodCallTranslatorProvider.cs +++ b/src/EFCore.Relational/Query/RelationalMethodCallTranslatorProvider.cs @@ -9,7 +9,6 @@ using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; using Microsoft.EntityFrameworkCore.Utilities; @@ -19,7 +18,7 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// Provides translations for LINQ expressions by dispatching to multiple specialized + /// Provides translations for LINQ expressions by dispatching to multiple specialized /// method call translators. /// /// @@ -64,7 +63,10 @@ public RelationalMethodCallTranslatorProvider([NotNull] RelationalMethodCallTran /// public virtual SqlExpression Translate( - IModel model, SqlExpression instance, MethodInfo method, IReadOnlyList arguments, + IModel model, + SqlExpression instance, + MethodInfo method, + IReadOnlyList arguments, IDiagnosticsLogger logger) { Check.NotNull(model, nameof(model)); diff --git a/src/EFCore.Relational/Query/RelationalMethodCallTranslatorProviderDependencies.cs b/src/EFCore.Relational/Query/RelationalMethodCallTranslatorProviderDependencies.cs index 81c5a1514d6..a745acc0d14 100644 --- a/src/EFCore.Relational/Query/RelationalMethodCallTranslatorProviderDependencies.cs +++ b/src/EFCore.Relational/Query/RelationalMethodCallTranslatorProviderDependencies.cs @@ -77,6 +77,7 @@ public RelationalMethodCallTranslatorProviderDependencies( /// Registered plugins. /// public IEnumerable Plugins { get; } + /// /// Relational Type Mapping Source. /// diff --git a/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessor.cs b/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessor.cs index 5fa50ea5bac..7e0cbd09702 100644 --- a/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessor.cs +++ b/src/EFCore.Relational/Query/RelationalParameterBasedSqlProcessor.cs @@ -11,7 +11,7 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// A class that processes the after parementer values are known. + /// A class that processes the after parementer values are known. /// /// /// This type is typically used by database providers (and other extensions). It is generally @@ -46,14 +46,16 @@ public RelationalParameterBasedSqlProcessor( protected virtual bool UseRelationalNulls { get; } /// - /// Optimizes the for given parameter values. + /// Optimizes the for given parameter values. /// /// A select expression to optimize. /// A dictionary of parameter values to use. /// A bool value indicating if the select expression can be cached. /// An optimized select expression. public virtual SelectExpression Optimize( - [NotNull] SelectExpression selectExpression, [NotNull] IReadOnlyDictionary parametersValues, out bool canCache) + [NotNull] SelectExpression selectExpression, + [NotNull] IReadOnlyDictionary parametersValues, + out bool canCache) { Check.NotNull(selectExpression, nameof(selectExpression)); Check.NotNull(parametersValues, nameof(parametersValues)); @@ -69,7 +71,7 @@ public virtual SelectExpression Optimize( } /// - /// Processes the based on nullability of nodes to apply null semantics in use and + /// Processes the based on nullability of nodes to apply null semantics in use and /// optimize it for given parameter values. /// /// A select expression to optimize. @@ -77,7 +79,9 @@ public virtual SelectExpression Optimize( /// A bool value indicating if the select expression can be cached. /// A processed select expression. protected virtual SelectExpression ProcessSqlNullability( - [NotNull] SelectExpression selectExpression, [NotNull] IReadOnlyDictionary parametersValues, out bool canCache) + [NotNull] SelectExpression selectExpression, + [NotNull] IReadOnlyDictionary parametersValues, + out bool canCache) { Check.NotNull(selectExpression, nameof(selectExpression)); Check.NotNull(parametersValues, nameof(parametersValues)); @@ -86,14 +90,16 @@ protected virtual SelectExpression ProcessSqlNullability( } /// - /// Expands the parameters to inside the for given parameter values. + /// Expands the parameters to inside the for given parameter values. /// /// A select expression to optimize. /// A dictionary of parameter values to use. /// A bool value indicating if the select expression can be cached. /// A processed select expression. protected virtual SelectExpression ExpandFromSqlParameter( - [NotNull] SelectExpression selectExpression, [NotNull] IReadOnlyDictionary parametersValues, out bool canCache) + [NotNull] SelectExpression selectExpression, + [NotNull] IReadOnlyDictionary parametersValues, + out bool canCache) { Check.NotNull(selectExpression, nameof(selectExpression)); Check.NotNull(parametersValues, nameof(parametersValues)); diff --git a/src/EFCore.Relational/Query/RelationalQueryCompilationContext.cs b/src/EFCore.Relational/Query/RelationalQueryCompilationContext.cs index 2d46df90395..839a0fd92bc 100644 --- a/src/EFCore.Relational/Query/RelationalQueryCompilationContext.cs +++ b/src/EFCore.Relational/Query/RelationalQueryCompilationContext.cs @@ -28,7 +28,7 @@ public RelationalQueryCompilationContext( [NotNull] QueryCompilationContextDependencies dependencies, [NotNull] RelationalQueryCompilationContextDependencies relationalDependencies, bool async) - : base (dependencies, async) + : base(dependencies, async) { Check.NotNull(relationalDependencies, nameof(relationalDependencies)); @@ -42,8 +42,8 @@ public RelationalQueryCompilationContext( protected virtual RelationalQueryCompilationContextDependencies RelationalDependencies { get; } /// - /// A value indicating the configured for the query. - /// If no value has been configured then will be used. + /// A value indicating the configured for the query. + /// If no value has been configured then will be used. /// public virtual QuerySplittingBehavior? QuerySplittingBehavior { get; internal set; } } diff --git a/src/EFCore.Relational/Query/RelationalQueryContext.cs b/src/EFCore.Relational/Query/RelationalQueryContext.cs index fa5d41231c9..fe2bc4fdb47 100644 --- a/src/EFCore.Relational/Query/RelationalQueryContext.cs +++ b/src/EFCore.Relational/Query/RelationalQueryContext.cs @@ -46,7 +46,7 @@ public RelationalQueryContext( protected virtual RelationalQueryContextDependencies RelationalDependencies { get; } /// - /// A factory for creating a readable query string from a + /// A factory for creating a readable query string from a /// public virtual IRelationalQueryStringFactory RelationalQueryStringFactory => RelationalDependencies.RelationalQueryStringFactory; diff --git a/src/EFCore.Relational/Query/RelationalQueryContextDependencies.cs b/src/EFCore.Relational/Query/RelationalQueryContextDependencies.cs index cecbf64cbd0..45dbb531eda 100644 --- a/src/EFCore.Relational/Query/RelationalQueryContextDependencies.cs +++ b/src/EFCore.Relational/Query/RelationalQueryContextDependencies.cs @@ -72,7 +72,7 @@ public RelationalQueryContextDependencies( public IRelationalConnection RelationalConnection { get; } /// - /// A factory for creating a readable query string from a + /// A factory for creating a readable query string from a /// public IRelationalQueryStringFactory RelationalQueryStringFactory { get; } diff --git a/src/EFCore.Relational/Query/RelationalQueryTranslationPostprocessor.cs b/src/EFCore.Relational/Query/RelationalQueryTranslationPostprocessor.cs index 42c8ecdbb41..349e253e1ed 100644 --- a/src/EFCore.Relational/Query/RelationalQueryTranslationPostprocessor.cs +++ b/src/EFCore.Relational/Query/RelationalQueryTranslationPostprocessor.cs @@ -58,7 +58,10 @@ public override Expression Process(Expression query) /// /// An expression to optimize. /// An expression which has SQL optimized. - [Obsolete("Use 'Optimize' method on " + nameof(RelationalParameterBasedSqlProcessor) + " instead. If you have a case for optimizations to be performed here, please file an issue on github.com/dotnet/efcore.")] + [Obsolete( + "Use 'Optimize' method on " + + nameof(RelationalParameterBasedSqlProcessor) + + " instead. If you have a case for optimizations to be performed here, please file an issue on github.com/dotnet/efcore.")] protected virtual Expression OptimizeSqlExpression([NotNull] Expression query) => query; } diff --git a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs index 3d4f4ddd857..fd3a2490e04 100644 --- a/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs @@ -72,8 +72,10 @@ protected RelationalQueryableMethodTranslatingExpressionVisitor( { RelationalDependencies = parentVisitor.RelationalDependencies; _queryCompilationContext = parentVisitor._queryCompilationContext; - _sqlTranslator = RelationalDependencies.RelationalSqlTranslatingExpressionVisitorFactory.Create(parentVisitor._queryCompilationContext, parentVisitor); - _weakEntityExpandingExpressionVisitor = new WeakEntityExpandingExpressionVisitor(_sqlTranslator, parentVisitor._sqlExpressionFactory); + _sqlTranslator = RelationalDependencies.RelationalSqlTranslatingExpressionVisitorFactory.Create( + parentVisitor._queryCompilationContext, parentVisitor); + _weakEntityExpandingExpressionVisitor = + new WeakEntityExpandingExpressionVisitor(_sqlTranslator, parentVisitor._sqlExpressionFactory); _projectionBindingExpressionVisitor = new RelationalProjectionBindingExpressionVisitor(this, _sqlTranslator); _sqlExpressionFactory = parentVisitor._sqlExpressionFactory; _subquery = true; @@ -90,7 +92,8 @@ protected override Expression VisitExtension(Expression extensionExpression) _sqlExpressionFactory.Select( fromSqlQueryRootExpression.EntityType, new FromSqlExpression( - fromSqlQueryRootExpression.EntityType.GetDefaultMappings().SingleOrDefault().Table.Name.Substring(0, 1).ToLower(), + fromSqlQueryRootExpression.EntityType.GetDefaultMappings().SingleOrDefault().Table.Name.Substring(0, 1) + .ToLower(), fromSqlQueryRootExpression.Sql, fromSqlQueryRootExpression.Argument))); @@ -135,9 +138,11 @@ protected override Expression VisitExtension(Expression extensionExpression) return CreateShapedQueryExpression(entityType, queryExpression); case QueryRootExpression queryRootExpression - when queryRootExpression.EntityType.GetSqlQueryMappings().FirstOrDefault(m => m.IsDefaultSqlQueryMapping)?.SqlQuery is ISqlQuery sqlQuery: - return Visit(new FromSqlQueryRootExpression( - queryRootExpression.EntityType, sqlQuery.Sql, Expression.Constant(Array.Empty(), typeof(object[])))); + when queryRootExpression.EntityType.GetSqlQueryMappings().FirstOrDefault(m => m.IsDefaultSqlQueryMapping)?.SqlQuery is + ISqlQuery sqlQuery: + return Visit( + new FromSqlQueryRootExpression( + queryRootExpression.EntityType, sqlQuery.Sql, Expression.Constant(Array.Empty(), typeof(object[])))); default: return base.VisitExtension(extensionExpression); @@ -385,7 +390,9 @@ protected override ShapedQueryExpression TranslateDistinct(ShapedQueryExpression /// protected override ShapedQueryExpression TranslateElementAtOrDefault( - ShapedQueryExpression source, Expression index, bool returnDefault) + ShapedQueryExpression source, + Expression index, + bool returnDefault) { Check.NotNull(source, nameof(source)); Check.NotNull(index, nameof(index)); @@ -405,7 +412,10 @@ protected override ShapedQueryExpression TranslateExcept(ShapedQueryExpression s /// protected override ShapedQueryExpression TranslateFirstOrDefault( - ShapedQueryExpression source, LambdaExpression predicate, Type returnType, bool returnDefault) + ShapedQueryExpression source, + LambdaExpression predicate, + Type returnType, + bool returnDefault) { Check.NotNull(source, nameof(source)); Check.NotNull(returnType, nameof(returnType)); @@ -425,6 +435,7 @@ protected override ShapedQueryExpression TranslateFirstOrDefault( { _queryCompilationContext.Logger.FirstWithoutOrderByAndFilterWarning(); } + selectExpression.ApplyLimit(TranslateExpression(Expression.Constant(1))); return source.ShaperExpression.Type != returnType @@ -473,7 +484,8 @@ protected override ShapedQueryExpression TranslateGroupBy( newResultSelectorBody = ExpandWeakEntities(selectExpression, newResultSelectorBody); - return source.UpdateShaperExpression(_projectionBindingExpressionVisitor.Translate(selectExpression, newResultSelectorBody)); + return source.UpdateShaperExpression( + _projectionBindingExpressionVisitor.Translate(selectExpression, newResultSelectorBody)); } return null; @@ -654,7 +666,10 @@ private SqlExpression CreateJoinPredicate(Expression outerKey, Expression innerK /// protected override ShapedQueryExpression TranslateLastOrDefault( - ShapedQueryExpression source, LambdaExpression predicate, Type returnType, bool returnDefault) + ShapedQueryExpression source, + LambdaExpression predicate, + Type returnType, + bool returnDefault) { Check.NotNull(source, nameof(source)); Check.NotNull(returnType, nameof(returnType)); @@ -663,8 +678,7 @@ protected override ShapedQueryExpression TranslateLastOrDefault( if (selectExpression.Orderings.Count == 0) { throw new InvalidOperationException( - RelationalStrings.LastUsedWithoutOrderBy(returnDefault ? - nameof(Queryable.LastOrDefault) : nameof(Queryable.Last))); + RelationalStrings.LastUsedWithoutOrderBy(returnDefault ? nameof(Queryable.LastOrDefault) : nameof(Queryable.Last))); } if (predicate != null) @@ -842,7 +856,9 @@ protected override ShapedQueryExpression TranslateOfType(ShapedQueryExpression s /// protected override ShapedQueryExpression TranslateOrderBy( - ShapedQueryExpression source, LambdaExpression keySelector, bool ascending) + ShapedQueryExpression source, + LambdaExpression keySelector, + bool ascending) { Check.NotNull(source, nameof(source)); Check.NotNull(keySelector, nameof(keySelector)); @@ -900,7 +916,9 @@ protected override ShapedQueryExpression TranslateSelect(ShapedQueryExpression s /// protected override ShapedQueryExpression TranslateSelectMany( - ShapedQueryExpression source, LambdaExpression collectionSelector, LambdaExpression resultSelector) + ShapedQueryExpression source, + LambdaExpression collectionSelector, + LambdaExpression resultSelector) { Check.NotNull(source, nameof(source)); Check.NotNull(collectionSelector, nameof(collectionSelector)); @@ -952,7 +970,8 @@ private sealed class CorrelationFindingExpressionVisitor : ExpressionVisitor public (LambdaExpression, bool, bool) IsCorrelated(LambdaExpression lambdaExpression) { - Check.DebugAssert(lambdaExpression.Parameters.Count == 1, "Multiparameter lambda passed to CorrelationFindingExpressionVisitor"); + Check.DebugAssert( + lambdaExpression.Parameters.Count == 1, "Multiparameter lambda passed to CorrelationFindingExpressionVisitor"); _correlated = false; _defaultIfEmpty = false; @@ -1005,7 +1024,10 @@ protected override ShapedQueryExpression TranslateSelectMany(ShapedQueryExpressi /// protected override ShapedQueryExpression TranslateSingleOrDefault( - ShapedQueryExpression source, LambdaExpression predicate, Type returnType, bool returnDefault) + ShapedQueryExpression source, + LambdaExpression predicate, + Type returnType, + bool returnDefault) { Check.NotNull(source, nameof(source)); Check.NotNull(returnType, nameof(returnType)); @@ -1181,7 +1203,8 @@ private SqlExpression TranslateExpression(Expression expression) } private SqlExpression TranslateLambdaExpression( - ShapedQueryExpression shapedQueryExpression, LambdaExpression lambdaExpression) + ShapedQueryExpression shapedQueryExpression, + LambdaExpression lambdaExpression) => TranslateExpression(RemapLambdaBody(shapedQueryExpression, lambdaExpression)); private Expression RemapLambdaBody(ShapedQueryExpression shapedQueryExpression, LambdaExpression lambdaExpression) @@ -1209,7 +1232,8 @@ public WeakEntityExpandingExpressionVisitor( _sqlExpressionFactory = sqlExpressionFactory; } - public string TranslationErrorDetails => _sqlTranslator.TranslationErrorDetails; + public string TranslationErrorDetails + => _sqlTranslator.TranslationErrorDetails; public Expression Expand(SelectExpression selectExpression, Expression lambdaBody) { @@ -1355,10 +1379,10 @@ private Expression TryExpand(Expression source, MemberIdentity member) // TODO: The following code should also handle Function and SqlQuery mappings var table = navigation.DeclaringEntityType.BaseType == null || entityType.GetDiscriminatorProperty() != null - ? navigation.DeclaringEntityType.GetViewOrTableMappings().Single().Table - : navigation.DeclaringEntityType.GetViewOrTableMappings().Select(tm => tm.Table) - .Except(navigation.DeclaringEntityType.BaseType.GetViewOrTableMappings().Select(tm => tm.Table)) - .Single(); + ? navigation.DeclaringEntityType.GetViewOrTableMappings().Single().Table + : navigation.DeclaringEntityType.GetViewOrTableMappings().Select(tm => tm.Table) + .Except(navigation.DeclaringEntityType.BaseType.GetViewOrTableMappings().Select(tm => tm.Table)) + .Single(); if (table.GetReferencingRowInternalForeignKeys(foreignKey.PrincipalEntityType)?.Contains(foreignKey) == true) { // Mapped to same table @@ -1419,7 +1443,11 @@ private Expression TryExpand(Expression source, MemberIdentity member) } private static IDictionary GetPropertyExpressionFromSameTable( - IEntityType entityType, ITableBase table, SelectExpression selectExpression, ColumnExpression identifyingColumn, bool nullable) + IEntityType entityType, + ITableBase table, + SelectExpression selectExpression, + ColumnExpression identifyingColumn, + bool nullable) { if (identifyingColumn.Table is TableExpression tableExpression) { @@ -1447,7 +1475,8 @@ private static IDictionary GetPropertyExpressionFro if (identifyingColumn.Table is SelectExpression subquery) { var subqueryIdentifyingColumn = (ColumnExpression)subquery.Projection - .SingleOrDefault(e => string.Equals(e.Alias, identifyingColumn.Name, StringComparison.OrdinalIgnoreCase)).Expression; + .SingleOrDefault(e => string.Equals(e.Alias, identifyingColumn.Name, StringComparison.OrdinalIgnoreCase)) + .Expression; var subqueryPropertyExpressions = GetPropertyExpressionFromSameTable( entityType, table, subquery, subqueryIdentifyingColumn, nullable); @@ -1471,13 +1500,16 @@ private static IDictionary GetPropertyExpressionFro } private static IDictionary GetPropertyExpressionsFromJoinedTable( - IEntityType entityType, ITableBase table, TableExpressionBase tableExpression) + IEntityType entityType, + ITableBase table, + TableExpressionBase tableExpression) { var propertyExpressions = new Dictionary(); foreach (var property in entityType .GetAllBaseTypes().Concat(entityType.GetDerivedTypesInclusive()).SelectMany(EntityTypeExtensions.GetDeclaredProperties)) { - propertyExpressions[property] = new ColumnExpression(property, table.FindColumn(property), tableExpression, nullable: true); + propertyExpressions[property] = new ColumnExpression( + property, table.FindColumn(property), tableExpression, nullable: true); } return propertyExpressions; @@ -1495,7 +1527,7 @@ private ShapedQueryExpression TranslateTwoParameterSelector(ShapedQueryExpressio var replacement2 = AccessField(transparentIdentifierType, transparentIdentifierParameter, "Inner"); var newResultSelector = Expression.Lambda( new ReplacingExpressionVisitor( - new[] { original1, original2 }, new[] { replacement1, replacement2 }) + new[] { original1, original2 }, new[] { replacement1, replacement2 }) .Visit(resultSelector.Body), transparentIdentifierParameter); @@ -1527,7 +1559,10 @@ private static void HandleGroupByForAggregate(SelectExpression selectExpression, } private ShapedQueryExpression AggregateResultShaper( - ShapedQueryExpression source, Expression projection, bool throwWhenEmpty, Type resultType) + ShapedQueryExpression source, + Expression projection, + bool throwWhenEmpty, + Type resultType) { if (projection == null) { diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs index 476f3d90168..5e04ef4f8dc 100644 --- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs @@ -45,29 +45,41 @@ private static readonly MemberInfo _singleQueryResultCoordinatorResultReadyMembe // Performing collection materialization private static readonly MethodInfo _includeReferenceMethodInfo - = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(IncludeReference)); + = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(IncludeReference)); + private static readonly MethodInfo _initializeIncludeCollectionMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(InitializeIncludeCollection)); + private static readonly MethodInfo _populateIncludeCollectionMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(PopulateIncludeCollection)); + private static readonly MethodInfo _initializeSplitIncludeCollectionMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(InitializeSplitIncludeCollection)); + private static readonly MethodInfo _populateSplitIncludeCollectionMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(PopulateSplitIncludeCollection)); + private static readonly MethodInfo _populateSplitIncludeCollectionAsyncMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(PopulateSplitIncludeCollectionAsync)); + private static readonly MethodInfo _initializeCollectionMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(InitializeCollection)); + private static readonly MethodInfo _populateCollectionMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(PopulateCollection)); + private static readonly MethodInfo _initializeSplitCollectionMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(InitializeSplitCollection)); + private static readonly MethodInfo _populateSplitCollectionMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(PopulateSplitCollection)); + private static readonly MethodInfo _populateSplitCollectionAsyncMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(PopulateSplitCollectionAsync)); + private static readonly MethodInfo _taskAwaiterMethodInfo = typeof(ShaperProcessingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(TaskAwaiter)); + private static readonly MethodInfo _collectionAccessorAddMethodInfo = typeof(IClrCollectionAccessor).GetTypeInfo().GetDeclaredMethod(nameof(IClrCollectionAccessor.Add)); @@ -90,22 +102,29 @@ private static readonly MethodInfo _collectionAccessorAddMethodInfo // States to materialize only once private readonly IDictionary _variableShaperMapping = new Dictionary(); + // There are always entity variables to avoid materializing same entity twice private readonly List _variables = new List(); + private readonly List _expressions = new List(); + // IncludeExpressions are added at the end in case they are using ValuesArray private readonly List _includeExpressions = new List(); + // If there is collection shaper then we need to construct ValuesArray to store values temporarily in ResultContext private List _collectionPopulatingExpressions; private Expression _valuesArrayExpression; private List _valuesArrayInitializers; + private bool _containsCollectionMaterialization; + // Since identifiers for collection are not part of larger lambda they don't cannot use caching to materialize only once. private bool _inline; // States to convert code to data reader read private readonly IDictionary> _materializationContextBindings = new Dictionary>(); + private readonly IDictionary entityTypeIdentifyingExpressionOffsets = new Dictionary(); @@ -183,6 +202,7 @@ private ShaperProcessingExpressionVisitor( { _readerColumns = new ReaderColumn[_selectExpression.Projection.Count]; } + _generateCommandCache = true; _detailedErrorsEnabled = parentVisitor._detailedErrorsEnabled; _isTracking = parentVisitor.QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.TrackAll; @@ -274,13 +294,15 @@ public LambdaExpression ProcessShaper( if (_isAsync) { - var tasks = Expression.NewArrayInit(typeof(Func), _collectionPopulatingExpressions.Select( - e => Expression.Lambda>(e))); - relatedDataLoaders = Expression.Lambda>( - Expression.Call(_taskAwaiterMethodInfo, tasks), - QueryCompilationContext.QueryContextParameter, - _executionStrategyParameter, - _resultCoordinatorParameter); + var tasks = Expression.NewArrayInit( + typeof(Func), _collectionPopulatingExpressions.Select( + e => Expression.Lambda>(e))); + relatedDataLoaders = + Expression.Lambda>( + Expression.Call(_taskAwaiterMethodInfo, tasks), + QueryCompilationContext.QueryContextParameter, + _executionStrategyParameter, + _resultCoordinatorParameter); } else { @@ -407,7 +429,7 @@ protected override Expression VisitExtension(Expression extensionExpression) } case ProjectionBindingExpression projectionBindingExpression - when _inline: + when _inline: { var projectionIndex = (int)GetProjectionIndex(projectionBindingExpression); var projection = _selectExpression.Projection[projectionIndex]; @@ -421,7 +443,7 @@ protected override Expression VisitExtension(Expression extensionExpression) } case ProjectionBindingExpression projectionBindingExpression - when !_inline: + when !_inline: { var key = GenerateKey(projectionBindingExpression); if (_variableShaperMapping.TryGetValue(key, out var accessor)) @@ -436,13 +458,15 @@ protected override Expression VisitExtension(Expression extensionExpression) var valueParameter = Expression.Parameter(projectionBindingExpression.Type); _variables.Add(valueParameter); - _expressions.Add(Expression.Assign(valueParameter, - CreateGetValueExpression( - _dataReaderParameter, - projectionIndex, - nullable, - projection.Expression.TypeMapping, - valueParameter.Type))); + _expressions.Add( + Expression.Assign( + valueParameter, + CreateGetValueExpression( + _dataReaderParameter, + projectionIndex, + nullable, + projection.Expression.TypeMapping, + valueParameter.Type))); if (_containsCollectionMaterialization) { @@ -476,8 +500,9 @@ protected override Expression VisitExtension(Expression extensionExpression) relationalCollectionShaperExpression) { var innerShaper = new ShaperProcessingExpressionVisitor( - _parentVisitor, _resultCoordinatorParameter, _selectExpression, _dataReaderParameter, _resultContextParameter, - _readerColumns) + _parentVisitor, _resultCoordinatorParameter, _selectExpression, _dataReaderParameter, + _resultContextParameter, + _readerColumns) .ProcessShaper(relationalCollectionShaperExpression.InnerShaper, out _, out _); var entityType = entity.Type; @@ -510,49 +535,59 @@ protected override Expression VisitExtension(Expression extensionExpression) var collectionIdConstant = Expression.Constant(relationalCollectionShaperExpression.CollectionId); - _includeExpressions.Add(Expression.Call( - _initializeIncludeCollectionMethodInfo.MakeGenericMethod(entityType, includingEntityType), - collectionIdConstant, - QueryCompilationContext.QueryContextParameter, - _dataReaderParameter, - _resultCoordinatorParameter, - entity, - Expression.Constant(parentIdentifierLambda.Compile()), - Expression.Constant(outerIdentifierLambda.Compile()), - Expression.Constant(navigation), - Expression.Constant(navigation.GetCollectionAccessor()), - Expression.Constant(_isTracking))); + _includeExpressions.Add( + Expression.Call( + _initializeIncludeCollectionMethodInfo.MakeGenericMethod(entityType, includingEntityType), + collectionIdConstant, + QueryCompilationContext.QueryContextParameter, + _dataReaderParameter, + _resultCoordinatorParameter, + entity, + Expression.Constant(parentIdentifierLambda.Compile()), + Expression.Constant(outerIdentifierLambda.Compile()), + Expression.Constant(navigation), + Expression.Constant(navigation.GetCollectionAccessor()), + Expression.Constant(_isTracking))); var relatedEntityType = innerShaper.ReturnType; var inverseNavigation = navigation.Inverse; - _collectionPopulatingExpressions.Add(Expression.Call( - _populateIncludeCollectionMethodInfo.MakeGenericMethod(includingEntityType, relatedEntityType), - collectionIdConstant, - QueryCompilationContext.QueryContextParameter, - _dataReaderParameter, - _resultCoordinatorParameter, - Expression.Constant(parentIdentifierLambda.Compile()), - Expression.Constant(outerIdentifierLambda.Compile()), - Expression.Constant(selfIdentifierLambda.Compile()), - Expression.Constant(relationalCollectionShaperExpression.ParentIdentifierValueComparers, typeof(IReadOnlyList)), - Expression.Constant(relationalCollectionShaperExpression.OuterIdentifierValueComparers, typeof(IReadOnlyList)), - Expression.Constant(relationalCollectionShaperExpression.SelfIdentifierValueComparers, typeof(IReadOnlyList)), - Expression.Constant(innerShaper.Compile()), - Expression.Constant(inverseNavigation, typeof(INavigationBase)), - Expression.Constant( - GenerateFixup( - includingEntityType, relatedEntityType, navigation, inverseNavigation).Compile()), - Expression.Constant(_isTracking))); + _collectionPopulatingExpressions.Add( + Expression.Call( + _populateIncludeCollectionMethodInfo.MakeGenericMethod(includingEntityType, relatedEntityType), + collectionIdConstant, + QueryCompilationContext.QueryContextParameter, + _dataReaderParameter, + _resultCoordinatorParameter, + Expression.Constant(parentIdentifierLambda.Compile()), + Expression.Constant(outerIdentifierLambda.Compile()), + Expression.Constant(selfIdentifierLambda.Compile()), + Expression.Constant( + relationalCollectionShaperExpression.ParentIdentifierValueComparers, + typeof(IReadOnlyList)), + Expression.Constant( + relationalCollectionShaperExpression.OuterIdentifierValueComparers, + typeof(IReadOnlyList)), + Expression.Constant( + relationalCollectionShaperExpression.SelfIdentifierValueComparers, + typeof(IReadOnlyList)), + Expression.Constant(innerShaper.Compile()), + Expression.Constant(inverseNavigation, typeof(INavigationBase)), + Expression.Constant( + GenerateFixup( + includingEntityType, relatedEntityType, navigation, inverseNavigation).Compile()), + Expression.Constant(_isTracking))); } else if (includeExpression.NavigationExpression is RelationalSplitCollectionShaperExpression relationalSplitCollectionShaperExpression) { - var innerProcessor = new ShaperProcessingExpressionVisitor(_parentVisitor, _resultCoordinatorParameter, + var innerProcessor = new ShaperProcessingExpressionVisitor( + _parentVisitor, _resultCoordinatorParameter, _executionStrategyParameter, relationalSplitCollectionShaperExpression.SelectExpression, _tags); - var innerShaper = innerProcessor.ProcessShaper(relationalSplitCollectionShaperExpression.InnerShaper, - out var relationalCommandCache, - out var relatedDataLoaders); + var innerShaper = innerProcessor.ProcessShaper( + relationalSplitCollectionShaperExpression.InnerShaper, + out var relationalCommandCache, + out var relatedDataLoaders); var entityType = entity.Type; var navigation = includeExpression.Navigation; @@ -583,41 +618,46 @@ protected override Expression VisitExtension(Expression extensionExpression) var collectionIdConstant = Expression.Constant(relationalSplitCollectionShaperExpression.CollectionId); - _includeExpressions.Add(Expression.Call( - _initializeSplitIncludeCollectionMethodInfo.MakeGenericMethod(entityType, includingEntityType), - collectionIdConstant, - QueryCompilationContext.QueryContextParameter, - _dataReaderParameter, - _resultCoordinatorParameter, - entity, - Expression.Constant(parentIdentifierLambda.Compile()), - Expression.Constant(navigation), - Expression.Constant(navigation.GetCollectionAccessor()), - Expression.Constant(_isTracking))); + _includeExpressions.Add( + Expression.Call( + _initializeSplitIncludeCollectionMethodInfo.MakeGenericMethod(entityType, includingEntityType), + collectionIdConstant, + QueryCompilationContext.QueryContextParameter, + _dataReaderParameter, + _resultCoordinatorParameter, + entity, + Expression.Constant(parentIdentifierLambda.Compile()), + Expression.Constant(navigation), + Expression.Constant(navigation.GetCollectionAccessor()), + Expression.Constant(_isTracking))); var relatedEntityType = innerShaper.ReturnType; var inverseNavigation = navigation.Inverse; - _collectionPopulatingExpressions.Add(Expression.Call( - (_isAsync ? _populateSplitIncludeCollectionAsyncMethodInfo : _populateSplitIncludeCollectionMethodInfo) + _collectionPopulatingExpressions.Add( + Expression.Call( + (_isAsync ? _populateSplitIncludeCollectionAsyncMethodInfo : _populateSplitIncludeCollectionMethodInfo) .MakeGenericMethod(includingEntityType, relatedEntityType), - collectionIdConstant, - Expression.Convert(QueryCompilationContext.QueryContextParameter, typeof(RelationalQueryContext)), - _executionStrategyParameter, - _resultCoordinatorParameter, - Expression.Constant(relationalCommandCache), - Expression.Constant(childIdentifierLambda.Compile()), - Expression.Constant(relationalSplitCollectionShaperExpression.IdentifierValueComparers, typeof(IReadOnlyList)), - Expression.Constant(innerShaper.Compile()), - Expression.Constant(relatedDataLoaders?.Compile(), - _isAsync - ? typeof(Func) - : typeof(Action)), - Expression.Constant(inverseNavigation, typeof(INavigationBase)), - Expression.Constant( - GenerateFixup( - includingEntityType, relatedEntityType, navigation, inverseNavigation).Compile()), - Expression.Constant(_isTracking))); + collectionIdConstant, + Expression.Convert(QueryCompilationContext.QueryContextParameter, typeof(RelationalQueryContext)), + _executionStrategyParameter, + _resultCoordinatorParameter, + Expression.Constant(relationalCommandCache), + Expression.Constant(childIdentifierLambda.Compile()), + Expression.Constant( + relationalSplitCollectionShaperExpression.IdentifierValueComparers, + typeof(IReadOnlyList)), + Expression.Constant(innerShaper.Compile()), + Expression.Constant( + relatedDataLoaders?.Compile(), + _isAsync + ? typeof(Func) + : typeof(Action)), + Expression.Constant(inverseNavigation, typeof(INavigationBase)), + Expression.Constant( + GenerateFixup( + includingEntityType, relatedEntityType, navigation, inverseNavigation).Compile()), + Expression.Constant(_isTracking))); } else { @@ -657,8 +697,9 @@ protected override Expression VisitExtension(Expression extensionExpression) if (!_variableShaperMapping.TryGetValue(key, out var accessor)) { var innerShaper = new ShaperProcessingExpressionVisitor( - _parentVisitor, _resultCoordinatorParameter, _selectExpression, _dataReaderParameter, _resultContextParameter, - _readerColumns) + _parentVisitor, _resultCoordinatorParameter, _selectExpression, _dataReaderParameter, + _resultContextParameter, + _readerColumns) .ProcessShaper(relationalCollectionShaperExpression.InnerShaper, out _, out _); var navigation = relationalCollectionShaperExpression.Navigation; @@ -710,19 +751,26 @@ protected override Expression VisitExtension(Expression extensionExpression) Expression.Constant(_valuesArrayInitializers.Count - 1)), relationalCollectionShaperExpression.Type); - _collectionPopulatingExpressions.Add(Expression.Call( - _populateCollectionMethodInfo.MakeGenericMethod(collectionType, elementType, relatedElementType), - collectionIdConstant, - QueryCompilationContext.QueryContextParameter, - _dataReaderParameter, - _resultCoordinatorParameter, - Expression.Constant(parentIdentifierLambda.Compile()), - Expression.Constant(outerIdentifierLambda.Compile()), - Expression.Constant(selfIdentifierLambda.Compile()), - Expression.Constant(relationalCollectionShaperExpression.ParentIdentifierValueComparers, typeof(IReadOnlyList)), - Expression.Constant(relationalCollectionShaperExpression.OuterIdentifierValueComparers, typeof(IReadOnlyList)), - Expression.Constant(relationalCollectionShaperExpression.SelfIdentifierValueComparers, typeof(IReadOnlyList)), - Expression.Constant(innerShaper.Compile()))); + _collectionPopulatingExpressions.Add( + Expression.Call( + _populateCollectionMethodInfo.MakeGenericMethod(collectionType, elementType, relatedElementType), + collectionIdConstant, + QueryCompilationContext.QueryContextParameter, + _dataReaderParameter, + _resultCoordinatorParameter, + Expression.Constant(parentIdentifierLambda.Compile()), + Expression.Constant(outerIdentifierLambda.Compile()), + Expression.Constant(selfIdentifierLambda.Compile()), + Expression.Constant( + relationalCollectionShaperExpression.ParentIdentifierValueComparers, + typeof(IReadOnlyList)), + Expression.Constant( + relationalCollectionShaperExpression.OuterIdentifierValueComparers, + typeof(IReadOnlyList)), + Expression.Constant( + relationalCollectionShaperExpression.SelfIdentifierValueComparers, + typeof(IReadOnlyList)), + Expression.Constant(innerShaper.Compile()))); _variableShaperMapping[key] = accessor; } @@ -735,11 +783,13 @@ protected override Expression VisitExtension(Expression extensionExpression) var key = GenerateKey(relationalSplitCollectionShaperExpression); if (!_variableShaperMapping.TryGetValue(key, out var accessor)) { - var innerProcessor = new ShaperProcessingExpressionVisitor(_parentVisitor, _resultCoordinatorParameter, + var innerProcessor = new ShaperProcessingExpressionVisitor( + _parentVisitor, _resultCoordinatorParameter, _executionStrategyParameter, relationalSplitCollectionShaperExpression.SelectExpression, _tags); - var innerShaper = innerProcessor.ProcessShaper(relationalSplitCollectionShaperExpression.InnerShaper, - out var relationalCommandCache, - out var relatedDataLoaders); + var innerShaper = innerProcessor.ProcessShaper( + relationalSplitCollectionShaperExpression.InnerShaper, + out var relationalCommandCache, + out var relatedDataLoaders); var navigation = relationalSplitCollectionShaperExpression.Navigation; var collectionAccessor = navigation?.GetCollectionAccessor(); @@ -788,21 +838,25 @@ protected override Expression VisitExtension(Expression extensionExpression) Expression.Constant(_valuesArrayInitializers.Count - 1)), relationalSplitCollectionShaperExpression.Type); - _collectionPopulatingExpressions.Add(Expression.Call( - (_isAsync ? _populateSplitCollectionAsyncMethodInfo : _populateSplitCollectionMethodInfo) + _collectionPopulatingExpressions.Add( + Expression.Call( + (_isAsync ? _populateSplitCollectionAsyncMethodInfo : _populateSplitCollectionMethodInfo) .MakeGenericMethod(collectionType, elementType, relatedElementType), - collectionIdConstant, - Expression.Convert(QueryCompilationContext.QueryContextParameter, typeof(RelationalQueryContext)), - _executionStrategyParameter, - _resultCoordinatorParameter, - Expression.Constant(relationalCommandCache), - Expression.Constant(childIdentifierLambda.Compile()), - Expression.Constant(relationalSplitCollectionShaperExpression.IdentifierValueComparers, typeof(IReadOnlyList)), - Expression.Constant(innerShaper.Compile()), - Expression.Constant(relatedDataLoaders?.Compile(), - _isAsync - ? typeof(Func) - : typeof(Action)))); + collectionIdConstant, + Expression.Convert(QueryCompilationContext.QueryContextParameter, typeof(RelationalQueryContext)), + _executionStrategyParameter, + _resultCoordinatorParameter, + Expression.Constant(relationalCommandCache), + Expression.Constant(childIdentifierLambda.Compile()), + Expression.Constant( + relationalSplitCollectionShaperExpression.IdentifierValueComparers, + typeof(IReadOnlyList)), + Expression.Constant(innerShaper.Compile()), + Expression.Constant( + relatedDataLoaders?.Compile(), + _isAsync + ? typeof(Func) + : typeof(Action)))); _variableShaperMapping[key] = accessor; } @@ -822,18 +876,21 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp Check.NotNull(methodCallExpression, nameof(methodCallExpression)); if (methodCallExpression.Method.IsGenericMethod - && methodCallExpression.Method.GetGenericMethodDefinition() == Infrastructure.ExpressionExtensions.ValueBufferTryReadValueMethod) + && methodCallExpression.Method.GetGenericMethodDefinition() + == Infrastructure.ExpressionExtensions.ValueBufferTryReadValueMethod) { var property = (IProperty)((ConstantExpression)methodCallExpression.Arguments[2]).Value; var mappingParameter = (ParameterExpression)((MethodCallExpression)methodCallExpression.Arguments[0]).Object; var projectionIndex = property == null - ? entityTypeIdentifyingExpressionOffsets[mappingParameter] + (int)((ConstantExpression)methodCallExpression.Arguments[1]).Value + ? entityTypeIdentifyingExpressionOffsets[mappingParameter] + + (int)((ConstantExpression)methodCallExpression.Arguments[1]).Value : _materializationContextBindings[mappingParameter][property]; var projection = _selectExpression.Projection[projectionIndex]; var nullable = IsNullableProjection(projection); - Check.DebugAssert(!nullable || property != null || methodCallExpression.Type.IsNullableType(), + Check.DebugAssert( + !nullable || property != null || methodCallExpression.Type.IsNullableType(), "For nullable reads the return type must be null unless property is specified."); return CreateGetValueExpression( @@ -915,7 +972,8 @@ private Expression CreateGetValueExpression( Type type, IPropertyBase property = null) { - Check.DebugAssert(property != null || type.IsNullableType(), "Must read nullable value from database if property is not specified."); + Check.DebugAssert( + property != null || type.IsNullableType(), "Must read nullable value from database if property is not specified."); var getMethod = typeMapping.GetDataReaderMethod(); @@ -1012,7 +1070,10 @@ Expression valueExpression [MethodImpl(MethodImplOptions.AggressiveInlining)] private static TValue ThrowReadValueException( - Exception exception, object value, Type expectedType, IPropertyBase property = null) + Exception exception, + object value, + Type expectedType, + IPropertyBase property = null) { var actualType = value?.GetType(); @@ -1029,19 +1090,19 @@ private static TValue ThrowReadValueException( message = exception is NullReferenceException || Equals(value, DBNull.Value) - ? CoreStrings.ErrorMaterializingPropertyNullReference(entityType, propertyName, expectedType) - : exception is InvalidCastException - ? CoreStrings.ErrorMaterializingPropertyInvalidCast(entityType, propertyName, expectedType, actualType) - : CoreStrings.ErrorMaterializingProperty(entityType, propertyName); + ? CoreStrings.ErrorMaterializingPropertyNullReference(entityType, propertyName, expectedType) + : exception is InvalidCastException + ? CoreStrings.ErrorMaterializingPropertyInvalidCast(entityType, propertyName, expectedType, actualType) + : CoreStrings.ErrorMaterializingProperty(entityType, propertyName); } else { message = exception is NullReferenceException || Equals(value, DBNull.Value) - ? CoreStrings.ErrorMaterializingValueNullReference(expectedType) - : exception is InvalidCastException - ? CoreStrings.ErrorMaterializingValueInvalidCast(expectedType, actualType) - : CoreStrings.ErrorMaterializingValue; + ? CoreStrings.ErrorMaterializingValueNullReference(expectedType) + : exception is InvalidCastException + ? CoreStrings.ErrorMaterializingValueInvalidCast(expectedType, actualType) + : CoreStrings.ErrorMaterializingValue; } throw new InvalidOperationException(message, exception); @@ -1151,13 +1212,15 @@ private static void PopulateIncludeCollection return; } - if (!CompareIdentifiers(outerIdentifierValueComparers, + if (!CompareIdentifiers( + outerIdentifierValueComparers, outerIdentifier(queryContext, dbDataReader), collectionMaterializationContext.OuterIdentifier)) { // Outer changed so collection has ended. Materialize last element. GenerateCurrentElementIfPending(); // If parent also changed then this row is now pointing to element of next collection - if (!CompareIdentifiers(parentIdentifierValueComparers, + if (!CompareIdentifiers( + parentIdentifierValueComparers, parentIdentifier(queryContext, dbDataReader), collectionMaterializationContext.ParentIdentifier)) { resultCoordinator.HasNext = true; @@ -1310,7 +1373,6 @@ bool InitializeReader(DbContext _, bool result) queryContext.Context, queryContext.CommandLogger)); - return result; } @@ -1324,7 +1386,8 @@ bool InitializeReader(DbContext _, bool result) { while (dataReaderContext.HasNext ?? dbDataReader.Read()) { - if (!CompareIdentifiers(identifierValueComparers, + if (!CompareIdentifiers( + identifierValueComparers, splitQueryCollectionContext.ParentIdentifier, childIdentifier(queryContext, dbDataReader))) { dataReaderContext.HasNext = true; @@ -1384,14 +1447,14 @@ async Task InitializeReaderAsync(DbContext _, bool result, CancellationTok dataReader = await relationalCommand.ExecuteReaderAsync( - new RelationalCommandParameterObject( - queryContext.Connection, - queryContext.ParameterValues, - relationalCommandCache.ReaderColumns, - queryContext.Context, - queryContext.CommandLogger), - cancellationToken) - .ConfigureAwait(false); + new RelationalCommandParameterObject( + queryContext.Connection, + queryContext.ParameterValues, + relationalCommandCache.ReaderColumns, + queryContext.Context, + queryContext.CommandLogger), + cancellationToken) + .ConfigureAwait(false); return result; } @@ -1406,7 +1469,8 @@ async Task InitializeReaderAsync(DbContext _, bool result, CancellationTok { while (dataReaderContext.HasNext ?? await dbDataReader.ReadAsync(queryContext.CancellationToken).ConfigureAwait(false)) { - if (!CompareIdentifiers(identifierValueComparers, + if (!CompareIdentifiers( + identifierValueComparers, splitQueryCollectionContext.ParentIdentifier, childIdentifier(queryContext, dbDataReader))) { dataReaderContext.HasNext = true; @@ -1422,6 +1486,7 @@ async Task InitializeReaderAsync(DbContext _, bool result, CancellationTok { await relatedDataLoaders(queryContext, executionStrategy, resultCoordinator).ConfigureAwait(false); } + var relatedEntity = innerShaper( queryContext, dbDataReader, splitQueryCollectionContext.ResultContext, resultCoordinator); @@ -1490,13 +1555,15 @@ private static void PopulateCollection( return; } - if (!CompareIdentifiers(outerIdentifierValueComparers, + if (!CompareIdentifiers( + outerIdentifierValueComparers, outerIdentifier(queryContext, dbDataReader), collectionMaterializationContext.OuterIdentifier)) { // Outer changed so collection has ended. Materialize last element. GenerateCurrentElementIfPending(); // If parent also changed then this row is now pointing to element of next collection - if (!CompareIdentifiers(parentIdentifierValueComparers, + if (!CompareIdentifiers( + parentIdentifierValueComparers, parentIdentifier(queryContext, dbDataReader), collectionMaterializationContext.ParentIdentifier)) { resultCoordinator.HasNext = true; @@ -1514,7 +1581,8 @@ private static void PopulateCollection( if (collectionMaterializationContext.SelfIdentifier != null) { - if (CompareIdentifiers(selfIdentifierValueComparers, + if (CompareIdentifiers( + selfIdentifierValueComparers, innerKey, collectionMaterializationContext.SelfIdentifier)) { // repeated row for current element @@ -1622,7 +1690,6 @@ bool InitializeReader(DbContext _, bool result) queryContext.Context, queryContext.CommandLogger)); - return result; } @@ -1640,7 +1707,8 @@ bool InitializeReader(DbContext _, bool result) while (dataReaderContext.HasNext ?? dbDataReader.Read()) { - if (!CompareIdentifiers(identifierValueComparers, + if (!CompareIdentifiers( + identifierValueComparers, splitQueryCollectionContext.ParentIdentifier, childIdentifier(queryContext, dbDataReader))) { dataReaderContext.HasNext = true; @@ -1688,14 +1756,14 @@ async Task InitializeReaderAsync(DbContext _, bool result, CancellationTok dataReader = await relationalCommand.ExecuteReaderAsync( - new RelationalCommandParameterObject( - queryContext.Connection, - queryContext.ParameterValues, - relationalCommandCache.ReaderColumns, - queryContext.Context, - queryContext.CommandLogger), - cancellationToken) - .ConfigureAwait(false); + new RelationalCommandParameterObject( + queryContext.Connection, + queryContext.ParameterValues, + relationalCommandCache.ReaderColumns, + queryContext.Context, + queryContext.CommandLogger), + cancellationToken) + .ConfigureAwait(false); return result; } @@ -1714,7 +1782,8 @@ async Task InitializeReaderAsync(DbContext _, bool result, CancellationTok while (dataReaderContext.HasNext ?? await dbDataReader.ReadAsync(queryContext.CancellationToken).ConfigureAwait(false)) { - if (!CompareIdentifiers(identifierValueComparers, + if (!CompareIdentifiers( + identifierValueComparers, splitQueryCollectionContext.ParentIdentifier, childIdentifier(queryContext, dbDataReader))) { dataReaderContext.HasNext = true; @@ -1730,8 +1799,9 @@ async Task InitializeReaderAsync(DbContext _, bool result, CancellationTok { await relatedDataLoaders(queryContext, executionStrategy, resultCoordinator).ConfigureAwait(false); } + var relatedElement = innerShaper( - queryContext, dbDataReader, splitQueryCollectionContext.ResultContext, resultCoordinator); + queryContext, dbDataReader, splitQueryCollectionContext.ResultContext, resultCoordinator); ((TCollection)splitQueryCollectionContext.Collection).Add(relatedElement); } diff --git a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.cs index 9d6e4ad061a..440d6379702 100644 --- a/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalShapedQueryCompilingExpressionVisitor.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Data.Common; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; @@ -60,7 +59,8 @@ protected override Expression VisitShapedQuery(ShapedQueryExpression shapedQuery VerifyNoClientConstant(shapedQueryExpression.ShaperExpression); var nonComposedFromSql = selectExpression.IsNonComposedFromSql(); - var splitQuery = ((RelationalQueryCompilationContext)QueryCompilationContext).QuerySplittingBehavior == QuerySplittingBehavior.SplitQuery; + var splitQuery = ((RelationalQueryCompilationContext)QueryCompilationContext).QuerySplittingBehavior + == QuerySplittingBehavior.SplitQuery; var shaper = new ShaperProcessingExpressionVisitor(this, selectExpression, _tags, splitQuery, nonComposedFromSql).ProcessShaper( shapedQueryExpression.ShaperExpression, out var relationalCommandCache, out var relatedDataLoaders); @@ -70,11 +70,13 @@ protected override Expression VisitShapedQuery(ShapedQueryExpression shapedQuery typeof(FromSqlQueryingEnumerable<>).MakeGenericType(shaper.ReturnType).GetConstructors()[0], Expression.Convert(QueryCompilationContext.QueryContextParameter, typeof(RelationalQueryContext)), Expression.Constant(relationalCommandCache), - Expression.Constant(selectExpression.Projection.Select(pe => ((ColumnExpression)pe.Expression).Name).ToList(), + Expression.Constant( + selectExpression.Projection.Select(pe => ((ColumnExpression)pe.Expression).Name).ToList(), typeof(IReadOnlyList)), Expression.Constant(shaper.Compile()), Expression.Constant(_contextType), - Expression.Constant(QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution)); + Expression.Constant( + QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution)); } if (splitQuery) @@ -95,16 +97,18 @@ protected override Expression VisitShapedQuery(ShapedQueryExpression shapedQuery relatedDataLoadersParameter, relatedDataLoadersAsyncParameter, Expression.Constant(_contextType), - Expression.Constant(QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution)); + Expression.Constant( + QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution)); } return Expression.New( - typeof(SingleQueryingEnumerable<>).MakeGenericType(shaper.ReturnType).GetConstructors()[0], - Expression.Convert(QueryCompilationContext.QueryContextParameter, typeof(RelationalQueryContext)), - Expression.Constant(relationalCommandCache), - Expression.Constant(shaper.Compile()), - Expression.Constant(_contextType), - Expression.Constant(QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution)); + typeof(SingleQueryingEnumerable<>).MakeGenericType(shaper.ReturnType).GetConstructors()[0], + Expression.Convert(QueryCompilationContext.QueryContextParameter, typeof(RelationalQueryContext)), + Expression.Constant(relationalCommandCache), + Expression.Constant(shaper.Compile()), + Expression.Constant(_contextType), + Expression.Constant( + QueryCompilationContext.QueryTrackingBehavior == QueryTrackingBehavior.NoTrackingWithIdentityResolution)); } } } diff --git a/src/EFCore.Relational/Query/RelationalSplitCollectionShaperExpression.cs b/src/EFCore.Relational/Query/RelationalSplitCollectionShaperExpression.cs index ab21f3b1bd2..a84fd796c34 100644 --- a/src/EFCore.Relational/Query/RelationalSplitCollectionShaperExpression.cs +++ b/src/EFCore.Relational/Query/RelationalSplitCollectionShaperExpression.cs @@ -14,7 +14,8 @@ namespace Microsoft.EntityFrameworkCore.Query { /// /// - /// An expression that represents creation of a collection during split query for relational provider in . + /// An expression that represents creation of a collection during split query for relational provider in + /// . /// /// /// This type is typically used by database providers (and other extensions). It is generally @@ -64,18 +65,22 @@ public RelationalSplitCollectionShaperExpression( /// A unique id for this collection shaper. /// public virtual int CollectionId { get; } + /// /// The identifier for the parent element. /// public virtual Expression ParentIdentifier { get; } + /// /// The identifier for the child element. /// public virtual Expression ChildIdentifier { get; } + /// /// The list of value comparers to compare identifiers. /// public virtual IReadOnlyList IdentifierValueComparers { get; } + /// /// The SQL query to get values for this collection from database. /// @@ -85,19 +90,24 @@ public RelationalSplitCollectionShaperExpression( /// The expression to create inner elements. /// public virtual Expression InnerShaper { get; } + /// - /// The navigation if associated with the collection. + /// The navigation if associated with the collection. /// public virtual INavigationBase Navigation { get; } + /// /// The clr type of elements of the collection. /// public virtual Type ElementType { get; } /// - public override Type Type => Navigation?.ClrType ?? typeof(List<>).MakeGenericType(ElementType); + public override Type Type + => Navigation?.ClrType ?? typeof(List<>).MakeGenericType(ElementType); + /// - public sealed override ExpressionType NodeType => ExpressionType.Extension; + public sealed override ExpressionType NodeType + => ExpressionType.Extension; /// protected override Expression VisitChildren(ExpressionVisitor visitor) @@ -116,10 +126,10 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual RelationalSplitCollectionShaperExpression Update( [NotNull] Expression parentIdentifier, @@ -137,7 +147,8 @@ public virtual RelationalSplitCollectionShaperExpression Update( || selectExpression != SelectExpression || innerShaper != InnerShaper ? new RelationalSplitCollectionShaperExpression( - CollectionId, parentIdentifier, childIdentifier, IdentifierValueComparers, selectExpression, innerShaper, Navigation, ElementType) + CollectionId, parentIdentifier, childIdentifier, IdentifierValueComparers, selectExpression, innerShaper, + Navigation, ElementType) : this; } diff --git a/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs index b5e6119320c..31e5c090df6 100644 --- a/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs @@ -33,15 +33,18 @@ public class RelationalSqlTranslatingExpressionVisitor : ExpressionVisitor private static readonly MethodInfo _parameterValueExtractor = typeof(RelationalSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterValueExtractor)); + private static readonly MethodInfo _parameterListValueExtractor = typeof(RelationalSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterListValueExtractor)); private static readonly MethodInfo _stringEqualsWithStringComparison = typeof(string).GetRuntimeMethod(nameof(string.Equals), new[] { typeof(string), typeof(StringComparison) }); + private static readonly MethodInfo _stringEqualsWithStringComparisonStatic = typeof(string).GetRuntimeMethod(nameof(string.Equals), new[] { typeof(string), typeof(string), typeof(StringComparison) }); + private static readonly MethodInfo _objectEqualsMethodInfo - = typeof(object).GetRuntimeMethod(nameof(object.Equals), new[] { typeof(object), typeof(object) }); + = typeof(object).GetRuntimeMethod(nameof(object.Equals), new[] { typeof(object), typeof(object) }); private readonly QueryCompilationContext _queryCompilationContext; private readonly IModel _model; @@ -157,8 +160,9 @@ public virtual SqlExpression TranslateAverage([NotNull] SqlExpression sqlExpress || inputType == typeof(long)) { sqlExpression = sqlExpression is DistinctExpression distinctExpression - ? new DistinctExpression(_sqlExpressionFactory.ApplyDefaultTypeMapping( - _sqlExpressionFactory.Convert(distinctExpression.Operand, typeof(double)))) + ? new DistinctExpression( + _sqlExpressionFactory.ApplyDefaultTypeMapping( + _sqlExpressionFactory.Convert(distinctExpression.Operand, typeof(double)))) : _sqlExpressionFactory.ApplyDefaultTypeMapping( _sqlExpressionFactory.Convert(sqlExpression, typeof(double))); } @@ -324,7 +328,7 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) var visitedRight = Visit(right); if ((binaryExpression.NodeType == ExpressionType.Equal - || binaryExpression.NodeType == ExpressionType.NotEqual) + || binaryExpression.NodeType == ExpressionType.NotEqual) // Visited expression could be null, We need to pass MemberInitExpression && TryRewriteEntityEquality(binaryExpression.NodeType, visitedLeft ?? left, visitedRight ?? right, out var result)) { @@ -341,14 +345,14 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) return TranslationFailed(binaryExpression.Left, visitedLeft, out var sqlLeft) || TranslationFailed(binaryExpression.Right, visitedRight, out var sqlRight) - ? null - : uncheckedNodeTypeVariant == ExpressionType.Coalesce - ? _sqlExpressionFactory.Coalesce(sqlLeft, sqlRight) - : (Expression)_sqlExpressionFactory.MakeBinary( - uncheckedNodeTypeVariant, - sqlLeft, - sqlRight, - null); + ? null + : uncheckedNodeTypeVariant == ExpressionType.Coalesce + ? _sqlExpressionFactory.Coalesce(sqlLeft, sqlRight) + : (Expression)_sqlExpressionFactory.MakeBinary( + uncheckedNodeTypeVariant, + sqlLeft, + sqlRight, + null); static bool TryUnwrapConvertToObject(Expression expression, out Expression operand) { @@ -378,8 +382,8 @@ protected override Expression VisitConditional(ConditionalExpression conditional return TranslationFailed(conditionalExpression.Test, test, out var sqlTest) || TranslationFailed(conditionalExpression.IfTrue, ifTrue, out var sqlIfTrue) || TranslationFailed(conditionalExpression.IfFalse, ifFalse, out var sqlIfFalse) - ? null - : _sqlExpressionFactory.Case(new[] { new CaseWhenClause(sqlTest, sqlIfTrue) }, sqlIfFalse); + ? null + : _sqlExpressionFactory.Case(new[] { new CaseWhenClause(sqlTest, sqlIfTrue) }, sqlIfFalse); } /// @@ -404,7 +408,7 @@ protected override Expression VisitExtension(Expression extensionExpression) case ProjectionBindingExpression projectionBindingExpression: return projectionBindingExpression.ProjectionMember != null ? ((SelectExpression)projectionBindingExpression.QueryExpression) - .GetMappedProjection(projectionBindingExpression.ProjectionMember) + .GetMappedProjection(projectionBindingExpression.ProjectionMember) : null; case GroupByShaperExpression groupByShaperExpression: @@ -416,11 +420,16 @@ protected override Expression VisitExtension(Expression extensionExpression) } /// - protected override Expression VisitInvocation(InvocationExpression invocationExpression) => null; + protected override Expression VisitInvocation(InvocationExpression invocationExpression) + => null; + /// - protected override Expression VisitLambda(Expression lambdaExpression) => null; + protected override Expression VisitLambda(Expression lambdaExpression) + => null; + /// - protected override Expression VisitListInit(ListInitExpression listInitExpression) => null; + protected override Expression VisitListInit(ListInitExpression listInitExpression) + => null; /// protected override Expression VisitMember(MemberExpression memberExpression) @@ -579,7 +588,9 @@ GroupingElementExpression ApplyPredicate(GroupingElementExpression groupingEleme : groupingElement.ApplyPredicate(predicate); } - static GroupingElementExpression ApplySelector(GroupingElementExpression groupingElement, LambdaExpression lambdaExpression) + static GroupingElementExpression ApplySelector( + GroupingElementExpression groupingElement, + LambdaExpression lambdaExpression) { var selector = RemapLambda(groupingElement, lambdaExpression); @@ -613,10 +624,7 @@ SqlExpression GetExpressionForAggregation(GroupingElementExpression groupingElem } selector = _sqlExpressionFactory.Case( - new List - { - new CaseWhenClause(groupingElement.Predicate, selector) - }, + new List { new CaseWhenClause(groupingElement.Predicate, selector) }, elseResult: null); } @@ -722,10 +730,11 @@ static bool IsAggregateResultWithCustomShaper(MethodInfo method) var left = Visit(methodCallExpression.Object); var right = Visit(RemoveObjectConvert(methodCallExpression.Arguments[0])); - if (TryRewriteEntityEquality(ExpressionType.Equal, - left ?? methodCallExpression.Object, - right ?? methodCallExpression.Arguments[0], - out var result)) + if (TryRewriteEntityEquality( + ExpressionType.Equal, + left ?? methodCallExpression.Object, + right ?? methodCallExpression.Arguments[0], + out var result)) { return result; } @@ -748,14 +757,16 @@ static bool IsAggregateResultWithCustomShaper(MethodInfo method) if (methodCallExpression.Arguments[0].Type == typeof(object[]) && methodCallExpression.Arguments[0] is NewArrayExpression) { - return Visit(ConvertObjectArrayEqualityComparison( - methodCallExpression.Arguments[0], methodCallExpression.Arguments[1])); + return Visit( + ConvertObjectArrayEqualityComparison( + methodCallExpression.Arguments[0], methodCallExpression.Arguments[1])); } var left = Visit(RemoveObjectConvert(methodCallExpression.Arguments[0])); var right = Visit(RemoveObjectConvert(methodCallExpression.Arguments[1])); - if (TryRewriteEntityEquality(ExpressionType.Equal, + if (TryRewriteEntityEquality( + ExpressionType.Equal, left ?? methodCallExpression.Arguments[0], right ?? methodCallExpression.Arguments[1], out var result)) @@ -848,9 +859,10 @@ static bool IsAggregateResultWithCustomShaper(MethodInfo method) } else { - AddTranslationErrorDetails(CoreStrings.QueryUnableToTranslateMethod( - methodCallExpression.Method.DeclaringType?.DisplayName(), - methodCallExpression.Method.Name)); + AddTranslationErrorDetails( + CoreStrings.QueryUnableToTranslateMethod( + methodCallExpression.Method.DeclaringType?.DisplayName(), + methodCallExpression.Method.Name)); } } @@ -862,7 +874,8 @@ protected override Expression VisitNew(NewExpression newExpression) => GetConstantOrNull(Check.NotNull(newExpression, nameof(newExpression))); /// - protected override Expression VisitNewArray(NewArrayExpression newArrayExpression) => null; + protected override Expression VisitNewArray(NewArrayExpression newArrayExpression) + => null; /// protected override Expression VisitParameter(ParameterExpression parameterExpression) @@ -961,7 +974,8 @@ SqlExpression GeneratePredicateTPT(EntityProjectionExpression entityProjectionEx _sqlExpressionFactory.Constant(concreteEntityTypes[0].GetDiscriminatorValue())) : (Expression)_sqlExpressionFactory.In( discriminatorColumn, - _sqlExpressionFactory.Constant(concreteEntityTypes.Select(et => et.GetDiscriminatorValue()).ToList()), + _sqlExpressionFactory.Constant( + concreteEntityTypes.Select(et => et.GetDiscriminatorValue()).ToList()), negated: false); } } @@ -1067,7 +1081,8 @@ private SqlExpression BindProperty(EntityReferenceExpression entityReferenceExpr { if (entityReferenceExpression.ParameterEntity != null) { - return ((EntityProjectionExpression)Visit(entityReferenceExpression.ParameterEntity.ValueBufferExpression)).BindProperty(property); + return ((EntityProjectionExpression)Visit(entityReferenceExpression.ParameterEntity.ValueBufferExpression)).BindProperty( + property); } if (entityReferenceExpression.SubqueryEntity != null) @@ -1183,7 +1198,8 @@ private bool TryRewriteContainsEntity(Expression source, Expression item, out Ex { case SqlConstantExpression sqlConstantExpression: var values = (IEnumerable)sqlConstantExpression.Value; - var propertyValueList = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(property.ClrType.MakeNullable())); + var propertyValueList = + (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(property.ClrType.MakeNullable())); var propertyGetter = property.GetGetter(); foreach (var value in values) { @@ -1194,7 +1210,7 @@ private bool TryRewriteContainsEntity(Expression source, Expression item, out Ex break; case SqlParameterExpression sqlParameterExpression - when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal): + when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal): var lambda = Expression.Lambda( Expression.Call( _parameterListValueExtractor.MakeGenericMethod(entityType.ClrType, property.ClrType.MakeNullable()), @@ -1205,8 +1221,8 @@ when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParamet ); var newParameterName = - $"{RuntimeParameterPrefix}" + - $"{sqlParameterExpression.Name.Substring(QueryCompilationContext.QueryParameterPrefix.Length)}_{property.Name}"; + $"{RuntimeParameterPrefix}" + + $"{sqlParameterExpression.Name.Substring(QueryCompilationContext.QueryParameterPrefix.Length)}_{property.Name}"; rewrittenSource = _queryCompilationContext.RegisterRuntimeParameter(newParameterName, lambda); break; @@ -1215,10 +1231,11 @@ when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParamet return false; } - result = Visit(Expression.Call( - EnumerableMethods.Contains.MakeGenericMethod(property.ClrType.MakeNullable()), - rewrittenSource, - CreatePropertyAccessExpression(item, property))); + result = Visit( + Expression.Call( + EnumerableMethods.Contains.MakeGenericMethod(property.ClrType.MakeNullable()), + rewrittenSource, + CreatePropertyAccessExpression(item, property))); return true; } @@ -1247,41 +1264,47 @@ private bool TryRewriteEntityEquality(ExpressionType nodeType, Expression left, var requiredNonPkProperties = entityType1.GetProperties().Where(p => !p.IsNullable && !p.IsPrimaryKey()).ToList(); if (requiredNonPkProperties.Count > 0) { - result = Visit(requiredNonPkProperties.Select(p => - { - var comparison = Expression.Call(_objectEqualsMethodInfo, - Expression.Convert(CreatePropertyAccessExpression(nonNullEntityReference, p), typeof(object)), - Expression.Convert(Expression.Constant(null, p.ClrType.MakeNullable()), typeof(object))); + result = Visit( + requiredNonPkProperties.Select( + p => + { + var comparison = Expression.Call( + _objectEqualsMethodInfo, + Expression.Convert(CreatePropertyAccessExpression(nonNullEntityReference, p), typeof(object)), + Expression.Convert(Expression.Constant(null, p.ClrType.MakeNullable()), typeof(object))); - return nodeType == ExpressionType.Equal - ? (Expression)comparison - : Expression.Not(comparison); - }).Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.OrElse(l, r) : Expression.AndAlso(l, r))); + return nodeType == ExpressionType.Equal + ? (Expression)comparison + : Expression.Not(comparison); + }).Aggregate( + (l, r) => nodeType == ExpressionType.Equal ? Expression.OrElse(l, r) : Expression.AndAlso(l, r))); return true; } - else + + var allNonPkProperties = entityType1.GetProperties().Where(p => !p.IsPrimaryKey()).ToList(); + if (allNonPkProperties.Count > 0) { - var allNonPkProperties = entityType1.GetProperties().Where(p => !p.IsPrimaryKey()).ToList(); - if (allNonPkProperties.Count > 0) - { - result = Visit(allNonPkProperties.Select(p => + result = Visit( + allNonPkProperties.Select( + p => { - var comparison = Expression.Call(_objectEqualsMethodInfo, + var comparison = Expression.Call( + _objectEqualsMethodInfo, Expression.Convert(CreatePropertyAccessExpression(nonNullEntityReference, p), typeof(object)), Expression.Convert(Expression.Constant(null, p.ClrType.MakeNullable()), typeof(object))); return nodeType == ExpressionType.Equal ? (Expression)comparison : Expression.Not(comparison); - }).Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.AndAlso(l, r) : Expression.OrElse(l, r))); + }).Aggregate( + (l, r) => nodeType == ExpressionType.Equal ? Expression.AndAlso(l, r) : Expression.OrElse(l, r))); - return true; - } - - result = null; - return false; + return true; } + + result = null; + return false; } var primaryKeyProperties1 = entityType1.FindPrimaryKey()?.Properties; @@ -1290,16 +1313,19 @@ private bool TryRewriteEntityEquality(ExpressionType nodeType, Expression left, throw new InvalidOperationException(CoreStrings.EntityEqualityOnKeylessEntityNotSupported(entityType1.DisplayName())); } - result = Visit(primaryKeyProperties1.Select(p => - { - var comparison = Expression.Call(_objectEqualsMethodInfo, - Expression.Convert(CreatePropertyAccessExpression(nonNullEntityReference, p), typeof(object)), - Expression.Convert(Expression.Constant(null, p.ClrType.MakeNullable()), typeof(object))); + result = Visit( + primaryKeyProperties1.Select( + p => + { + var comparison = Expression.Call( + _objectEqualsMethodInfo, + Expression.Convert(CreatePropertyAccessExpression(nonNullEntityReference, p), typeof(object)), + Expression.Convert(Expression.Constant(null, p.ClrType.MakeNullable()), typeof(object))); - return nodeType == ExpressionType.Equal - ? (Expression)comparison - : Expression.Not(comparison); - }).Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.OrElse(l, r) : Expression.AndAlso(l, r))); + return nodeType == ExpressionType.Equal + ? (Expression)comparison + : Expression.Not(comparison); + }).Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.OrElse(l, r) : Expression.AndAlso(l, r))); return true; } @@ -1332,16 +1358,19 @@ private bool TryRewriteEntityEquality(ExpressionType nodeType, Expression left, CoreStrings.EntityEqualitySubqueryWithCompositeKeyNotSupported(entityType.DisplayName())); } - result = Visit(primaryKeyProperties.Select(p => - { - var comparison = Expression.Call(_objectEqualsMethodInfo, - Expression.Convert(CreatePropertyAccessExpression(left, p), typeof(object)), - Expression.Convert(CreatePropertyAccessExpression(right, p), typeof(object))); + result = Visit( + primaryKeyProperties.Select( + p => + { + var comparison = Expression.Call( + _objectEqualsMethodInfo, + Expression.Convert(CreatePropertyAccessExpression(left, p), typeof(object)), + Expression.Convert(CreatePropertyAccessExpression(right, p), typeof(object))); - return nodeType == ExpressionType.Equal - ? (Expression)comparison - : Expression.Not(comparison); - }).Aggregate((l, r) => Expression.AndAlso(l, r))); + return nodeType == ExpressionType.Equal + ? (Expression)comparison + : Expression.Not(comparison); + }).Aggregate((l, r) => Expression.AndAlso(l, r))); return true; } @@ -1355,7 +1384,7 @@ private Expression CreatePropertyAccessExpression(Expression target, IProperty p property.GetGetter().GetClrValue(sqlConstantExpression.Value), property.ClrType.MakeNullable()); case SqlParameterExpression sqlParameterExpression - when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal): + when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal): var lambda = Expression.Lambda( Expression.Call( _parameterValueExtractor.MakeGenericMethod(property.ClrType.MakeNullable()), @@ -1365,14 +1394,14 @@ when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParamet QueryCompilationContext.QueryContextParameter); var newParameterName = - $"{RuntimeParameterPrefix}" + - $"{sqlParameterExpression.Name.Substring(QueryCompilationContext.QueryParameterPrefix.Length)}_{property.Name}"; + $"{RuntimeParameterPrefix}" + + $"{sqlParameterExpression.Name.Substring(QueryCompilationContext.QueryParameterPrefix.Length)}_{property.Name}"; return _queryCompilationContext.RegisterRuntimeParameter(newParameterName, lambda); case MemberInitExpression memberInitExpression - when memberInitExpression.Bindings.SingleOrDefault( - mb => mb.Member.Name == property.Name) is MemberAssignment memberAssignment: + when memberInitExpression.Bindings.SingleOrDefault( + mb => mb.Member.Name == property.Name) is MemberAssignment memberAssignment: return memberAssignment.Expression; default: @@ -1387,7 +1416,9 @@ private static T ParameterValueExtractor(QueryContext context, string basePar } private static List ParameterListValueExtractor( - QueryContext context, string baseParameterName, IProperty property) + QueryContext context, + string baseParameterName, + IProperty property) { if (!(context.ParameterValues[baseParameterName] is IEnumerable baseListParameter)) { @@ -1462,8 +1493,11 @@ private EntityReferenceExpression(EntityReferenceExpression entityReferenceExpre public ShapedQueryExpression SubqueryEntity { get; } public IEntityType EntityType { get; } - public override Type Type => EntityType.ClrType; - public override ExpressionType NodeType => ExpressionType.Extension; + public override Type Type + => EntityType.ClrType; + + public override ExpressionType NodeType + => ExpressionType.Extension; public Expression Convert(Type type) { @@ -1485,6 +1519,7 @@ public GroupingElementExpression(Expression element) { Element = element; } + public Expression Element { get; private set; } public bool IsDistinct { get; private set; } public SqlExpression Predicate { get; private set; } @@ -1525,8 +1560,12 @@ public GroupingElementExpression ApplyPredicate(SqlExpression expression) return this; } - public override Type Type => typeof(IEnumerable<>).MakeGenericType(Element.Type); - public override ExpressionType NodeType => ExpressionType.Extension; + + public override Type Type + => typeof(IEnumerable<>).MakeGenericType(Element.Type); + + public override ExpressionType NodeType + => ExpressionType.Extension; } private sealed class SqlTypeMappingVerifyingExpressionVisitor : ExpressionVisitor diff --git a/src/EFCore.Relational/Query/SqlExpressionFactory.cs b/src/EFCore.Relational/Query/SqlExpressionFactory.cs index 16ca637a883..f9f551b2109 100644 --- a/src/EFCore.Relational/Query/SqlExpressionFactory.cs +++ b/src/EFCore.Relational/Query/SqlExpressionFactory.cs @@ -39,12 +39,12 @@ public virtual SqlExpression ApplyDefaultTypeMapping(SqlExpression sqlExpression { return sqlExpression == null || sqlExpression.TypeMapping != null - ? sqlExpression - : sqlExpression is SqlUnaryExpression sqlUnaryExpression + ? sqlExpression + : sqlExpression is SqlUnaryExpression sqlUnaryExpression && sqlUnaryExpression.OperatorType == ExpressionType.Convert && sqlUnaryExpression.Type == typeof(object) - ? sqlUnaryExpression.Operand - : ApplyTypeMapping(sqlExpression, _typeMappingSource.FindMapping(sqlExpression.Type)); + ? sqlUnaryExpression.Operand + : ApplyTypeMapping(sqlExpression, _typeMappingSource.FindMapping(sqlExpression.Type)); } /// @@ -91,7 +91,8 @@ private SqlExpression ApplyTypeMappingOnLike(LikeExpression likeExpression) } private SqlExpression ApplyTypeMappingOnCase( - CaseExpression caseExpression, RelationalTypeMapping typeMapping) + CaseExpression caseExpression, + RelationalTypeMapping typeMapping) { var whenClauses = new List(); foreach (var caseWhenClause in caseExpression.WhenClauses) @@ -108,15 +109,18 @@ private SqlExpression ApplyTypeMappingOnCase( } private SqlExpression ApplyTypeMappingOnCollate( - CollateExpression collateExpression, RelationalTypeMapping typeMapping) + CollateExpression collateExpression, + RelationalTypeMapping typeMapping) => collateExpression.Update(ApplyTypeMapping(collateExpression.Operand, typeMapping)); private SqlExpression ApplyTypeMappingOnDistinct( - DistinctExpression distinctExpression, RelationalTypeMapping typeMapping) + DistinctExpression distinctExpression, + RelationalTypeMapping typeMapping) => distinctExpression.Update(ApplyTypeMapping(distinctExpression.Operand, typeMapping)); private SqlExpression ApplyTypeMappingOnSqlUnary( - SqlUnaryExpression sqlUnaryExpression, RelationalTypeMapping typeMapping) + SqlUnaryExpression sqlUnaryExpression, + RelationalTypeMapping typeMapping) { SqlExpression operand; Type resultType; @@ -150,15 +154,17 @@ private SqlExpression ApplyTypeMappingOnSqlUnary( break; default: - throw new InvalidOperationException(RelationalStrings.UnsupportedOperatorForSqlExpression( - sqlUnaryExpression.OperatorType, typeof(SqlUnaryExpression).ShortDisplayName())); + throw new InvalidOperationException( + RelationalStrings.UnsupportedOperatorForSqlExpression( + sqlUnaryExpression.OperatorType, typeof(SqlUnaryExpression).ShortDisplayName())); } return new SqlUnaryExpression(sqlUnaryExpression.OperatorType, operand, resultType, resultTypeMapping); } private SqlExpression ApplyTypeMappingOnSqlBinary( - SqlBinaryExpression sqlBinaryExpression, RelationalTypeMapping typeMapping) + SqlBinaryExpression sqlBinaryExpression, + RelationalTypeMapping typeMapping) { var left = sqlBinaryExpression.Left; var right = sqlBinaryExpression.Right; @@ -209,8 +215,9 @@ private SqlExpression ApplyTypeMappingOnSqlBinary( } default: - throw new InvalidOperationException(RelationalStrings.UnsupportedOperatorForSqlExpression( - sqlBinaryExpression.OperatorType, typeof(SqlBinaryExpression).ShortDisplayName())); + throw new InvalidOperationException( + RelationalStrings.UnsupportedOperatorForSqlExpression( + sqlBinaryExpression.OperatorType, typeof(SqlBinaryExpression).ShortDisplayName())); } return new SqlBinaryExpression( @@ -223,7 +230,10 @@ private SqlExpression ApplyTypeMappingOnSqlBinary( /// public virtual SqlBinaryExpression MakeBinary( - ExpressionType operatorType, SqlExpression left, SqlExpression right, RelationalTypeMapping typeMapping) + ExpressionType operatorType, + SqlExpression left, + SqlExpression right, + RelationalTypeMapping typeMapping) { Check.NotNull(left, nameof(left)); Check.NotNull(right, nameof(right)); @@ -398,10 +408,9 @@ public virtual SqlFunctionExpression Coalesce(SqlExpression left, SqlExpression ?? ExpressionExtensions.InferTypeMapping(left, right) ?? _typeMappingSource.FindMapping(resultType); - var typeMappedArguments = new List() + var typeMappedArguments = new List { - ApplyTypeMapping(left, inferredTypeMapping), - ApplyTypeMapping(right, inferredTypeMapping) + ApplyTypeMapping(left, inferredTypeMapping), ApplyTypeMapping(right, inferredTypeMapping) }; return new SqlFunctionExpression( @@ -416,7 +425,10 @@ public virtual SqlFunctionExpression Coalesce(SqlExpression left, SqlExpression /// public virtual SqlUnaryExpression MakeUnary( - ExpressionType operatorType, SqlExpression operand, Type type, RelationalTypeMapping typeMapping = null) + ExpressionType operatorType, + SqlExpression operand, + Type type, + RelationalTypeMapping typeMapping = null) { Check.NotNull(operatorType, nameof(operand)); Check.NotNull(operand, nameof(operand)); @@ -538,7 +550,8 @@ public virtual SqlFunctionExpression Function( IEnumerable arguments, Type returnType, RelationalTypeMapping typeMapping = null) - => Function(name, arguments, nullable: true, argumentsPropagateNullability: arguments.Select(a => false), returnType, typeMapping); + => Function( + name, arguments, nullable: true, argumentsPropagateNullability: arguments.Select(a => false), returnType, typeMapping); /// [Obsolete("Use overload that explicitly specifies value for 'argumentsPropagateNullability' argument.")] @@ -548,10 +561,13 @@ public virtual SqlFunctionExpression Function( IEnumerable arguments, Type returnType, RelationalTypeMapping typeMapping = null) - => Function(schema, name, arguments, nullable: true, argumentsPropagateNullability: arguments.Select(a => false), returnType, typeMapping); + => Function( + schema, name, arguments, nullable: true, argumentsPropagateNullability: arguments.Select(a => false), returnType, + typeMapping); /// - [Obsolete("Use overload that explicitly specifies values for 'instancePropagatesNullability' and 'argumentsPropagateNullability' arguments.")] + [Obsolete( + "Use overload that explicitly specifies values for 'instancePropagatesNullability' and 'argumentsPropagateNullability' arguments.")] public virtual SqlFunctionExpression Function( SqlExpression instance, string name, @@ -580,7 +596,11 @@ public virtual SqlFunctionExpression Function(string schema, string name, Type r /// [Obsolete("Use NiladicFunction method.")] - public virtual SqlFunctionExpression Function(SqlExpression instance, string name, Type returnType, RelationalTypeMapping typeMapping = null) + public virtual SqlFunctionExpression Function( + SqlExpression instance, + string name, + Type returnType, + RelationalTypeMapping typeMapping = null) => NiladicFunction(instance, name, nullable: true, instancePropagatesNullability: false, returnType, typeMapping); /// @@ -628,7 +648,8 @@ public virtual SqlFunctionExpression Function( typeMappedArguments.Add(ApplyDefaultTypeMapping(argument)); } - return new SqlFunctionExpression(schema, name, typeMappedArguments, nullable, argumentsPropagateNullability, returnType, typeMapping); + return new SqlFunctionExpression( + schema, name, typeMappedArguments, nullable, argumentsPropagateNullability, returnType, typeMapping); } /// @@ -655,11 +676,17 @@ public virtual SqlFunctionExpression Function( typeMappedArguments.Add(ApplyDefaultTypeMapping(argument)); } - return new SqlFunctionExpression(instance, name, typeMappedArguments, nullable, instancePropagatesNullability, argumentsPropagateNullability, returnType, typeMapping); + return new SqlFunctionExpression( + instance, name, typeMappedArguments, nullable, instancePropagatesNullability, argumentsPropagateNullability, returnType, + typeMapping); } /// - public virtual SqlFunctionExpression NiladicFunction(string name, bool nullable, Type returnType, RelationalTypeMapping typeMapping = null) + public virtual SqlFunctionExpression NiladicFunction( + string name, + bool nullable, + Type returnType, + RelationalTypeMapping typeMapping = null) { Check.NotEmpty(name, nameof(name)); Check.NotNull(returnType, nameof(returnType)); @@ -668,7 +695,12 @@ public virtual SqlFunctionExpression NiladicFunction(string name, bool nullable, } /// - public virtual SqlFunctionExpression NiladicFunction(string schema, string name, bool nullable, Type returnType, RelationalTypeMapping typeMapping = null) + public virtual SqlFunctionExpression NiladicFunction( + string schema, + string name, + bool nullable, + Type returnType, + RelationalTypeMapping typeMapping = null) { Check.NotEmpty(schema, nameof(schema)); Check.NotEmpty(name, nameof(name)); @@ -690,7 +722,8 @@ public virtual SqlFunctionExpression NiladicFunction( Check.NotEmpty(name, nameof(name)); Check.NotNull(returnType, nameof(returnType)); - return new SqlFunctionExpression(ApplyDefaultTypeMapping(instance), name, nullable, instancePropagatesNullability, returnType, typeMapping); + return new SqlFunctionExpression( + ApplyDefaultTypeMapping(instance), name, nullable, instancePropagatesNullability, returnType, typeMapping); } /// @@ -755,7 +788,8 @@ public virtual SqlConstantExpression Constant(object value, RelationalTypeMappin => new SqlConstantExpression(Expression.Constant(value), typeMapping); /// - public virtual SelectExpression Select(SqlExpression projection) => new SelectExpression(projection); + public virtual SelectExpression Select(SqlExpression projection) + => new SelectExpression(projection); /// public virtual SelectExpression Select(IEntityType entityType) @@ -899,7 +933,9 @@ bool HasSiblings(IEntityType entityType) } private void AddOptionalDependentConditions( - SelectExpression selectExpression, IEntityType entityType, ITableBase table) + SelectExpression selectExpression, + IEntityType entityType, + ITableBase table) { SqlExpression predicate = null; var requiredNonPkProperties = entityType.GetProperties().Where(p => !p.IsNullable && !p.IsPrimaryKey()).ToList(); @@ -975,10 +1011,12 @@ private SqlExpression IsNotNull(IProperty property, EntityProjectionExpression e /// [Obsolete("Use IRelationalTypeMappingSource directly.")] - public virtual RelationalTypeMapping GetTypeMappingForValue(object value) => _typeMappingSource.GetMappingForValue(value); + public virtual RelationalTypeMapping GetTypeMappingForValue(object value) + => _typeMappingSource.GetMappingForValue(value); /// [Obsolete("Use IRelationalTypeMappingSource directly.")] - public virtual RelationalTypeMapping FindMapping(Type type) => _typeMappingSource.FindMapping(Check.NotNull(type, nameof(type))); + public virtual RelationalTypeMapping FindMapping(Type type) + => _typeMappingSource.FindMapping(Check.NotNull(type, nameof(type))); } } diff --git a/src/EFCore.Relational/Query/SqlExpressionVisitor.cs b/src/EFCore.Relational/Query/SqlExpressionVisitor.cs index 2b01e88d9f4..298b6cbf936 100644 --- a/src/EFCore.Relational/Query/SqlExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/SqlExpressionVisitor.cs @@ -127,168 +127,196 @@ protected override Expression VisitExtension(Expression extensionExpression) /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitCase([NotNull] CaseExpression caseExpression); + /// /// Visits the children of the collate expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitCollate([NotNull] CollateExpression collateExpression); + /// /// Visits the children of the column expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitColumn([NotNull] ColumnExpression columnExpression); + /// /// Visits the children of the cross apply expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitCrossApply([NotNull] CrossApplyExpression crossApplyExpression); + /// /// Visits the children of the cross join expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitCrossJoin([NotNull] CrossJoinExpression crossJoinExpression); + /// /// Visits the children of the distinct expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitDistinct([NotNull] DistinctExpression distinctExpression); + /// /// Visits the children of the except expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitExcept([NotNull] ExceptExpression exceptExpression); + /// /// Visits the children of the exists expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitExists([NotNull] ExistsExpression existsExpression); + /// /// Visits the children of the from sql expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitFromSql([NotNull] FromSqlExpression fromSqlExpression); + /// /// Visits the children of the in expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitIn([NotNull] InExpression inExpression); + /// /// Visits the children of the intersect expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitIntersect([NotNull] IntersectExpression intersectExpression); + /// /// Visits the children of the like expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitLike([NotNull] LikeExpression likeExpression); + /// /// Visits the children of the inner join expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitInnerJoin([NotNull] InnerJoinExpression innerJoinExpression); + /// /// Visits the children of the left join expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitLeftJoin([NotNull] LeftJoinExpression leftJoinExpression); + /// /// Visits the children of the ordering expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitOrdering([NotNull] OrderingExpression orderingExpression); + /// /// Visits the children of the outer apply expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitOuterApply([NotNull] OuterApplyExpression outerApplyExpression); + /// /// Visits the children of the projection expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitProjection([NotNull] ProjectionExpression projectionExpression); + /// /// Visits the children of the table valued function expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitTableValuedFunction([NotNull] TableValuedFunctionExpression tableValuedFunctionExpression); + /// /// Visits the children of the row number expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitRowNumber([NotNull] RowNumberExpression rowNumberExpression); + /// /// Visits the children of the scalar subquery expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitScalarSubquery([NotNull] ScalarSubqueryExpression scalarSubqueryExpression); + /// /// Visits the children of the select expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitSelect([NotNull] SelectExpression selectExpression); + /// /// Visits the children of the sql binary expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitSqlBinary([NotNull] SqlBinaryExpression sqlBinaryExpression); + /// /// Visits the children of the sql constant expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitSqlConstant([NotNull] SqlConstantExpression sqlConstantExpression); + /// /// Visits the children of the sql fragent expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitSqlFragment([NotNull] SqlFragmentExpression sqlFragmentExpression); + /// /// Visits the children of the sql function expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitSqlFunction([NotNull] SqlFunctionExpression sqlFunctionExpression); + /// /// Visits the children of the sql parameter expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitSqlParameter([NotNull] SqlParameterExpression sqlParameterExpression); + /// /// Visits the children of the sql unary expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitSqlUnary([NotNull] SqlUnaryExpression sqlUnaryExpression); + /// /// Visits the children of the table expression. /// /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected abstract Expression VisitTable([NotNull] TableExpression tableExpression); + /// /// Visits the children of the union expression. /// diff --git a/src/EFCore.Relational/Query/SqlExpressions/CaseExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/CaseExpression.cs index 337da536384..f1104cca64b 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/CaseExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/CaseExpression.cs @@ -26,9 +26,9 @@ public class CaseExpression : SqlExpression /// /// Creates a new instance of the class which represents a simple CASE expression. /// - /// An expression to compare with in . - /// A list of to compare and get result from. - /// A value to return if no matches, if any. + /// An expression to compare with in . + /// A list of to compare and get result from. + /// A value to return if no matches, if any. public CaseExpression( [NotNull] SqlExpression operand, [NotNull] IReadOnlyList whenClauses, @@ -45,8 +45,8 @@ public CaseExpression( /// /// Creates a new instance of the class which represents a searched CASE expression. /// - /// A list of to evaluate condition and get result from. - /// A value to return if no matches, if any. + /// A list of to evaluate condition and get result from. + /// A value to return if no matches, if any. public CaseExpression( [NotNull] IReadOnlyList whenClauses, [CanBeNull] SqlExpression elseResult = null) @@ -57,15 +57,18 @@ public CaseExpression( } /// - /// The value to compare in . + /// The value to compare in . /// public virtual SqlExpression Operand { get; } + /// - /// The list of to match or evaluate condition to get result. + /// The list of to match or evaluate condition to get result. /// - public virtual IReadOnlyList WhenClauses => _whenClauses; + public virtual IReadOnlyList WhenClauses + => _whenClauses; + /// - /// The value to return if none of the matches. + /// The value to return if none of the matches. /// public virtual SqlExpression ElseResult { get; } @@ -108,9 +111,9 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual CaseExpression Update( [CanBeNull] SqlExpression operand, diff --git a/src/EFCore.Relational/Query/SqlExpressions/CaseWhenClause.cs b/src/EFCore.Relational/Query/SqlExpressions/CaseWhenClause.cs index 91c89258d6e..c6419239045 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/CaseWhenClause.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/CaseWhenClause.cs @@ -21,7 +21,7 @@ public class CaseWhenClause /// /// Creates a new instance of the class. /// - /// A value to compare with or condition to evaluate. + /// A value to compare with or condition to evaluate. /// A value to return if test succeeds. public CaseWhenClause([NotNull] SqlExpression test, [NotNull] SqlExpression result) { @@ -33,11 +33,12 @@ public CaseWhenClause([NotNull] SqlExpression test, [NotNull] SqlExpression resu } /// - /// The value to compare with or the condition to evaluate. + /// The value to compare with or the condition to evaluate. /// public virtual SqlExpression Test { get; } + /// - /// The value to return if succeeds. + /// The value to return if succeeds. /// public virtual SqlExpression Result { get; } @@ -53,6 +54,7 @@ private bool Equals(CaseWhenClause caseWhenClause) && Result.Equals(caseWhenClause.Result); /// - public override int GetHashCode() => HashCode.Combine(Test, Result); + public override int GetHashCode() + => HashCode.Combine(Test, Result); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/CollateExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/CollateExpression.cs index de57e0a5bab..9af5508e4b7 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/CollateExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/CollateExpression.cs @@ -38,6 +38,7 @@ public CollateExpression([NotNull] SqlExpression operand, [NotNull] string colla /// The expression on which collation is applied. /// public virtual SqlExpression Operand { get; } + /// /// The collation value to use. /// @@ -55,7 +56,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual CollateExpression Update([NotNull] SqlExpression operand) { @@ -90,6 +91,7 @@ private bool Equals(CollateExpression collateExpression) && Collation.Equals(collateExpression.Collation, StringComparison.Ordinal); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Operand, Collation); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Operand, Collation); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/ColumnExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/ColumnExpression.cs index d3aa0e7ccb6..2f79b64d180 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/ColumnExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/ColumnExpression.cs @@ -70,6 +70,7 @@ private ColumnExpression(string name, TableExpressionBase table, Type type, Rela /// The name of the column. /// public string Name { get; } + /// /// The table from which column is being referenced. /// @@ -91,7 +92,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// /// Makes this column nullable. /// - /// A new expression which has property set to true. + /// A new expression which has property set to true. public ColumnExpression MakeNullable() => new ColumnExpression(Name, Table, Type, TypeMapping, true); @@ -118,8 +119,10 @@ private bool Equals(ColumnExpression columnExpression) && IsNullable == columnExpression.IsNullable; /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Name, Table, IsNullable); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Name, Table, IsNullable); - private string DebuggerDisplay() => $"{Table.Alias}.{Name}"; + private string DebuggerDisplay() + => $"{Table.Alias}.{Name}"; } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/CrossApplyExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/CrossApplyExpression.cs index 84aa008ba4e..0d595ea0b5e 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/CrossApplyExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/CrossApplyExpression.cs @@ -39,7 +39,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual CrossApplyExpression Update([NotNull] TableExpressionBase table) { @@ -70,6 +70,7 @@ private bool Equals(CrossApplyExpression crossApplyExpression) => base.Equals(crossApplyExpression); /// - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/CrossJoinExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/CrossJoinExpression.cs index cbd08a3ab97..a74aca9a8fd 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/CrossJoinExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/CrossJoinExpression.cs @@ -39,7 +39,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual CrossJoinExpression Update([NotNull] TableExpressionBase table) { @@ -70,6 +70,7 @@ private bool Equals(CrossJoinExpression crossJoinExpression) => base.Equals(crossJoinExpression); /// - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/DistinctExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/DistinctExpression.cs index 02f1e476a26..ef16ba7fdd0 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/DistinctExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/DistinctExpression.cs @@ -48,7 +48,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual DistinctExpression Update([NotNull] SqlExpression operand) { @@ -81,6 +81,7 @@ private bool Equals(DistinctExpression distinctExpression) && Operand.Equals(distinctExpression.Operand); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Operand); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Operand); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/ExceptExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/ExceptExpression.cs index 176360ce800..3605645ee6b 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/ExceptExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/ExceptExpression.cs @@ -50,8 +50,8 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual ExceptExpression Update([NotNull] SelectExpression source1, [NotNull] SelectExpression source2) { diff --git a/src/EFCore.Relational/Query/SqlExpressions/ExistsExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/ExistsExpression.cs index c9c9a91ed55..af5e6ccc6b9 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/ExistsExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/ExistsExpression.cs @@ -25,7 +25,7 @@ public class ExistsExpression : SqlExpression /// /// A subquery to check existence of. /// A value indicating if the existence check is negated. - /// The associated with the expression. + /// The associated with the expression. public ExistsExpression( [NotNull] SelectExpression subquery, bool negated, @@ -42,6 +42,7 @@ public ExistsExpression( /// The subquery to check existence of. /// public virtual SelectExpression Subquery { get; } + /// /// The value indicating if the existence check is negated. /// @@ -59,7 +60,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual ExistsExpression Update([NotNull] SelectExpression subquery) { @@ -102,6 +103,7 @@ private bool Equals(ExistsExpression existsExpression) && IsNegated == existsExpression.IsNegated; /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Subquery, IsNegated); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Subquery, IsNegated); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/FromSqlExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/FromSqlExpression.cs index 1c9e68a4325..0970c7e831f 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/FromSqlExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/FromSqlExpression.cs @@ -66,7 +66,7 @@ public FromSqlExpression([NotNull] string alias, [NotNull] string sql, [NotNull] /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual FromSqlExpression Update([NotNull] Expression arguments) { @@ -106,6 +106,7 @@ private bool Equals(FromSqlExpression fromSqlExpression) && ExpressionEqualityComparer.Instance.Equals(Arguments, fromSqlExpression.Arguments); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Sql); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Sql); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/InExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/InExpression.cs index 53abde7ba13..dc22978b44a 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/InExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/InExpression.cs @@ -23,12 +23,12 @@ namespace Microsoft.EntityFrameworkCore.Query.SqlExpressions public class InExpression : SqlExpression { /// - /// Creates a new instance of the class which represents a IN subquery expression. + /// Creates a new instance of the class which represents a IN subquery expression. /// /// An item to look into values. /// A value indicating if the item should be present in the values or absent. /// A subquery in which item is searched. - /// The associated with the expression. + /// The associated with the expression. [Obsolete("Use overload which passes negated argument after subquery argument.")] public InExpression( [NotNull] SqlExpression item, @@ -40,12 +40,12 @@ public InExpression( } /// - /// Creates a new instance of the class which represents a IN values expression. + /// Creates a new instance of the class which represents a IN values expression. /// /// An item to look into values. /// A value indicating if the item should be present in the values or absent. /// A list of values in which item is searched. - /// The associated with the expression. + /// The associated with the expression. [Obsolete("Use overload which passes negated argument after values argument.")] public InExpression( [NotNull] SqlExpression item, @@ -57,12 +57,12 @@ public InExpression( } /// - /// Creates a new instance of the class which represents a IN subquery expression. + /// Creates a new instance of the class which represents a IN subquery expression. /// /// An item to look into values. /// A subquery in which item is searched. /// A value indicating if the item should be present in the values or absent. - /// The associated with the expression. + /// The associated with the expression. public InExpression( [NotNull] SqlExpression item, [NotNull] SelectExpression subquery, @@ -73,12 +73,12 @@ public InExpression( } /// - /// Creates a new instance of the class which represents a IN values expression. + /// Creates a new instance of the class which represents a IN values expression. /// /// An item to look into values. /// A list of values in which item is searched. /// A value indicating if the item should be present in the values or absent. - /// The associated with the expression. + /// The associated with the expression. public InExpression( [NotNull] SqlExpression item, [NotNull] SqlExpression values, @@ -89,7 +89,11 @@ public InExpression( } private InExpression( - SqlExpression item, SqlExpression values, SelectExpression subquery, bool negated, RelationalTypeMapping typeMapping) + SqlExpression item, + SqlExpression values, + SelectExpression subquery, + bool negated, + RelationalTypeMapping typeMapping) : base(typeof(bool), typeMapping) { Item = item; @@ -102,14 +106,17 @@ private InExpression( /// The item to look into values. /// public virtual SqlExpression Item { get; } + /// /// The value indicating if item should be present in the values or absent. /// public virtual bool IsNegated { get; } + /// /// The list of values to search item in. /// public virtual SqlExpression Values { get; } + /// /// The subquery to search item in. /// @@ -128,21 +135,24 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) } /// - /// Negates this expression by changing presence/absence state indicated by . + /// Negates this expression by changing presence/absence state indicated by . /// /// An expression which is negated form of this expression. - public virtual InExpression Negate() => new InExpression(Item, Values, Subquery, !IsNegated, TypeMapping); + public virtual InExpression Negate() + => new InExpression(Item, Values, Subquery, !IsNegated, TypeMapping); /// /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual InExpression Update( - [NotNull] SqlExpression item, [CanBeNull] SqlExpression values, [CanBeNull] SelectExpression subquery) + [NotNull] SqlExpression item, + [CanBeNull] SqlExpression values, + [CanBeNull] SelectExpression subquery) { Check.NotNull(item, nameof(item)); @@ -211,6 +221,7 @@ private bool Equals(InExpression inExpression) && (Subquery == null ? inExpression.Subquery == null : Subquery.Equals(inExpression.Subquery)); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Item, IsNegated, Values, Subquery); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Item, IsNegated, Values, Subquery); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/InnerJoinExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/InnerJoinExpression.cs index 762c1bf6988..dc3c4c3aad8 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/InnerJoinExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/InnerJoinExpression.cs @@ -43,8 +43,8 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual InnerJoinExpression Update([NotNull] TableExpressionBase table, [NotNull] SqlExpression joinPredicate) { @@ -78,6 +78,7 @@ private bool Equals(InnerJoinExpression innerJoinExpression) => base.Equals(innerJoinExpression); /// - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/IntersectExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/IntersectExpression.cs index 5b00fb5b902..9f5c3cd564a 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/IntersectExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/IntersectExpression.cs @@ -27,7 +27,10 @@ public class IntersectExpression : SetOperationBase /// A table source which is second source in the set operation. /// A bool value indicating whether result will remove duplicate rows. public IntersectExpression( - [NotNull] string alias, [NotNull] SelectExpression source1, [NotNull] SelectExpression source2, bool distinct) + [NotNull] string alias, + [NotNull] SelectExpression source1, + [NotNull] SelectExpression source2, + bool distinct) : base(alias, source1, source2, distinct) { } @@ -47,8 +50,8 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual IntersectExpression Update([NotNull] SelectExpression source1, [NotNull] SelectExpression source2) { diff --git a/src/EFCore.Relational/Query/SqlExpressions/JoinExpressionBase.cs b/src/EFCore.Relational/Query/SqlExpressions/JoinExpressionBase.cs index b772d6796dd..8713904293e 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/JoinExpressionBase.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/JoinExpressionBase.cs @@ -47,6 +47,7 @@ private bool Equals(JoinExpressionBase joinExpressionBase) && Table.Equals(joinExpressionBase.Table); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Table); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Table); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/LeftJoinExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/LeftJoinExpression.cs index c10019189b6..3f46e73e1ef 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/LeftJoinExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/LeftJoinExpression.cs @@ -43,8 +43,8 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual LeftJoinExpression Update([NotNull] TableExpressionBase table, [NotNull] SqlExpression joinPredicate) { @@ -78,6 +78,7 @@ private bool Equals(LeftJoinExpression leftJoinExpression) => base.Equals(leftJoinExpression); /// - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/LikeExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/LikeExpression.cs index f68abb17a49..f546c1c8241 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/LikeExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/LikeExpression.cs @@ -26,7 +26,7 @@ public class LikeExpression : SqlExpression /// An expression on which LIKE is applied. /// A pattern to search. /// An optional escape character to use in LIKE. - /// The associated with the expression. + /// The associated with the expression. public LikeExpression( [NotNull] SqlExpression match, [NotNull] SqlExpression pattern, @@ -46,10 +46,12 @@ public LikeExpression( /// The expression on which LIKE is applied. /// public virtual SqlExpression Match { get; } + /// - /// The pattern to search in . + /// The pattern to search in . /// public virtual SqlExpression Pattern { get; } + /// /// The escape chater to use in LIKE. /// @@ -71,12 +73,14 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual LikeExpression Update( - [NotNull] SqlExpression match, [NotNull] SqlExpression pattern, [CanBeNull] SqlExpression escapeChar) + [NotNull] SqlExpression match, + [NotNull] SqlExpression pattern, + [CanBeNull] SqlExpression escapeChar) { Check.NotNull(match, nameof(match)); Check.NotNull(pattern, nameof(pattern)); @@ -116,6 +120,7 @@ private bool Equals(LikeExpression likeExpression) && EscapeChar.Equals(likeExpression.EscapeChar); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Match, Pattern, EscapeChar); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Match, Pattern, EscapeChar); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/OrderingExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/OrderingExpression.cs index 07c4438c5ae..2d59c64561a 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/OrderingExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/OrderingExpression.cs @@ -36,15 +36,19 @@ public OrderingExpression([NotNull] SqlExpression expression, bool ascending) /// The expression used for ordering. /// public virtual SqlExpression Expression { get; } + /// /// The value indicating if the ordering is ascending. /// public virtual bool IsAscending { get; } /// - public sealed override ExpressionType NodeType => ExpressionType.Extension; + public sealed override ExpressionType NodeType + => ExpressionType.Extension; + /// - public override Type Type => Expression.Type; + public override Type Type + => Expression.Type; /// protected override Expression VisitChildren(ExpressionVisitor visitor) @@ -58,7 +62,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual OrderingExpression Update([NotNull] SqlExpression expression) { @@ -91,6 +95,7 @@ private bool Equals(OrderingExpression orderingExpression) && IsAscending == orderingExpression.IsAscending; /// - public override int GetHashCode() => HashCode.Combine(Expression, IsAscending); + public override int GetHashCode() + => HashCode.Combine(Expression, IsAscending); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/OuterApplyExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/OuterApplyExpression.cs index f099547b14f..22f4d420d93 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/OuterApplyExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/OuterApplyExpression.cs @@ -39,7 +39,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual OuterApplyExpression Update([NotNull] TableExpressionBase table) { @@ -70,6 +70,7 @@ private bool Equals(OuterApplyExpression outerApplyExpression) => base.Equals(outerApplyExpression); /// - public override int GetHashCode() => base.GetHashCode(); + public override int GetHashCode() + => base.GetHashCode(); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/PredicateJoinExpressionBase.cs b/src/EFCore.Relational/Query/SqlExpressions/PredicateJoinExpressionBase.cs index 9fab267b457..e8d914f6a3b 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/PredicateJoinExpressionBase.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/PredicateJoinExpressionBase.cs @@ -48,6 +48,7 @@ private bool Equals(PredicateJoinExpressionBase predicateJoinExpressionBase) && JoinPredicate.Equals(predicateJoinExpressionBase.JoinPredicate); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), JoinPredicate); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), JoinPredicate); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/ProjectionExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/ProjectionExpression.cs index 9280bcb0594..66e7231b64b 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/ProjectionExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/ProjectionExpression.cs @@ -10,10 +10,10 @@ namespace Microsoft.EntityFrameworkCore.Query.SqlExpressions { /// /// - /// An expression that represents a projection in . + /// An expression that represents a projection in . /// /// - /// This is a simple wrapper around a and an alias. + /// This is a simple wrapper around a and an alias. /// Instances of this type cannot be constructed by application or database provider code. If this is a problem for your /// application or provider, then please file an issue at https://github.com/dotnet/efcore. /// @@ -33,15 +33,19 @@ internal ProjectionExpression([NotNull] SqlExpression expression, [NotNull] stri /// The alias assigned to this projection, if any. /// public string Alias { get; } + /// /// The SQL value which is being projected. /// public SqlExpression Expression { get; } /// - public override Type Type => Expression.Type; + public override Type Type + => Expression.Type; + /// - public override ExpressionType NodeType => ExpressionType.Extension; + public override ExpressionType NodeType + => ExpressionType.Extension; /// protected override Expression VisitChildren(ExpressionVisitor visitor) @@ -55,7 +59,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public ProjectionExpression Update([NotNull] SqlExpression expression) { @@ -92,6 +96,7 @@ private bool Equals(ProjectionExpression projectionExpression) && Expression.Equals(projectionExpression.Expression); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Alias, Expression); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Alias, Expression); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/RowNumberExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/RowNumberExpression.cs index 3df314e5d1d..a6ce1b94a20 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/RowNumberExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/RowNumberExpression.cs @@ -27,7 +27,7 @@ public class RowNumberExpression : SqlExpression /// /// A list expressions to partition by. /// A list of ordering expressions to order by. - /// The associated with the expression. + /// The associated with the expression. public RowNumberExpression( [CanBeNull] IReadOnlyList partitions, [NotNull] IReadOnlyList orderings, @@ -44,6 +44,7 @@ public RowNumberExpression( /// The list of expressions used in partitioning. /// public virtual IReadOnlyList Partitions { get; } + /// /// The list of ordering expressions used to order inside the given partition. /// @@ -80,11 +81,12 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual RowNumberExpression Update( - [CanBeNull] IReadOnlyList partitions, [NotNull] IReadOnlyList orderings) + [CanBeNull] IReadOnlyList partitions, + [NotNull] IReadOnlyList orderings) { Check.NotNull(orderings, nameof(orderings)); diff --git a/src/EFCore.Relational/Query/SqlExpressions/ScalarSubqueryExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/ScalarSubqueryExpression.cs index 7070b0637c0..aaad51b0574 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/ScalarSubqueryExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/ScalarSubqueryExpression.cs @@ -60,7 +60,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual ScalarSubqueryExpression Update([NotNull] SelectExpression subquery) { @@ -97,6 +97,7 @@ private bool Equals(ScalarSubqueryExpression scalarSubqueryExpression) && Subquery.Equals(scalarSubqueryExpression.Subquery); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Subquery); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Subquery); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs index 30d508ed1aa..098e90888f3 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs @@ -32,15 +32,16 @@ namespace Microsoft.EntityFrameworkCore.Query.SqlExpressions // Class is sealed because there are no public/protected constructors. Can be unsealed if this is changed. public sealed class SelectExpression : TableExpressionBase { - private static readonly Dictionary _mirroredOperationMap = new Dictionary - { - { ExpressionType.Equal, ExpressionType.Equal }, - { ExpressionType.NotEqual, ExpressionType.NotEqual }, - { ExpressionType.LessThan, ExpressionType.GreaterThan }, - { ExpressionType.LessThanOrEqual, ExpressionType.GreaterThanOrEqual }, - { ExpressionType.GreaterThan, ExpressionType.LessThan }, - { ExpressionType.GreaterThanOrEqual, ExpressionType.LessThanOrEqual }, - }; + private static readonly Dictionary _mirroredOperationMap = + new Dictionary + { + { ExpressionType.Equal, ExpressionType.Equal }, + { ExpressionType.NotEqual, ExpressionType.NotEqual }, + { ExpressionType.LessThan, ExpressionType.GreaterThan }, + { ExpressionType.LessThanOrEqual, ExpressionType.GreaterThanOrEqual }, + { ExpressionType.GreaterThan, ExpressionType.LessThan }, + { ExpressionType.GreaterThanOrEqual, ExpressionType.LessThanOrEqual }, + }; private const string DiscriminatorColumnAlias = "Discriminator"; @@ -51,10 +52,13 @@ private readonly IDictionary _tables = new List(); private readonly List _groupBy = new List(); private readonly List _orderings = new List(); + private readonly List<(ColumnExpression Column, ValueComparer Comparer)> _identifier = new List<(ColumnExpression Column, ValueComparer Comparer)>(); + private readonly List<(ColumnExpression Column, ValueComparer Comparer)> _childIdentifiers = new List<(ColumnExpression Column, ValueComparer Comparer)>(); + private readonly List _pendingCollections = new List(); private List _tptLeftJoinTables = new List(); @@ -63,48 +67,61 @@ private readonly IDictionary /// The list of expressions being projected out from the result set. /// - public IReadOnlyList Projection => _projection; + public IReadOnlyList Projection + => _projection; + /// /// The list of tables sources used to generate the result set. /// - public IReadOnlyList Tables => _tables; + public IReadOnlyList Tables + => _tables; + /// /// The SQL GROUP BY clause for the SELECT. /// - public IReadOnlyList GroupBy => _groupBy; + public IReadOnlyList GroupBy + => _groupBy; + /// /// The list of orderings used to sort the result set. /// - public IReadOnlyList Orderings => _orderings; + public IReadOnlyList Orderings + => _orderings; + /// - /// The list of tags applied to this . + /// The list of tags applied to this . /// public ISet Tags { get; private set; } = new HashSet(); + /// /// The WHERE predicate for the SELECT. /// public SqlExpression Predicate { get; private set; } + /// - /// The HAVING predicate for the SELECT when clause exists. + /// The HAVING predicate for the SELECT when clause exists. /// public SqlExpression Having { get; private set; } + /// /// The limit applied to the number of rows in the result set. /// public SqlExpression Limit { get; private set; } + /// /// The offset to skip rows from the result set. /// public SqlExpression Offset { get; private set; } + /// - /// A bool value indicating if DISTINCT is applied to projection of this . + /// A bool value indicating if DISTINCT is applied to projection of this . /// public bool IsDistinct { get; private set; } + /// /// Applies a given set of tags. /// /// A list of tags to apply. - public void ApplyTags([NotNull] ISet tags) { Check.NotNull(tags, nameof(tags)); @@ -230,9 +247,10 @@ internal SelectExpression(IEntityType entityType, ISqlExpressionFactory sqlExpre if (!derivedType.IsAbstract()) { - caseWhenClauses.Add(new CaseWhenClause( - sqlExpressionFactory.IsNotNull(keyColumns[0]), - sqlExpressionFactory.Constant(derivedType.ShortName()))); + caseWhenClauses.Add( + new CaseWhenClause( + sqlExpressionFactory.IsNotNull(keyColumns[0]), + sqlExpressionFactory.Constant(derivedType.ShortName()))); } var joinPredicate = joinColumns.Zip(keyColumns, (l, r) => sqlExpressionFactory.Equal(l, r)) @@ -290,13 +308,16 @@ internal SelectExpression(IEntityType entityType, TableExpressionBase tableExpre } private static ColumnExpression CreateColumnExpression( - IProperty property, ITableBase table, TableExpressionBase tableExpression, bool nullable) + IProperty property, + ITableBase table, + TableExpressionBase tableExpression, + bool nullable) => new ColumnExpression(property, table.FindColumn(property), tableExpression, nullable); /// - /// Checks whether this representes a which is not composed upon. + /// Checks whether this representes a which is not composed upon. /// - /// A bool value indicating a non-composed . + /// A bool value indicating a non-composed . public bool IsNonComposedFromSql() => Limit == null && Offset == null @@ -365,7 +386,7 @@ private static IEnumerable GetAllPropertiesInHierarchy(IEntityType en .SelectMany(EntityTypeExtensions.GetDeclaredProperties); /// - /// Replaces current projection mapping with a new one to change what is being projected out from this . + /// Replaces current projection mapping with a new one to change what is being projected out from this . /// /// A new projection mapping. public void ReplaceProjectionMapping([NotNull] IDictionary projectionMapping) @@ -380,7 +401,7 @@ public void ReplaceProjectionMapping([NotNull] IDictionary - /// Gets the projection mapped to the given . + /// Gets the projection mapped to the given . /// /// A projection member to search in the mapping. /// The mapped projection for given projection member. @@ -392,7 +413,7 @@ public Expression GetMappedProjection([NotNull] ProjectionMember projectionMembe } /// - /// Adds given to the projection. + /// Adds given to the projection. /// /// An expression to add. /// An int value indicating the index at which the expression was added in the projection list. @@ -424,6 +445,7 @@ private int AddToProjection(SqlExpression sqlExpression, string alias) { currentAlias = $"{baseAlias}{counter++}"; } + baseAlias = currentAlias; } @@ -433,10 +455,10 @@ private int AddToProjection(SqlExpression sqlExpression, string alias) } /// - /// Adds given to the projection. + /// Adds given to the projection. /// /// An entity projection to add. - /// A dictionary of to int indicating properties and their corresponding indexes in the projection list. + /// A dictionary of to int indicating properties and their corresponding indexes in the projection list. public IDictionary AddToProjection([NotNull] EntityProjectionExpression entityProjection) { Check.NotNull(entityProjection, nameof(entityProjection)); @@ -461,7 +483,7 @@ public IDictionary AddToProjection([NotNull] EntityProjectionExp } /// - /// Prepares the to apply aggregate operation over it. + /// Prepares the to apply aggregate operation over it. /// public void PrepareForAggregate() { @@ -474,7 +496,7 @@ public void PrepareForAggregate() } /// - /// Applies filter predicate to the . + /// Applies filter predicate to the . /// /// An expression to use for filtering. public void ApplyPredicate([NotNull] SqlExpression expression) @@ -575,7 +597,7 @@ private void AppendGroupBy([NotNull] Expression keySelector) } /// - /// Applies ordering to the . This overwrites any previous ordering specified. + /// Applies ordering to the . This overwrites any previous ordering specified. /// /// An ordering expression to use for ordering. public void ApplyOrdering([NotNull] OrderingExpression orderingExpression) @@ -596,7 +618,7 @@ public void ApplyOrdering([NotNull] OrderingExpression orderingExpression) } /// - /// Appends ordering to the existing orderings of the . + /// Appends ordering to the existing orderings of the . /// /// An ordering expression to use for ordering. public void AppendOrdering([NotNull] OrderingExpression orderingExpression) @@ -610,7 +632,7 @@ public void AppendOrdering([NotNull] OrderingExpression orderingExpression) } /// - /// Applies limit to the to limit the number of rows returned in the result set. + /// Applies limit to the to limit the number of rows returned in the result set. /// /// An expression representing limit row count. public void ApplyLimit([NotNull] SqlExpression sqlExpression) @@ -626,7 +648,7 @@ public void ApplyLimit([NotNull] SqlExpression sqlExpression) } /// - /// Applies offset to the to skip the number of rows in the result set. + /// Applies offset to the to skip the number of rows in the result set. /// /// An expression representing offset row count. public void ApplyOffset([NotNull] SqlExpression sqlExpression) @@ -643,7 +665,7 @@ public void ApplyOffset([NotNull] SqlExpression sqlExpression) } /// - /// Reverses the existing orderings on the . + /// Reverses the existing orderings on the . /// public void ReverseOrderings() { @@ -667,7 +689,7 @@ public void ReverseOrderings() } /// - /// Applies DISTINCT operator to the projections of the . + /// Applies DISTINCT operator to the projections of the . /// public void ApplyDistinct() { @@ -683,7 +705,7 @@ public void ApplyDistinct() } /// - /// Applies on the . + /// Applies on the . /// /// A factory to use for generating required sql expressions. public void ApplyDefaultIfEmpty([NotNull] ISqlExpressionFactory sqlExpressionFactory) @@ -768,9 +790,9 @@ private enum SetOperationType } /// - /// Applies EXCEPT operation to the . + /// Applies EXCEPT operation to the . /// - /// A to perform the operation. + /// A to perform the operation. /// A bool value indicating if resulting table source should remove duplicates. public void ApplyExcept([NotNull] SelectExpression source2, bool distinct) { @@ -780,9 +802,9 @@ public void ApplyExcept([NotNull] SelectExpression source2, bool distinct) } /// - /// Applies INTERSECT operation to the . + /// Applies INTERSECT operation to the . /// - /// A to perform the operation. + /// A to perform the operation. /// A bool value indicating if resulting table source should remove duplicates. public void ApplyIntersect([NotNull] SelectExpression source2, bool distinct) { @@ -792,9 +814,9 @@ public void ApplyIntersect([NotNull] SelectExpression source2, bool distinct) } /// - /// Applies UNION operation to the . + /// Applies UNION operation to the . /// - /// A to perform the operation. + /// A to perform the operation. /// A bool value indicating if resulting table source should remove duplicates. public void ApplyUnion([NotNull] SelectExpression source2, bool distinct) { @@ -904,7 +926,9 @@ private void ApplySetOperation(SetOperationType setOperationType, SelectExpressi continue; } - throw new InvalidOperationException(RelationalStrings.UnknownProjectionMappingType(joinedMapping.Value1.GetType().Name, joinedMapping.Value2.GetType().Name)); + throw new InvalidOperationException( + RelationalStrings.UnknownProjectionMappingType( + joinedMapping.Value1.GetType().Name, joinedMapping.Value2.GetType().Name)); } Offset = null; @@ -919,8 +943,10 @@ private void ApplySetOperation(SetOperationType setOperationType, SelectExpressi void HandleEntityProjection( ProjectionMember projectionMember, - SelectExpression select1, EntityProjectionExpression projection1, - SelectExpression select2, EntityProjectionExpression projection2) + SelectExpression select1, + EntityProjectionExpression projection1, + SelectExpression select2, + EntityProjectionExpression projection2) { if (projection1.EntityType != projection2.EntityType) { @@ -949,8 +975,10 @@ void HandleEntityProjection( } ColumnExpression GenerateDiscriminatorExpression( - SelectExpression select1, SqlExpression expression1, - SelectExpression select2, SqlExpression expression2, + SelectExpression select1, + SqlExpression expression1, + SelectExpression select2, + SqlExpression expression2, string alias) { var innerProjection1 = new ProjectionExpression(expression1, alias); @@ -962,8 +990,10 @@ ColumnExpression GenerateDiscriminatorExpression( } ColumnExpression GenerateColumnProjection( - SelectExpression select1, ColumnExpression column1, - SelectExpression select2, ColumnExpression column2) + SelectExpression select1, + ColumnExpression column1, + SelectExpression select2, + ColumnExpression column2) { var alias = GenerateUniqueAlias(column1.Name); var innerProjection1 = new ProjectionExpression(column1, alias); @@ -1014,9 +1044,9 @@ private ColumnExpression GenerateOuterColumn(SqlExpression projection, string al } /// - /// Pushes down the into a subquery. + /// Pushes down the into a subquery. /// - /// A mapping of projections before pushdown to s after pushdown. + /// A mapping of projections before pushdown to s after pushdown. public IDictionary PushdownIntoSubquery() { var subquery = new SelectExpression( @@ -1153,7 +1183,8 @@ EntityProjectionExpression LiftEntityProjectionFromSubquery(EntityProjectionExpr ColumnExpression discriminatorExpression = null; if (entityProjection.DiscriminatorExpression != null) { - discriminatorExpression = subquery.GenerateOuterColumn(entityProjection.DiscriminatorExpression, DiscriminatorColumnAlias); + discriminatorExpression = subquery.GenerateOuterColumn( + entityProjection.DiscriminatorExpression, DiscriminatorColumnAlias); projectionMap[entityProjection.DiscriminatorExpression] = discriminatorExpression; } @@ -1180,7 +1211,7 @@ EntityProjectionExpression LiftEntityProjectionFromSubquery(EntityProjectionExpr } /// - /// Adds a non-scalar single result to the projection of the . + /// Adds a non-scalar single result to the projection of the . /// /// A shaped query expression for the subquery producing single non-scalar result. /// A shaper expression to shape the result of this projection. @@ -1212,9 +1243,10 @@ public Expression AddSingleProjection([NotNull] ShapedQueryExpression shapedQuer var defaultResult = shapedQueryExpression.ResultCardinality == ResultCardinality.SingleOrDefault ? (Expression)Default(shaperExpression.Type) : Block( - Throw(New( - typeof(InvalidOperationException).GetConstructors().Single(ci => ci.GetParameters().Count() == 1), - Constant(RelationalStrings.SequenceContainsNoElements))), + Throw( + New( + typeof(InvalidOperationException).GetConstructors().Single(ci => ci.GetParameters().Count() == 1), + Constant(RelationalStrings.SequenceContainsNoElements))), Default(shaperExpression.Type)); shaperExpression = Condition( @@ -1276,17 +1308,17 @@ public Expression AddSingleProjection([NotNull] ShapedQueryExpression shapedQuer static Expression RemoveConvert(Expression expression) => expression is UnaryExpression unaryExpression && unaryExpression.NodeType == ExpressionType.Convert - ? RemoveConvert(unaryExpression.Operand) - : expression; + ? RemoveConvert(unaryExpression.Operand) + : expression; } /// - /// Adds a collection to the projection of the . + /// Adds a collection to the projection of the . /// /// A shaped query expression for the subquery producing collection result. /// A navigation associated with this collection, if any. /// The type of the element in the collection. - /// A which represents shaping of this collection. + /// A which represents shaping of this collection. public CollectionShaperExpression AddCollectionProjection( [NotNull] ShapedQueryExpression shapedQueryExpression, [CanBeNull] INavigationBase navigation, @@ -1331,14 +1363,15 @@ public Expression ApplyCollectionJoin( if (splitQuery) { var containsReferenceToOuter = new SelectExpressionCorrelationFindingExpressionVisitor(this) - .ContainsOuterReference(innerSelectExpression); + .ContainsOuterReference(innerSelectExpression); if (containsReferenceToOuter) { return null; } var identifierFromParent = _identifier; - if (innerSelectExpression.Tables.LastOrDefault(e => e is InnerJoinExpression) is InnerJoinExpression collectionInnerJoinExpression + if (innerSelectExpression.Tables.LastOrDefault(e => e is InnerJoinExpression) is InnerJoinExpression + collectionInnerJoinExpression && collectionInnerJoinExpression.Table is SelectExpression collectionInnerSelectExpression) { // This computes true parent identifier count for correlation. @@ -1374,16 +1407,19 @@ public Expression ApplyCollectionJoin( { foreach (var partition in rowNumberExpression.Partitions) { - innerOrderingExpressions.Add(new OrderingExpression( - collectionSelectExpression.GenerateOuterColumn(rowNumberSubquery.GenerateOuterColumn(partition)), - ascending: true)); + innerOrderingExpressions.Add( + new OrderingExpression( + collectionSelectExpression.GenerateOuterColumn(rowNumberSubquery.GenerateOuterColumn(partition)), + ascending: true)); } foreach (var ordering in rowNumberExpression.Orderings) { - innerOrderingExpressions.Add(new OrderingExpression( - collectionSelectExpression.GenerateOuterColumn(rowNumberSubquery.GenerateOuterColumn(ordering.Expression)), - ordering.IsAscending)); + innerOrderingExpressions.Add( + new OrderingExpression( + collectionSelectExpression.GenerateOuterColumn( + rowNumberSubquery.GenerateOuterColumn(ordering.Expression)), + ordering.IsAscending)); } } @@ -1398,9 +1434,10 @@ public Expression ApplyCollectionJoin( continue; } - innerOrderingExpressions.Add(new OrderingExpression( - collectionSelectExpression2.GenerateOuterColumn(ordering.Expression), - ordering.IsAscending)); + innerOrderingExpressions.Add( + new OrderingExpression( + collectionSelectExpression2.GenerateOuterColumn(ordering.Expression), + ordering.IsAscending)); } } } @@ -1416,8 +1453,9 @@ public Expression ApplyCollectionJoin( if (identifierIndex < identifierFromParent.Count && outerOrdering.Expression.Equals(identifierFromParent[identifierIndex].Column)) { - innerSelectExpression.AppendOrdering(new OrderingExpression( - innerSelectExpression._identifier[identifierIndex].Column, ascending: true)); + innerSelectExpression.AppendOrdering( + new OrderingExpression( + innerSelectExpression._identifier[identifierIndex].Column, ascending: true)); identifierIndex++; } else @@ -1474,16 +1512,18 @@ public Expression ApplyCollectionJoin( { foreach (var partition in rowNumberExpression.Partitions) { - innerOrderingExpressions.Add(new OrderingExpression( - collectionSelectExpression.GenerateOuterColumn(rowNumberSubquery.GenerateOuterColumn(partition)), - ascending: true)); + innerOrderingExpressions.Add( + new OrderingExpression( + collectionSelectExpression.GenerateOuterColumn(rowNumberSubquery.GenerateOuterColumn(partition)), + ascending: true)); } foreach (var ordering in rowNumberExpression.Orderings) { - innerOrderingExpressions.Add(new OrderingExpression( - collectionSelectExpression.GenerateOuterColumn(rowNumberSubquery.GenerateOuterColumn(ordering.Expression)), - ordering.IsAscending)); + innerOrderingExpressions.Add( + new OrderingExpression( + collectionSelectExpression.GenerateOuterColumn(rowNumberSubquery.GenerateOuterColumn(ordering.Expression)), + ordering.IsAscending)); } } else if (joinedTable is SelectExpression collectionSelectExpression2 @@ -1496,9 +1536,10 @@ public Expression ApplyCollectionJoin( continue; } - innerOrderingExpressions.Add(new OrderingExpression( - collectionSelectExpression2.GenerateOuterColumn(ordering.Expression), - ordering.IsAscending)); + innerOrderingExpressions.Add( + new OrderingExpression( + collectionSelectExpression2.GenerateOuterColumn(ordering.Expression), + ordering.IsAscending)); } } else @@ -1541,8 +1582,10 @@ public Expression ApplyCollectionJoin( { newEntityIndexMap[item.Key] = indexMap[item.Value]; } + mappedValue = newEntityIndexMap; } + mapping[projection.Key] = mappedValue; } @@ -1553,8 +1596,8 @@ public Expression ApplyCollectionJoin( var (selfIdentifier, selfIdentifierValueComparers) = GetIdentifierAccessor( innerSelectExpression._identifier - .Except(innerSelectExpression._childIdentifiers) - .Select(e => (e.Column.MakeNullable(), e.Comparer))); + .Except(innerSelectExpression._childIdentifiers) + .Select(e => (e.Column.MakeNullable(), e.Comparer))); foreach (var identifier in innerSelectExpression._identifier) { @@ -1683,12 +1726,12 @@ private SqlBinaryExpression ValidateKeyComparison( bool allowNonEquality) { if (sqlBinaryExpression.OperatorType == ExpressionType.Equal - || (allowNonEquality && - (sqlBinaryExpression.OperatorType == ExpressionType.NotEqual - || sqlBinaryExpression.OperatorType == ExpressionType.GreaterThan - || sqlBinaryExpression.OperatorType == ExpressionType.GreaterThanOrEqual - || sqlBinaryExpression.OperatorType == ExpressionType.LessThan - || sqlBinaryExpression.OperatorType == ExpressionType.LessThanOrEqual))) + || (allowNonEquality + && (sqlBinaryExpression.OperatorType == ExpressionType.NotEqual + || sqlBinaryExpression.OperatorType == ExpressionType.GreaterThan + || sqlBinaryExpression.OperatorType == ExpressionType.GreaterThanOrEqual + || sqlBinaryExpression.OperatorType == ExpressionType.LessThan + || sqlBinaryExpression.OperatorType == ExpressionType.LessThanOrEqual))) { if (sqlBinaryExpression.Left is ColumnExpression leftColumn && sqlBinaryExpression.Right is ColumnExpression rightColumn) @@ -1979,10 +2022,13 @@ private Expression AddJoin( private sealed class ProjectionBindingExpressionRemappingExpressionVisitor : ExpressionVisitor { private readonly Expression _queryExpression; + // Shifting PMs, converting PMs to index/indexMap private IDictionary _projectionMemberMappings; + // Relocating index private int[] _indexMap; + // Shift pending collection offset private int _pendingCollectionOffset; @@ -1991,8 +2037,10 @@ public ProjectionBindingExpressionRemappingExpressionVisitor(Expression queryExp _queryExpression = queryExpression; } - public Expression RemapProjectionMember(Expression expression, - IDictionary projectionMemberMappings, int pendingCollectionOffset = 0) + public Expression RemapProjectionMember( + Expression expression, + IDictionary projectionMemberMappings, + int pendingCollectionOffset = 0) { _projectionMemberMappings = projectionMemberMappings; _indexMap = null; @@ -2038,16 +2086,14 @@ private ProjectionBindingExpression Remap(ProjectionBindingExpression projection { return CreateNewBinding(_indexMap[index], projectionBindingExpression.Type); } - else - { - var indexMap = new Dictionary(); - foreach (var item in projectionBindingExpression.IndexMap) - { - indexMap[item.Key] = _indexMap[item.Value]; - } - return CreateNewBinding(indexMap, projectionBindingExpression.Type); + var indexMap = new Dictionary(); + foreach (var item in projectionBindingExpression.IndexMap) + { + indexMap[item.Key] = _indexMap[item.Value]; } + + return CreateNewBinding(indexMap, projectionBindingExpression.Type); } var currentProjectionMember = projectionBindingExpression.ProjectionMember; @@ -2097,6 +2143,7 @@ private void AddJoin( { innerSelectExpression.ApplyLimit(limit); } + if (offset != null) { innerSelectExpression.ApplyOffset(offset); @@ -2114,7 +2161,8 @@ private void AddJoin( ? innerSelectExpression._identifier.Select(e => new OrderingExpression(e.Column, true)) : new[] { new OrderingExpression(new SqlFragmentExpression("(SELECT 1)"), true) }; - var rowNumberExpression = new RowNumberExpression(partitions, orderings.ToList(), (limit ?? offset).TypeMapping); + var rowNumberExpression = new RowNumberExpression( + partitions, orderings.ToList(), (limit ?? offset).TypeMapping); innerSelectExpression.ClearOrdering(); var projectionMappings = innerSelectExpression.PushdownIntoSubquery(); @@ -2130,16 +2178,17 @@ private void AddJoin( offsetPredicate = new SqlBinaryExpression( ExpressionType.LessThan, offset, outerColumn, typeof(bool), joinPredicate.TypeMapping); } + if (limit != null) { if (offset != null) { limit = offset is SqlConstantExpression offsetConstant && limit is SqlConstantExpression limitConstant - ? (SqlExpression)new SqlConstantExpression( - Constant((int)offsetConstant.Value + (int)limitConstant.Value), - limit.TypeMapping) - : new SqlBinaryExpression(ExpressionType.Add, offset, limit, limit.Type, limit.TypeMapping); + ? (SqlExpression)new SqlConstantExpression( + Constant((int)offsetConstant.Value + (int)limitConstant.Value), + limit.TypeMapping) + : new SqlBinaryExpression(ExpressionType.Add, offset, limit, limit.Type, limit.TypeMapping); } limitPredicate = new SqlBinaryExpression( @@ -2226,9 +2275,9 @@ private void AddJoin( } /// - /// Adds the given to table sources using INNER JOIN. + /// Adds the given to table sources using INNER JOIN. /// - /// A to join with. + /// A to join with. /// A predicate to use for the join. public void AddInnerJoin([NotNull] SelectExpression innerSelectExpression, [NotNull] SqlExpression joinPredicate) { @@ -2239,9 +2288,9 @@ public void AddInnerJoin([NotNull] SelectExpression innerSelectExpression, [NotN } /// - /// Adds the given to table sources using LEFT JOIN. + /// Adds the given to table sources using LEFT JOIN. /// - /// A to join with. + /// A to join with. /// A predicate to use for the join. public void AddLeftJoin([NotNull] SelectExpression innerSelectExpression, [NotNull] SqlExpression joinPredicate) { @@ -2252,9 +2301,9 @@ public void AddLeftJoin([NotNull] SelectExpression innerSelectExpression, [NotNu } /// - /// Adds the given to table sources using CROSS JOIN. + /// Adds the given to table sources using CROSS JOIN. /// - /// A to join with. + /// A to join with. public void AddCrossJoin([NotNull] SelectExpression innerSelectExpression) { Check.NotNull(innerSelectExpression, nameof(innerSelectExpression)); @@ -2263,9 +2312,9 @@ public void AddCrossJoin([NotNull] SelectExpression innerSelectExpression) } /// - /// Adds the given to table sources using CROSS APPLY. + /// Adds the given to table sources using CROSS APPLY. /// - /// A to join with. + /// A to join with. public void AddCrossApply([NotNull] SelectExpression innerSelectExpression) { Check.NotNull(innerSelectExpression, nameof(innerSelectExpression)); @@ -2274,9 +2323,9 @@ public void AddCrossApply([NotNull] SelectExpression innerSelectExpression) } /// - /// Adds the given to table sources using OUTER APPLY. + /// Adds the given to table sources using OUTER APPLY. /// - /// A to join with. + /// A to join with. public void AddOuterApply([NotNull] SelectExpression innerSelectExpression) { Check.NotNull(innerSelectExpression, nameof(innerSelectExpression)); @@ -2285,9 +2334,9 @@ public void AddOuterApply([NotNull] SelectExpression innerSelectExpression) } /// - /// Adds the query expression of the given to table sources using INNER JOIN and combine shapers. + /// Adds the query expression of the given to table sources using INNER JOIN and combine shapers. /// - /// A to join with. + /// A to join with. /// A predicate to use for the join. /// An expression for outer shaper. /// An expression which shapes the result of this join. @@ -2301,13 +2350,14 @@ public Expression AddInnerJoin( Check.NotNull(outerShaper, nameof(outerShaper)); return AddJoin( - JoinType.InnerJoin, (SelectExpression)innerSource.QueryExpression, outerShaper, innerSource.ShaperExpression, joinPredicate); + JoinType.InnerJoin, (SelectExpression)innerSource.QueryExpression, outerShaper, innerSource.ShaperExpression, + joinPredicate); } /// - /// Adds the query expression of the given to table sources using LEFT JOIN and combine shapers. + /// Adds the query expression of the given to table sources using LEFT JOIN and combine shapers. /// - /// A to join with. + /// A to join with. /// A predicate to use for the join. /// An expression for outer shaper. /// An expression which shapes the result of this join. @@ -2325,9 +2375,9 @@ public Expression AddLeftJoin( } /// - /// Adds the query expression of the given to table sources using CROSS JOIN and combine shapers. + /// Adds the query expression of the given to table sources using CROSS JOIN and combine shapers. /// - /// A to join with. + /// A to join with. /// An expression for outer shaper. /// An expression which shapes the result of this join. public Expression AddCrossJoin( @@ -2341,9 +2391,9 @@ public Expression AddCrossJoin( } /// - /// Adds the query expression of the given to table sources using CROSS APPLY and combine shapers. + /// Adds the query expression of the given to table sources using CROSS APPLY and combine shapers. /// - /// A to join with. + /// A to join with. /// An expression for outer shaper. /// An expression which shapes the result of this join. public Expression AddCrossApply( @@ -2357,9 +2407,9 @@ public Expression AddCrossApply( } /// - /// Adds the query expression of the given to table sources using OUTER APPLY and combine shapers. + /// Adds the query expression of the given to table sources using OUTER APPLY and combine shapers. /// - /// A to join with. + /// A to join with. /// An expression for outer shaper. /// An expression which shapes the result of this join. public Expression AddOuterApply( @@ -2383,8 +2433,11 @@ public SqlRemappingVisitor(IDictionary mappings _mappings = mappings; } - public SqlExpression Remap(SqlExpression sqlExpression) => (SqlExpression)Visit(sqlExpression); - public SelectExpression Remap(SelectExpression sqlExpression) => (SelectExpression)Visit(sqlExpression); + public SqlExpression Remap(SqlExpression sqlExpression) + => (SqlExpression)Visit(sqlExpression); + + public SelectExpression Remap(SelectExpression sqlExpression) + => (SelectExpression)Visit(sqlExpression); public override Expression Visit(Expression expression) { @@ -2451,9 +2504,9 @@ private void AddJoin( } /// - /// Adds the given to table sources using INNER JOIN. + /// Adds the given to table sources using INNER JOIN. /// - /// A to join with. + /// A to join with. /// A predicate to use for the join. /// The type of the result generated after performing the join. [Obsolete("Use the other overloads.")] @@ -2469,9 +2522,9 @@ public void AddInnerJoin( } /// - /// Adds the given to table sources using LEFT JOIN. + /// Adds the given to table sources using LEFT JOIN. /// - /// A to join with. + /// A to join with. /// A predicate to use for the join. /// The type of the result generated after performing the join. [Obsolete("Use the other overloads.")] @@ -2487,9 +2540,9 @@ public void AddLeftJoin( } /// - /// Adds the given to table sources using CROSS JOIN. + /// Adds the given to table sources using CROSS JOIN. /// - /// A to join with. + /// A to join with. /// The type of the result generated after performing the join. [Obsolete("Use the other overloads.")] public void AddCrossJoin([NotNull] SelectExpression innerSelectExpression, [CanBeNull] Type transparentIdentifierType) @@ -2500,9 +2553,9 @@ public void AddCrossJoin([NotNull] SelectExpression innerSelectExpression, [CanB } /// - /// Adds the given to table sources using CROSS APPLY. + /// Adds the given to table sources using CROSS APPLY. /// - /// A to join with. + /// A to join with. /// The type of the result generated after performing the join. [Obsolete("Use the other overloads.")] public void AddCrossApply([NotNull] SelectExpression innerSelectExpression, [CanBeNull] Type transparentIdentifierType) @@ -2513,9 +2566,9 @@ public void AddCrossApply([NotNull] SelectExpression innerSelectExpression, [Can } /// - /// Adds the given to table sources using OUTER APPLY. + /// Adds the given to table sources using OUTER APPLY. /// - /// A to join with. + /// A to join with. /// The type of the result generated after performing the join. [Obsolete("Use the other overloads.")] public void AddOuterApply([NotNull] SelectExpression innerSelectExpression, [CanBeNull] Type transparentIdentifierType) @@ -2979,16 +3032,16 @@ private bool Equals(SelectExpression selectExpression) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. // This does not take internal states since when using this method SelectExpression should be finalized [Obsolete("Use the overload which does not require distinct & alias parameter.")] @@ -3029,14 +3082,14 @@ public SelectExpression Update( /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. // This does not take internal states since when using this method SelectExpression should be finalized public SelectExpression Update( diff --git a/src/EFCore.Relational/Query/SqlExpressions/SetOperationBase.cs b/src/EFCore.Relational/Query/SqlExpressions/SetOperationBase.cs index 4eeeeefc0be..ef0d246acb7 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SetOperationBase.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SetOperationBase.cs @@ -26,7 +26,10 @@ public abstract class SetOperationBase : TableExpressionBase /// A table source which is second source in the set operation. /// A bool value indicating whether result will remove duplicate rows. protected SetOperationBase( - [NotNull] string alias, [NotNull] SelectExpression source1, [NotNull] SelectExpression source2, bool distinct) + [NotNull] string alias, + [NotNull] SelectExpression source1, + [NotNull] SelectExpression source2, + bool distinct) : base(Check.NotEmpty(alias, nameof(alias))) { Check.NotNull(source1, nameof(source1)); @@ -41,10 +44,12 @@ protected SetOperationBase( /// The bool value indicating whether result will remove duplicate rows. /// public virtual bool IsDistinct { get; } + /// /// The first source of the set operation. /// public virtual SelectExpression Source1 { get; } + /// /// The second source of the set operation. /// diff --git a/src/EFCore.Relational/Query/SqlExpressions/SqlBinaryExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SqlBinaryExpression.cs index 3946188227e..520834a780a 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SqlBinaryExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SqlBinaryExpression.cs @@ -56,8 +56,8 @@ internal static bool IsValidOperator(ExpressionType operatorType) /// The operator to apply. /// An expression which is left operand. /// An expression which is right operand. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. public SqlBinaryExpression( ExpressionType operatorType, [NotNull] SqlExpression left, @@ -71,8 +71,9 @@ public SqlBinaryExpression( if (!IsValidOperator(operatorType)) { - throw new InvalidOperationException(RelationalStrings.UnsupportedOperatorForSqlExpression( - operatorType, typeof(SqlBinaryExpression).ShortDisplayName())); + throw new InvalidOperationException( + RelationalStrings.UnsupportedOperatorForSqlExpression( + operatorType, typeof(SqlBinaryExpression).ShortDisplayName())); } OperatorType = operatorType; @@ -84,10 +85,12 @@ public SqlBinaryExpression( /// The operator of this SQL binary operation. /// public virtual ExpressionType OperatorType { get; } + /// /// The left operand. /// public virtual SqlExpression Left { get; } + /// /// The right operand. /// @@ -108,8 +111,8 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual SqlBinaryExpression Update([NotNull] SqlExpression left, [NotNull] SqlExpression right) { @@ -156,7 +159,8 @@ protected override void Print(ExpressionPrinter expressionPrinter) expressionPrinter.Append(")"); } - static bool RequiresBrackets(SqlExpression expression) => expression is SqlBinaryExpression || expression is LikeExpression; + static bool RequiresBrackets(SqlExpression expression) + => expression is SqlBinaryExpression || expression is LikeExpression; } /// @@ -173,6 +177,7 @@ private bool Equals(SqlBinaryExpression sqlBinaryExpression) && Right.Equals(sqlBinaryExpression.Right); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), OperatorType, Left, Right); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), OperatorType, Left, Right); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/SqlConstantExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SqlConstantExpression.cs index ac79633cc0f..dccc290c581 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SqlConstantExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SqlConstantExpression.cs @@ -26,8 +26,8 @@ public class SqlConstantExpression : SqlExpression /// /// Creates a new instance of the class. /// - /// A . - /// The associated with the expression. + /// A . + /// The associated with the expression. public SqlConstantExpression([NotNull] ConstantExpression constantExpression, [CanBeNull] RelationalTypeMapping typeMapping) : base(Check.NotNull(constantExpression, nameof(constantExpression)).Type.UnwrapNullableType(), typeMapping) { @@ -37,7 +37,8 @@ public SqlConstantExpression([NotNull] ConstantExpression constantExpression, [C /// /// The constant value. /// - public virtual object Value => _constantExpression.Value; + public virtual object Value + => _constantExpression.Value; /// /// Applies supplied type mapping to this expression. @@ -107,6 +108,7 @@ private bool ValueEquals(object value1, object value2) } /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Value); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Value); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/SqlExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SqlExpression.cs index d800204368e..a6269b9588c 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SqlExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SqlExpression.cs @@ -24,8 +24,8 @@ public abstract class SqlExpression : Expression, IPrintableExpression /// /// Creates a new instance of the class. /// - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. protected SqlExpression([NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) { Check.NotNull(type, nameof(type)); @@ -40,7 +40,7 @@ protected SqlExpression([NotNull] Type type, [CanBeNull] RelationalTypeMapping t public override Type Type { get; } /// - /// The associated with this expression. + /// The associated with this expression. /// public virtual RelationalTypeMapping TypeMapping { get; } @@ -49,16 +49,18 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) => throw new InvalidOperationException(RelationalStrings.VisitChildrenMustBeOverridden); /// - public sealed override ExpressionType NodeType => ExpressionType.Extension; + public sealed override ExpressionType NodeType + => ExpressionType.Extension; /// - /// Creates a printable string representation of the given expression using . + /// Creates a printable string representation of the given expression using . /// /// The expression printer to use. protected abstract void Print([NotNull] ExpressionPrinter expressionPrinter); /// - void IPrintableExpression.Print(ExpressionPrinter expressionPrinter) => Print(expressionPrinter); + void IPrintableExpression.Print(ExpressionPrinter expressionPrinter) + => Print(expressionPrinter); /// public override bool Equals(object obj) @@ -69,10 +71,11 @@ public override bool Equals(object obj) private bool Equals(SqlExpression sqlExpression) => Type == sqlExpression.Type - && ((TypeMapping == null && sqlExpression.TypeMapping == null) - || TypeMapping?.Equals(sqlExpression.TypeMapping) == true); + && ((TypeMapping == null && sqlExpression.TypeMapping == null) + || TypeMapping?.Equals(sqlExpression.TypeMapping) == true); /// - public override int GetHashCode() => HashCode.Combine(Type, TypeMapping); + public override int GetHashCode() + => HashCode.Combine(Type, TypeMapping); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/SqlFragmentExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SqlFragmentExpression.cs index 961ea3fc427..e1959727b18 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SqlFragmentExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SqlFragmentExpression.cs @@ -65,6 +65,7 @@ private bool Equals(SqlFragmentExpression sqlFragmentExpression) && !string.Equals(Sql, "*"); // We make star projection different because it could be coming from different table. /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Sql); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Sql); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/SqlFunctionExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SqlFunctionExpression.cs index 4d8ac7c1e94..925be2edf72 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SqlFunctionExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SqlFunctionExpression.cs @@ -28,14 +28,15 @@ public class SqlFunctionExpression : SqlExpression /// /// The name of the function. /// A bool value indicating whether this function can return null. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. public SqlFunctionExpression( [NotNull] string functionName, bool nullable, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) - : this(instance: null, schema: null, functionName, nullable, instancePropagatesNullability: null, builtIn: true, type, typeMapping) + : this( + instance: null, schema: null, functionName, nullable, instancePropagatesNullability: null, builtIn: true, type, typeMapping) { } @@ -45,27 +46,30 @@ public SqlFunctionExpression( /// The schema in which the function is defined. /// The name of the function. /// A bool value indicating whether this function can return null. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. public SqlFunctionExpression( [NotNull] string schema, [NotNull] string functionName, bool nullable, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) - : this(instance: null, Check.NotEmpty(schema, nameof(schema)), functionName, nullable, instancePropagatesNullability: null, builtIn: false, type, typeMapping) + : this( + instance: null, Check.NotEmpty(schema, nameof(schema)), functionName, nullable, instancePropagatesNullability: null, + builtIn: false, type, typeMapping) { } /// - /// Creates a new instance of the class which represents a niladic function which is invoked on an instance. + /// Creates a new instance of the class which represents a niladic function which is invoked on an + /// instance. /// /// An expression on which the function is defined. /// The name of the function. /// A bool value indicating whether this function can return null. /// A value indicating if instance propagates null to result. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. public SqlFunctionExpression( [NotNull] SqlExpression instance, [NotNull] string functionName, @@ -73,7 +77,9 @@ public SqlFunctionExpression( bool instancePropagatesNullability, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) - : this(Check.NotNull(instance, nameof(instance)), schema: null, functionName, nullable, instancePropagatesNullability, builtIn: true, type, typeMapping) + : this( + Check.NotNull(instance, nameof(instance)), schema: null, functionName, nullable, instancePropagatesNullability, + builtIn: true, type, typeMapping) { } @@ -86,7 +92,9 @@ private SqlFunctionExpression( bool builtIn, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) - : this(instance, schema, name, niladic: true, arguments: null, nullable, instancePropagatesNullability, argumentsPropagateNullability: null, builtIn, type, typeMapping) + : this( + instance, schema, name, niladic: true, arguments: null, nullable, instancePropagatesNullability, + argumentsPropagateNullability: null, builtIn, type, typeMapping) { } @@ -97,8 +105,8 @@ private SqlFunctionExpression( /// The arguments of the function. /// A bool value indicating whether this function can return null. /// A list of bool values indicating whether individual arguments propagate null to result. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. public SqlFunctionExpression( [NotNull] string functionName, [NotNull] IEnumerable arguments, @@ -106,7 +114,9 @@ public SqlFunctionExpression( [NotNull] IEnumerable argumentsPropagateNullability, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) - : this(instance: null, schema: null, functionName, arguments, nullable, instancePropagatesNullability: null, argumentsPropagateNullability, builtIn: true, type, typeMapping) + : this( + instance: null, schema: null, functionName, arguments, nullable, instancePropagatesNullability: null, + argumentsPropagateNullability, builtIn: true, type, typeMapping) { } @@ -118,8 +128,8 @@ public SqlFunctionExpression( /// The arguments of the function. /// A bool value indicating whether this function can return null. /// A list of bool values indicating whether individual arguments propagate null to result. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. public SqlFunctionExpression( [CanBeNull] string schema, [NotNull] string functionName, @@ -128,7 +138,9 @@ public SqlFunctionExpression( [NotNull] IEnumerable argumentsPropagateNullability, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) - : this(instance: null, Check.NullButNotEmpty(schema, nameof(schema)), functionName, arguments, nullable, instancePropagatesNullability: null, argumentsPropagateNullability, builtIn: false, type, typeMapping) + : this( + instance: null, Check.NullButNotEmpty(schema, nameof(schema)), functionName, arguments, nullable, + instancePropagatesNullability: null, argumentsPropagateNullability, builtIn: false, type, typeMapping) { } @@ -141,8 +153,8 @@ public SqlFunctionExpression( /// A bool value indicating whether this function can return null. /// A value indicating if instance propagates null to result. /// A list of bool values indicating whether individual arguments propagate null to result. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. public SqlFunctionExpression( [NotNull] SqlExpression instance, [NotNull] string functionName, @@ -152,7 +164,9 @@ public SqlFunctionExpression( [NotNull] IEnumerable argumentsPropagateNullability, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) - : this(Check.NotNull(instance, nameof(instance)), schema: null, functionName, arguments, nullable, instancePropagatesNullability, argumentsPropagateNullability, builtIn: true, type, typeMapping) + : this( + Check.NotNull(instance, nameof(instance)), schema: null, functionName, arguments, nullable, instancePropagatesNullability, + argumentsPropagateNullability, builtIn: true, type, typeMapping) { } @@ -167,7 +181,10 @@ private SqlFunctionExpression( bool builtIn, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) - : this(instance, schema, name, niladic: false, Check.NotNull(arguments, nameof(arguments)), nullable, instancePropagatesNullability, Check.NotNull(argumentsPropagateNullability, nameof(argumentsPropagateNullability)) , builtIn, type, typeMapping) + : this( + instance, schema, name, niladic: false, Check.NotNull(arguments, nameof(arguments)), nullable, + instancePropagatesNullability, Check.NotNull(argumentsPropagateNullability, nameof(argumentsPropagateNullability)), builtIn, + type, typeMapping) { } @@ -232,17 +249,18 @@ private SqlFunctionExpression( /// /// A bool value indicating if the function can return null result. /// - public virtual bool IsNullable { get; private set; } + public virtual bool IsNullable { get; } /// /// A bool value indicating if the instance propagates null to the result. /// - public virtual bool? InstancePropagatesNullability { get; private set; } + public virtual bool? InstancePropagatesNullability { get; } + /// /// A list of bool values indicating whether individual argument propagate null to the result. /// - public virtual IReadOnlyList ArgumentsPropagateNullability { get; private set; } + public virtual IReadOnlyList ArgumentsPropagateNullability { get; } /// protected override Expression VisitChildren(ExpressionVisitor visitor) @@ -303,8 +321,8 @@ public virtual SqlFunctionExpression ApplyTypeMapping([CanBeNull] RelationalType /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual SqlFunctionExpression Update([CanBeNull] SqlExpression instance, [CanBeNull] IReadOnlyList arguments) { @@ -390,23 +408,23 @@ public override int GetHashCode() /// Creates a new instance of the class. /// /// The name of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. [Obsolete("Use new SqlFunctionExpression(...) with appropriate arguments.")] [EditorBrowsable(EditorBrowsableState.Never)] public static SqlFunctionExpression CreateNiladic( - [NotNull] string name, - [NotNull] Type type, - [CanBeNull] RelationalTypeMapping typeMapping) - => new SqlFunctionExpression(name, nullable: true, type, typeMapping); + [NotNull] string name, + [NotNull] Type type, + [CanBeNull] RelationalTypeMapping typeMapping) + => new SqlFunctionExpression(name, nullable: true, type, typeMapping); /// /// Creates a new instance of the class. /// /// The schema in which the function is defined. /// The name of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. [Obsolete("Use new SqlFunctionExpression(...) with appropriate arguments.")] [EditorBrowsable(EditorBrowsableState.Never)] public static SqlFunctionExpression CreateNiladic( @@ -421,8 +439,8 @@ public static SqlFunctionExpression CreateNiladic( /// /// An expression on which the function is defined. /// The name of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. [Obsolete("Use new SqlFunctionExpression(...) with appropriate arguments.")] [EditorBrowsable(EditorBrowsableState.Never)] public static SqlFunctionExpression CreateNiladic( @@ -438,8 +456,8 @@ public static SqlFunctionExpression CreateNiladic( /// An expression on which the function is applied. /// The name of the function. /// The arguments of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. [Obsolete("Use new SqlFunctionExpression(...) with appropriate arguments.")] [EditorBrowsable(EditorBrowsableState.Never)] public static SqlFunctionExpression Create( @@ -463,8 +481,8 @@ public static SqlFunctionExpression Create( /// /// The name of the function. /// The arguments of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. [Obsolete("Use new SqlFunctionExpression(...) with appropriate arguments.")] [EditorBrowsable(EditorBrowsableState.Never)] public static SqlFunctionExpression Create( @@ -472,7 +490,8 @@ public static SqlFunctionExpression Create( [NotNull] IEnumerable arguments, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) - => new SqlFunctionExpression(name, arguments, nullable: true, argumentsPropagateNullability: arguments.Select(a => false), type, typeMapping); + => new SqlFunctionExpression( + name, arguments, nullable: true, argumentsPropagateNullability: arguments.Select(a => false), type, typeMapping); /// /// Creates a new instance of the class. @@ -480,8 +499,8 @@ public static SqlFunctionExpression Create( /// The schema in which the function is defined. /// The name of the function. /// The arguments of the function. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. [Obsolete("Use new SqlFunctionExpression(...) with appropriate arguments.")] [EditorBrowsable(EditorBrowsableState.Never)] public static SqlFunctionExpression Create( @@ -490,7 +509,8 @@ public static SqlFunctionExpression Create( [NotNull] IEnumerable arguments, [NotNull] Type type, [CanBeNull] RelationalTypeMapping typeMapping) - => new SqlFunctionExpression(schema, name, arguments, nullable: true, argumentsPropagateNullability: arguments.Select(a => false), type, typeMapping); + => new SqlFunctionExpression( + schema, name, arguments, nullable: true, argumentsPropagateNullability: arguments.Select(a => false), type, typeMapping); #endregion } diff --git a/src/EFCore.Relational/Query/SqlExpressions/SqlParameterExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SqlParameterExpression.cs index d3cc2e44cc0..333657171a1 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SqlParameterExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SqlParameterExpression.cs @@ -14,7 +14,7 @@ namespace Microsoft.EntityFrameworkCore.Query.SqlExpressions /// An expression that represents a parameter in a SQL tree. /// /// - /// This is a simple wrapper around a in the SQL tree. + /// This is a simple wrapper around a in the SQL tree. /// Instances of this type cannot be constructed by application or database provider code. If this is a problem for your /// application or provider, then please file an issue at https://github.com/dotnet/efcore. /// @@ -33,7 +33,8 @@ internal SqlParameterExpression(ParameterExpression parameterExpression, Relatio /// /// The name of the parameter. /// - public string Name => _parameterExpression.Name; + public string Name + => _parameterExpression.Name; /// /// The bool value indicating if this parameter can have null values. @@ -76,6 +77,7 @@ private bool Equals(SqlParameterExpression sqlParameterExpression) && string.Equals(Name, sqlParameterExpression.Name); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Name); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Name); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/SqlUnaryExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/SqlUnaryExpression.cs index b00410d08da..24b84e6cb62 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/SqlUnaryExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/SqlUnaryExpression.cs @@ -40,8 +40,8 @@ internal static bool IsValidOperator(ExpressionType operatorType) /// /// The operator to apply. /// An expression on which operator is applied. - /// The of the expression. - /// The associated with the expression. + /// The of the expression. + /// The associated with the expression. public SqlUnaryExpression( ExpressionType operatorType, [NotNull] SqlExpression operand, @@ -54,8 +54,9 @@ public SqlUnaryExpression( if (!IsValidOperator(operatorType)) { - throw new InvalidOperationException(RelationalStrings.UnsupportedOperatorForSqlExpression( - operatorType, typeof(SqlUnaryExpression).ShortDisplayName())); + throw new InvalidOperationException( + RelationalStrings.UnsupportedOperatorForSqlExpression( + operatorType, typeof(SqlUnaryExpression).ShortDisplayName())); } OperatorType = operatorType; @@ -66,6 +67,7 @@ public SqlUnaryExpression( /// The operator of this SQL unary operation. /// public virtual ExpressionType OperatorType { get; } + /// /// The operand of this SQL unary operation. /// @@ -83,7 +85,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual SqlUnaryExpression Update([NotNull] SqlExpression operand) { @@ -130,6 +132,7 @@ private bool Equals(SqlUnaryExpression sqlUnaryExpression) && Operand.Equals(sqlUnaryExpression.Operand); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), OperatorType, Operand); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), OperatorType, Operand); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/TableExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/TableExpression.cs index 2cfc39d5a7a..541521e1039 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/TableExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/TableExpression.cs @@ -52,7 +52,7 @@ protected override void Print(ExpressionPrinter expressionPrinter) public string Schema { get; } /// - /// The associated with this table or view. + /// The associated with this table or view. /// public ITableBase Table { get; } @@ -62,6 +62,7 @@ public override bool Equals(object obj) => obj != null && ReferenceEquals(this, obj); /// - public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Name, Schema); + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), Name, Schema); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/TableExpressionBase.cs b/src/EFCore.Relational/Query/SqlExpressions/TableExpressionBase.cs index d475d18015a..9d90272b378 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/TableExpressionBase.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/TableExpressionBase.cs @@ -44,18 +44,22 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) } /// - public override Type Type => typeof(object); + public override Type Type + => typeof(object); + /// - public sealed override ExpressionType NodeType => ExpressionType.Extension; + public sealed override ExpressionType NodeType + => ExpressionType.Extension; /// - /// Creates a printable string representation of the given expression using . + /// Creates a printable string representation of the given expression using . /// /// The expression printer to use. protected abstract void Print([NotNull] ExpressionPrinter expressionPrinter); /// - void IPrintableExpression.Print(ExpressionPrinter expressionPrinter) => Print(expressionPrinter); + void IPrintableExpression.Print(ExpressionPrinter expressionPrinter) + => Print(expressionPrinter); /// public override bool Equals(object obj) @@ -68,6 +72,7 @@ private bool Equals(TableExpressionBase tableExpressionBase) => string.Equals(Alias, tableExpressionBase.Alias); /// - public override int GetHashCode() => HashCode.Combine(Alias); + public override int GetHashCode() + => HashCode.Combine(Alias); } } diff --git a/src/EFCore.Relational/Query/SqlExpressions/TableValuedFunctionExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/TableValuedFunctionExpression.cs index cb1a2105bff..91f291996fc 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/TableValuedFunctionExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/TableValuedFunctionExpression.cs @@ -25,12 +25,13 @@ public class TableValuedFunctionExpression : TableExpressionBase /// /// Creates a new instance of the class. /// - /// The associated this function. + /// The associated this function. /// The arguments of the function. public TableValuedFunctionExpression([NotNull] IStoreFunction storeFunction, [NotNull] IReadOnlyList arguments) - : this(storeFunction.Name.Substring(0, 1).ToLower(), - Check.NotNull(storeFunction, nameof(storeFunction)), - Check.NotNull(arguments, nameof(arguments))) + : this( + storeFunction.Name.Substring(0, 1).ToLower(), + Check.NotNull(storeFunction, nameof(storeFunction)), + Check.NotNull(arguments, nameof(arguments))) { } @@ -50,7 +51,9 @@ private TableValuedFunctionExpression(string alias, IStoreFunction storeFunction /// The list of arguments of this function. /// public virtual IReadOnlyList Arguments - { get; } + { + get; + } /// protected override Expression VisitChildren(ExpressionVisitor visitor) @@ -74,7 +77,7 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual TableValuedFunctionExpression Update([NotNull] IReadOnlyList arguments) { diff --git a/src/EFCore.Relational/Query/SqlExpressions/UnionExpression.cs b/src/EFCore.Relational/Query/SqlExpressions/UnionExpression.cs index 758a8ae0150..9fc3a64af9e 100644 --- a/src/EFCore.Relational/Query/SqlExpressions/UnionExpression.cs +++ b/src/EFCore.Relational/Query/SqlExpressions/UnionExpression.cs @@ -50,8 +50,8 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) /// Creates a new expression that is like this one, but using the supplied children. If all of the children are the same, it will /// return this expression. /// - /// The property of the result. - /// The property of the result. + /// The property of the result. + /// The property of the result. /// This expression if no children changed, or an expression with the updated children. public virtual UnionExpression Update([NotNull] SelectExpression source1, [NotNull] SelectExpression source2) { diff --git a/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs b/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs index 0b18bb2d058..25e79db6a4c 100644 --- a/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs +++ b/src/EFCore.Relational/Query/SqlNullabilityProcessor.cs @@ -57,14 +57,16 @@ public SqlNullabilityProcessor( protected virtual IReadOnlyDictionary ParameterValues { get; private set; } /// - /// Processes a to apply null semantics and optimize it. + /// Processes a to apply null semantics and optimize it. /// /// A select expression to process. /// A dictionary of parameter values in use. /// A bool value indicating whether the select expression can be cached. /// An optimized select expression. public virtual SelectExpression Process( - [NotNull] SelectExpression selectExpression, [NotNull] IReadOnlyDictionary parameterValues, out bool canCache) + [NotNull] SelectExpression selectExpression, + [NotNull] IReadOnlyDictionary parameterValues, + out bool canCache) { Check.NotNull(selectExpression, nameof(selectExpression)); Check.NotNull(parameterValues, nameof(parameterValues)); @@ -82,7 +84,8 @@ public virtual SelectExpression Process( /// /// Marks the select expression being processed as cannot be cached. /// - protected virtual void DoNotCache() => _canCache = false; + protected virtual void DoNotCache() + => _canCache = false; /// /// Adds a column to non nullable columns list to further optimizations can take the column as non-nullable. @@ -92,7 +95,7 @@ protected virtual void AddNonNullableColumn([NotNull] ColumnExpression columnExp => _nonNullableColumns.Add(Check.NotNull(columnExpression, nameof(columnExpression))); /// - /// Visits a . + /// Visits a . /// /// A table expression base to visit. /// An optimized table expression base. @@ -175,12 +178,13 @@ protected virtual TableExpressionBase Visit([NotNull] TableExpressionBase tableE default: throw new InvalidOperationException( - RelationalStrings.UnknownExpressionType(tableExpressionBase, tableExpressionBase.GetType(), nameof(SqlNullabilityProcessor))); + RelationalStrings.UnknownExpressionType( + tableExpressionBase, tableExpressionBase.GetType(), nameof(SqlNullabilityProcessor))); } } /// - /// Visits a . + /// Visits a . /// /// A select expression to visit. /// An optimized select expression. @@ -312,7 +316,7 @@ protected virtual SelectExpression Visit([NotNull] SelectExpression selectExpres } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A sql expression to visit. /// A bool value indicating whether the sql expression is nullable. @@ -321,7 +325,7 @@ protected virtual SqlExpression Visit([CanBeNull] SqlExpression sqlExpression, o => Visit(sqlExpression, allowOptimizedExpansion: false, out nullable); /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A sql expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. @@ -331,7 +335,10 @@ protected virtual SqlExpression Visit([CanBeNull] SqlExpression sqlExpression, b => Visit(sqlExpression, allowOptimizedExpansion, preserveNonNullableColumns: false, out nullable); private SqlExpression Visit( - [CanBeNull] SqlExpression sqlExpression, bool allowOptimizedExpansion, bool preserveNonNullableColumns, out bool nullable) + [CanBeNull] SqlExpression sqlExpression, + bool allowOptimizedExpansion, + bool preserveNonNullableColumns, + out bool nullable) { if (sqlExpression == null) { @@ -343,35 +350,35 @@ private SqlExpression Visit( var result = sqlExpression switch { CaseExpression caseExpression - => VisitCase(caseExpression, allowOptimizedExpansion, out nullable), + => VisitCase(caseExpression, allowOptimizedExpansion, out nullable), CollateExpression collateExpression - => VisitCollate(collateExpression, allowOptimizedExpansion, out nullable), + => VisitCollate(collateExpression, allowOptimizedExpansion, out nullable), ColumnExpression columnExpression - => VisitColumn(columnExpression, allowOptimizedExpansion, out nullable), + => VisitColumn(columnExpression, allowOptimizedExpansion, out nullable), DistinctExpression distinctExpression - => VisitDistinct(distinctExpression, allowOptimizedExpansion, out nullable), + => VisitDistinct(distinctExpression, allowOptimizedExpansion, out nullable), ExistsExpression existsExpression - => VisitExists(existsExpression, allowOptimizedExpansion, out nullable), + => VisitExists(existsExpression, allowOptimizedExpansion, out nullable), InExpression inExpression - => VisitIn(inExpression, allowOptimizedExpansion, out nullable), + => VisitIn(inExpression, allowOptimizedExpansion, out nullable), LikeExpression likeExpression - => VisitLike(likeExpression, allowOptimizedExpansion, out nullable), + => VisitLike(likeExpression, allowOptimizedExpansion, out nullable), RowNumberExpression rowNumberExpression - => VisitRowNumber(rowNumberExpression, allowOptimizedExpansion, out nullable), + => VisitRowNumber(rowNumberExpression, allowOptimizedExpansion, out nullable), ScalarSubqueryExpression scalarSubqueryExpression - => VisitScalarSubquery(scalarSubqueryExpression, allowOptimizedExpansion, out nullable), + => VisitScalarSubquery(scalarSubqueryExpression, allowOptimizedExpansion, out nullable), SqlBinaryExpression sqlBinaryExpression - => VisitSqlBinary(sqlBinaryExpression, allowOptimizedExpansion, out nullable), + => VisitSqlBinary(sqlBinaryExpression, allowOptimizedExpansion, out nullable), SqlConstantExpression sqlConstantExpression - => VisitSqlConstant(sqlConstantExpression, allowOptimizedExpansion, out nullable), + => VisitSqlConstant(sqlConstantExpression, allowOptimizedExpansion, out nullable), SqlFragmentExpression sqlFragmentExpression - => VisitSqlFragment(sqlFragmentExpression, allowOptimizedExpansion, out nullable), + => VisitSqlFragment(sqlFragmentExpression, allowOptimizedExpansion, out nullable), SqlFunctionExpression sqlFunctionExpression - => VisitSqlFunction(sqlFunctionExpression, allowOptimizedExpansion, out nullable), + => VisitSqlFunction(sqlFunctionExpression, allowOptimizedExpansion, out nullable), SqlParameterExpression sqlParameterExpression - => VisitSqlParameter(sqlParameterExpression, allowOptimizedExpansion, out nullable), + => VisitSqlParameter(sqlParameterExpression, allowOptimizedExpansion, out nullable), SqlUnaryExpression sqlUnaryExpression - => VisitSqlUnary(sqlUnaryExpression, allowOptimizedExpansion, out nullable), + => VisitSqlUnary(sqlUnaryExpression, allowOptimizedExpansion, out nullable), _ => VisitCustomSqlExpression(sqlExpression, allowOptimizedExpansion, out nullable) }; @@ -384,19 +391,21 @@ SqlUnaryExpression sqlUnaryExpression } /// - /// Visits a custom added by providers and computes its nullability. + /// Visits a custom added by providers and computes its nullability. /// /// A sql expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitCustomSqlExpression( - [NotNull] SqlExpression sqlExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] SqlExpression sqlExpression, + bool allowOptimizedExpansion, + out bool nullable) => throw new InvalidOperationException( RelationalStrings.UnknownExpressionType(sqlExpression, sqlExpression.GetType(), nameof(SqlNullabilityProcessor))); /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A case expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. @@ -468,19 +477,21 @@ protected virtual SqlExpression VisitCase([NotNull] CaseExpression caseExpressio return elseResult == null && whenClauses.Count == 1 && TryGetBoolConstantValue(whenClauses[0].Test) == true - ? whenClauses[0].Result - : caseExpression.Update(operand, whenClauses, elseResult); + ? whenClauses[0].Result + : caseExpression.Update(operand, whenClauses, elseResult); } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A collate expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitCollate( - [NotNull] CollateExpression collateExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] CollateExpression collateExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(collateExpression, nameof(collateExpression)); @@ -488,14 +499,16 @@ protected virtual SqlExpression VisitCollate( } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A column expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitColumn( - [NotNull] ColumnExpression columnExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] ColumnExpression columnExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(columnExpression, nameof(columnExpression)); @@ -505,14 +518,16 @@ protected virtual SqlExpression VisitColumn( } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A collate expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitDistinct( - [NotNull] DistinctExpression distinctExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] DistinctExpression distinctExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(distinctExpression, nameof(distinctExpression)); @@ -520,14 +535,16 @@ protected virtual SqlExpression VisitDistinct( } /// - /// Visits an and computes its nullability. + /// Visits an and computes its nullability. /// /// An exists expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitExists( - [NotNull] ExistsExpression existsExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] ExistsExpression existsExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(existsExpression, nameof(existsExpression)); @@ -541,7 +558,7 @@ protected virtual SqlExpression VisitExists( } /// - /// Visits an and computes its nullability. + /// Visits an and computes its nullability. /// /// An in expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. @@ -646,7 +663,8 @@ protected virtual SqlExpression VisitIn([NotNull] InExpression inExpression, boo simplifiedInExpression, _sqlExpressionFactory.IsNull(item)); - (SqlConstantExpression ProcessedValuesExpression, List ProcessedValuesList, bool HasNullValue) ProcessInExpressionValues(SqlExpression valuesExpression, bool extractNullValues) + (SqlConstantExpression ProcessedValuesExpression, List ProcessedValuesList, bool HasNullValue) + ProcessInExpressionValues(SqlExpression valuesExpression, bool extractNullValues) { var inValues = new List(); var hasNullValue = false; @@ -681,7 +699,10 @@ protected virtual SqlExpression VisitIn([NotNull] InExpression inExpression, boo return (processedValuesExpression, inValues, hasNullValue); } - SqlExpression SimplifyInExpression(InExpression inExpression, SqlConstantExpression inValuesExpression, List inValuesList) + SqlExpression SimplifyInExpression( + InExpression inExpression, + SqlConstantExpression inValuesExpression, + List inValuesList) { return inValuesList.Count == 1 ? inExpression.IsNegated @@ -696,7 +717,7 @@ SqlExpression SimplifyInExpression(InExpression inExpression, SqlConstantExpress } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A like expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. @@ -716,14 +737,16 @@ protected virtual SqlExpression VisitLike([NotNull] LikeExpression likeExpressio } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A row number expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitRowNumber( - [NotNull] RowNumberExpression rowNumberExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] RowNumberExpression rowNumberExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(rowNumberExpression, nameof(rowNumberExpression)); @@ -752,14 +775,16 @@ protected virtual SqlExpression VisitRowNumber( } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A scalar subquery expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitScalarSubquery( - [NotNull] ScalarSubqueryExpression scalarSubqueryExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] ScalarSubqueryExpression scalarSubqueryExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(scalarSubqueryExpression, nameof(scalarSubqueryExpression)); @@ -769,14 +794,16 @@ protected virtual SqlExpression VisitScalarSubquery( } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A sql binary expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitSqlBinary( - [NotNull] SqlBinaryExpression sqlBinaryExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] SqlBinaryExpression sqlBinaryExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(sqlBinaryExpression, nameof(sqlBinaryExpression)); @@ -883,24 +910,26 @@ protected virtual SqlExpression VisitSqlBinary( return result is SqlBinaryExpression sqlBinaryResult && (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso || sqlBinaryExpression.OperatorType == ExpressionType.OrElse) - ? SimplifyLogicalSqlBinaryExpression(sqlBinaryResult) - : result; + ? SimplifyLogicalSqlBinaryExpression(sqlBinaryResult) + : result; SqlExpression AddNullConcatenationProtection(SqlExpression argument, RelationalTypeMapping typeMapping) => argument is SqlConstantExpression || argument is SqlParameterExpression - ? (SqlExpression)_sqlExpressionFactory.Constant(string.Empty, typeMapping) - : _sqlExpressionFactory.Coalesce(argument, _sqlExpressionFactory.Constant(string.Empty, typeMapping)); + ? (SqlExpression)_sqlExpressionFactory.Constant(string.Empty, typeMapping) + : _sqlExpressionFactory.Coalesce(argument, _sqlExpressionFactory.Constant(string.Empty, typeMapping)); } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A sql constant expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitSqlConstant( - [NotNull] SqlConstantExpression sqlConstantExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] SqlConstantExpression sqlConstantExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(sqlConstantExpression, nameof(sqlConstantExpression)); @@ -910,14 +939,16 @@ protected virtual SqlExpression VisitSqlConstant( } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A sql fragment expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitSqlFragment( - [NotNull] SqlFragmentExpression sqlFragmentExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] SqlFragmentExpression sqlFragmentExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(sqlFragmentExpression, nameof(sqlFragmentExpression)); @@ -927,14 +958,16 @@ protected virtual SqlExpression VisitSqlFragment( } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A sql function expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitSqlFunction( - [NotNull] SqlFunctionExpression sqlFunctionExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] SqlFunctionExpression sqlFunctionExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(sqlFunctionExpression, nameof(sqlFunctionExpression)); @@ -965,22 +998,24 @@ protected virtual SqlExpression VisitSqlFunction( return sqlFunctionExpression.IsBuiltIn && string.Equals(sqlFunctionExpression.Name, "SUM", StringComparison.OrdinalIgnoreCase) - ? _sqlExpressionFactory.Coalesce( + ? _sqlExpressionFactory.Coalesce( sqlFunctionExpression.Update(instance, arguments), _sqlExpressionFactory.Constant(0, sqlFunctionExpression.TypeMapping), sqlFunctionExpression.TypeMapping) - : sqlFunctionExpression.Update(instance, arguments); + : sqlFunctionExpression.Update(instance, arguments); } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A sql parameter expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitSqlParameter( - [NotNull] SqlParameterExpression sqlParameterExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] SqlParameterExpression sqlParameterExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(sqlParameterExpression, nameof(sqlParameterExpression)); @@ -992,14 +1027,16 @@ protected virtual SqlExpression VisitSqlParameter( } /// - /// Visits a and computes its nullability. + /// Visits a and computes its nullability. /// /// A sql unary expression to visit. /// A bool value indicating if optimized expansion which considers null value as false value is allowed. /// A bool value indicating whether the sql expression is nullable. /// An optimized sql expression. protected virtual SqlExpression VisitSqlUnary( - [NotNull] SqlUnaryExpression sqlUnaryExpression, bool allowOptimizedExpansion, out bool nullable) + [NotNull] SqlUnaryExpression sqlUnaryExpression, + bool allowOptimizedExpansion, + out bool nullable) { Check.NotNull(sqlUnaryExpression, nameof(sqlUnaryExpression)); @@ -1033,9 +1070,9 @@ protected virtual SqlExpression VisitSqlUnary( private static bool? TryGetBoolConstantValue(SqlExpression expression) => expression is SqlConstantExpression constantExpression - && constantExpression.Value is bool boolValue - ? boolValue - : (bool?)null; + && constantExpression.Value is bool boolValue + ? boolValue + : (bool?)null; private void RestoreNonNullableColumnsList(int counter) { @@ -1081,8 +1118,12 @@ private SqlExpression ProcessJoinPredicate(SqlExpression predicate) } private SqlExpression OptimizeComparison( - SqlBinaryExpression sqlBinaryExpression, SqlExpression left, SqlExpression right, - bool leftNullable, bool rightNullable, out bool nullable) + SqlBinaryExpression sqlBinaryExpression, + SqlExpression left, + SqlExpression right, + bool leftNullable, + bool rightNullable, + out bool nullable) { var leftNullValue = leftNullable && (left is SqlConstantExpression || left is SqlParameterExpression); var rightNullValue = rightNullable && (right is SqlConstantExpression || right is SqlParameterExpression); @@ -1160,7 +1201,8 @@ private SqlExpression OptimizeComparison( if (!leftNullable && !rightNullable - && (sqlBinaryExpression.OperatorType == ExpressionType.Equal || sqlBinaryExpression.OperatorType == ExpressionType.NotEqual)) + && (sqlBinaryExpression.OperatorType == ExpressionType.Equal + || sqlBinaryExpression.OperatorType == ExpressionType.NotEqual)) { var leftUnary = left as SqlUnaryExpression; var rightUnary = right as SqlUnaryExpression; @@ -1196,8 +1238,13 @@ private SqlExpression OptimizeComparison( } private SqlExpression RewriteNullSemantics( - SqlBinaryExpression sqlBinaryExpression, SqlExpression left, SqlExpression right, - bool leftNullable, bool rightNullable, bool optimize, out bool nullable) + SqlBinaryExpression sqlBinaryExpression, + SqlExpression left, + SqlExpression right, + bool leftNullable, + bool rightNullable, + bool optimize, + out bool nullable) { var leftUnary = left as SqlUnaryExpression; var rightUnary = right as SqlUnaryExpression; @@ -1330,7 +1377,8 @@ private SqlExpression SimplifyLogicalSqlBinaryExpression(SqlBinaryExpression sql // a is null && a is not null -> false return leftUnary.OperatorType == rightUnary.OperatorType ? (SqlExpression)leftUnary - : _sqlExpressionFactory.Constant(sqlBinaryExpression.OperatorType == ExpressionType.OrElse, sqlBinaryExpression.TypeMapping); + : _sqlExpressionFactory.Constant( + sqlBinaryExpression.OperatorType == ExpressionType.OrElse, sqlBinaryExpression.TypeMapping); } // true && a -> a @@ -1347,7 +1395,8 @@ private SqlExpression SimplifyLogicalSqlBinaryExpression(SqlBinaryExpression sql ? newLeftConstant : sqlBinaryExpression.Right; } - else if (sqlBinaryExpression.Right is SqlConstantExpression newRightConstant) + + if (sqlBinaryExpression.Right is SqlConstantExpression newRightConstant) { // a && true -> a // a || true -> true @@ -1401,6 +1450,7 @@ private SqlExpression OptimizeNonNullableNotExpression(SqlUnaryExpression sqlUna case ExpressionType.NotEqual: return _sqlExpressionFactory.IsNull(sqlUnaryOperand.Operand); } + break; } @@ -1441,7 +1491,7 @@ private SqlExpression OptimizeNonNullableNotExpression(SqlUnaryExpression sqlUna sqlBinaryOperand.TypeMapping); } } - break; + break; } return sqlUnaryExpression; @@ -1529,11 +1579,12 @@ private SqlExpression ProcessNullNotNull(SqlUnaryExpression sqlUnaryExpression, sqlUnaryOperand.OperatorType == ExpressionType.NotEqual, sqlUnaryOperand.TypeMapping); } + break; case SqlBinaryExpression sqlBinaryOperand when sqlBinaryOperand.OperatorType != ExpressionType.AndAlso - && sqlBinaryOperand.OperatorType != ExpressionType.OrElse: + && sqlBinaryOperand.OperatorType != ExpressionType.OrElse: { // in general: // binaryOp(a, b) == null -> a == null || b == null @@ -1571,7 +1622,8 @@ private SqlExpression ProcessNullNotNull(SqlUnaryExpression sqlUnaryExpression, case SqlFunctionExpression sqlFunctionExpression: { - if (sqlFunctionExpression.IsBuiltIn && string.Equals("COALESCE", sqlFunctionExpression.Name, StringComparison.OrdinalIgnoreCase)) + if (sqlFunctionExpression.IsBuiltIn + && string.Equals("COALESCE", sqlFunctionExpression.Name, StringComparison.OrdinalIgnoreCase)) { // for coalesce: // (a ?? b) == null -> a == null && b == null @@ -1637,22 +1689,24 @@ private SqlExpression ProcessNullNotNull(SqlUnaryExpression sqlUnaryExpression, if (nullabilityPropagationElements.Count > 0) { var result = nullabilityPropagationElements - .Select(e => ProcessNullNotNull( - _sqlExpressionFactory.MakeUnary( - sqlUnaryExpression.OperatorType, - e, - sqlUnaryExpression.Type, - sqlUnaryExpression.TypeMapping), - operandNullable)) - .Aggregate((r, e) => SimplifyLogicalSqlBinaryExpression( - sqlUnaryExpression.OperatorType == ExpressionType.Equal - ? _sqlExpressionFactory.OrElse(r, e) - : _sqlExpressionFactory.AndAlso(r, e))); + .Select( + e => ProcessNullNotNull( + _sqlExpressionFactory.MakeUnary( + sqlUnaryExpression.OperatorType, + e, + sqlUnaryExpression.Type, + sqlUnaryExpression.TypeMapping), + operandNullable)) + .Aggregate( + (r, e) => SimplifyLogicalSqlBinaryExpression( + sqlUnaryExpression.OperatorType == ExpressionType.Equal + ? _sqlExpressionFactory.OrElse(r, e) + : _sqlExpressionFactory.AndAlso(r, e))); return result; } } - break; + break; } return sqlUnaryExpression; @@ -1742,8 +1796,8 @@ private SqlExpression ExpandNegatedNullableEqualNullable( SimplifyLogicalSqlBinaryExpression( _sqlExpressionFactory.AndAlso( _sqlExpressionFactory.NotEqual(left, right), - SimplifyLogicalSqlBinaryExpression( - _sqlExpressionFactory.AndAlso(leftIsNotNull, rightIsNotNull)))), + SimplifyLogicalSqlBinaryExpression( + _sqlExpressionFactory.AndAlso(leftIsNotNull, rightIsNotNull)))), SimplifyLogicalSqlBinaryExpression( _sqlExpressionFactory.AndAlso(leftIsNull, rightIsNull)))); @@ -1758,7 +1812,9 @@ private SqlExpression ExpandNegatedNullableEqualNullable( // N | 0 | N | 0 | 0 | // N | 1 | N | 0 | 0 | private SqlExpression ExpandNullableEqualNonNullable( - SqlExpression left, SqlExpression right, SqlExpression leftIsNotNull) + SqlExpression left, + SqlExpression right, + SqlExpression leftIsNotNull) => SimplifyLogicalSqlBinaryExpression( _sqlExpressionFactory.AndAlso( _sqlExpressionFactory.Equal(left, right), @@ -1775,7 +1831,9 @@ private SqlExpression ExpandNullableEqualNonNullable( // N | 0 | N | 0 | 0 | // N | 1 | N | 0 | 0 | private SqlExpression ExpandNegatedNullableEqualNonNullable( - SqlExpression left, SqlExpression right, SqlExpression leftIsNotNull) + SqlExpression left, + SqlExpression right, + SqlExpression leftIsNotNull) => SimplifyLogicalSqlBinaryExpression( _sqlExpressionFactory.AndAlso( _sqlExpressionFactory.NotEqual(left, right), @@ -1876,7 +1934,9 @@ private SqlExpression ExpandNegatedNullableNotEqualNullable( // N | 0 | N | 1 | 1 | // N | 1 | N | 1 | 1 | private SqlExpression ExpandNullableNotEqualNonNullable( - SqlExpression left, SqlExpression right, SqlExpression leftIsNull) + SqlExpression left, + SqlExpression right, + SqlExpression leftIsNull) => SimplifyLogicalSqlBinaryExpression( _sqlExpressionFactory.OrElse( _sqlExpressionFactory.NotEqual(left, right), @@ -1893,7 +1953,9 @@ private SqlExpression ExpandNullableNotEqualNonNullable( // N | 0 | N | 1 | 1 | // N | 1 | N | 1 | 1 | private SqlExpression ExpandNegatedNullableNotEqualNonNullable( - SqlExpression left, SqlExpression right, SqlExpression leftIsNull) + SqlExpression left, + SqlExpression right, + SqlExpression leftIsNull) => SimplifyLogicalSqlBinaryExpression( _sqlExpressionFactory.OrElse( _sqlExpressionFactory.Equal(left, right), diff --git a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseColumn.cs b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseColumn.cs index a11bb811ab4..d3901ed054c 100644 --- a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseColumn.cs +++ b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseColumn.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; @@ -67,6 +66,7 @@ public class DatabaseColumn : Annotatable public virtual ValueGenerated? ValueGenerated { get; set; } /// - public override string ToString() => Name ?? ""; + public override string ToString() + => Name ?? ""; } } diff --git a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseForeignKey.cs b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseForeignKey.cs index 989842fcce6..6326e0ce23f 100644 --- a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseForeignKey.cs +++ b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseForeignKey.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Generic; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -47,6 +46,7 @@ public class DatabaseForeignKey : Annotatable public virtual ReferentialAction? OnDelete { get; set; } /// - public override string ToString() => Name ?? ""; + public override string ToString() + => Name ?? ""; } } diff --git a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseIndex.cs b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseIndex.cs index 0901296bbfc..7185ca69ed6 100644 --- a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseIndex.cs +++ b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseIndex.cs @@ -38,6 +38,7 @@ public class DatabaseIndex : Annotatable public virtual string Filter { get; [param: CanBeNull] set; } /// - public override string ToString() => Name ?? ""; + public override string ToString() + => Name ?? ""; } } diff --git a/src/EFCore.Relational/Scaffolding/Metadata/DatabasePrimaryKey.cs b/src/EFCore.Relational/Scaffolding/Metadata/DatabasePrimaryKey.cs index 965d404bc4f..498c5046651 100644 --- a/src/EFCore.Relational/Scaffolding/Metadata/DatabasePrimaryKey.cs +++ b/src/EFCore.Relational/Scaffolding/Metadata/DatabasePrimaryKey.cs @@ -28,6 +28,7 @@ public class DatabasePrimaryKey : Annotatable public virtual IList Columns { get; } = new List(); /// - public override string ToString() => Name ?? ""; + public override string ToString() + => Name ?? ""; } } diff --git a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseUniqueConstraint.cs b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseUniqueConstraint.cs index ccd58bb24c7..c04eb7dde2c 100644 --- a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseUniqueConstraint.cs +++ b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseUniqueConstraint.cs @@ -28,6 +28,7 @@ public class DatabaseUniqueConstraint : Annotatable public virtual IList Columns { get; } = new List(); /// - public override string ToString() => Name ?? ""; + public override string ToString() + => Name ?? ""; } } diff --git a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseView.cs b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseView.cs index 61204e5a976..1f936e7ad18 100644 --- a/src/EFCore.Relational/Scaffolding/Metadata/DatabaseView.cs +++ b/src/EFCore.Relational/Scaffolding/Metadata/DatabaseView.cs @@ -1,8 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using JetBrains.Annotations; - namespace Microsoft.EntityFrameworkCore.Scaffolding.Metadata { /// diff --git a/src/EFCore.Relational/Storage/DateTimeOffsetTypeMapping.cs b/src/EFCore.Relational/Storage/DateTimeOffsetTypeMapping.cs index 74ab05b75d0..e8ffe06fdfc 100644 --- a/src/EFCore.Relational/Storage/DateTimeOffsetTypeMapping.cs +++ b/src/EFCore.Relational/Storage/DateTimeOffsetTypeMapping.cs @@ -52,6 +52,7 @@ protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters p /// /// Gets the string format to be used to generate SQL literals of this type. /// - protected override string SqlLiteralFormatString => "TIMESTAMP '" + DateTimeOffsetFormatConst + "'"; + protected override string SqlLiteralFormatString + => "TIMESTAMP '" + DateTimeOffsetFormatConst + "'"; } } diff --git a/src/EFCore.Relational/Storage/DateTimeTypeMapping.cs b/src/EFCore.Relational/Storage/DateTimeTypeMapping.cs index c38348b2bb6..1b527934562 100644 --- a/src/EFCore.Relational/Storage/DateTimeTypeMapping.cs +++ b/src/EFCore.Relational/Storage/DateTimeTypeMapping.cs @@ -52,6 +52,7 @@ protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters p /// /// Gets the string format to be used to generate SQL literals of this type. /// - protected override string SqlLiteralFormatString => "TIMESTAMP '" + DateTimeFormatConst + "'"; + protected override string SqlLiteralFormatString + => "TIMESTAMP '" + DateTimeFormatConst + "'"; } } diff --git a/src/EFCore.Relational/Storage/DecimalTypeMapping.cs b/src/EFCore.Relational/Storage/DecimalTypeMapping.cs index d334f0a8bb7..3dcf0e551b6 100644 --- a/src/EFCore.Relational/Storage/DecimalTypeMapping.cs +++ b/src/EFCore.Relational/Storage/DecimalTypeMapping.cs @@ -55,6 +55,7 @@ protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters p /// /// Gets the string format to be used to generate SQL literals of this type. /// - protected override string SqlLiteralFormatString => DecimalFormatConst; + protected override string SqlLiteralFormatString + => DecimalFormatConst; } } diff --git a/src/EFCore.Relational/Storage/GuidTypeMapping.cs b/src/EFCore.Relational/Storage/GuidTypeMapping.cs index 8d650e55878..6e9eb868a83 100644 --- a/src/EFCore.Relational/Storage/GuidTypeMapping.cs +++ b/src/EFCore.Relational/Storage/GuidTypeMapping.cs @@ -50,6 +50,7 @@ protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters p /// /// Gets the string format to be used to generate SQL literals of this type. /// - protected override string SqlLiteralFormatString => "'{0}'"; + protected override string SqlLiteralFormatString + => "'{0}'"; } } diff --git a/src/EFCore.Relational/Storage/IRelationalCommand.cs b/src/EFCore.Relational/Storage/IRelationalCommand.cs index 5246120a0a6..05df150dc0e 100644 --- a/src/EFCore.Relational/Storage/IRelationalCommand.cs +++ b/src/EFCore.Relational/Storage/IRelationalCommand.cs @@ -105,6 +105,7 @@ Task ExecuteReaderAsync( DbCommand CreateDbCommand( RelationalCommandParameterObject parameterObject, Guid commandId, - DbCommandMethod commandMethod) => throw new NotImplementedException(); + DbCommandMethod commandMethod) + => throw new NotImplementedException(); } } diff --git a/src/EFCore.Relational/Storage/IRelationalConnection.cs b/src/EFCore.Relational/Storage/IRelationalConnection.cs index 5008a3a3525..def75ec554f 100644 --- a/src/EFCore.Relational/Storage/IRelationalConnection.cs +++ b/src/EFCore.Relational/Storage/IRelationalConnection.cs @@ -72,7 +72,7 @@ DbConnection DbConnection /// Opens the connection to the database. /// /// Indicate if the connection errors are expected and should be logged as debug message. - /// if the underlying connection was actually opened; otherwise. + /// if the underlying connection was actually opened; otherwise. bool Open(bool errorsExpected = false); /// @@ -83,7 +83,7 @@ DbConnection DbConnection /// A to observe while waiting for the task to complete. /// /// - /// A task that represents the asynchronous operation, with a value of if the connection + /// A task that represents the asynchronous operation, with a value of if the connection /// was actually opened. /// Task OpenAsync(CancellationToken cancellationToken, bool errorsExpected = false); @@ -91,14 +91,14 @@ DbConnection DbConnection /// /// Closes the connection to the database. /// - /// if the underlying connection was actually closed; otherwise. + /// if the underlying connection was actually closed; otherwise. bool Close(); /// /// Closes the connection to the database. /// /// - /// A task that represents the asynchronous operation, with a value of if the connection + /// A task that represents the asynchronous operation, with a value of if the connection /// was actually closed. /// Task CloseAsync(); diff --git a/src/EFCore.Relational/Storage/IRelationalDatabaseCreator.cs b/src/EFCore.Relational/Storage/IRelationalDatabaseCreator.cs index 4a681489e8c..d25aac90e8b 100644 --- a/src/EFCore.Relational/Storage/IRelationalDatabaseCreator.cs +++ b/src/EFCore.Relational/Storage/IRelationalDatabaseCreator.cs @@ -29,7 +29,7 @@ public interface IRelationalDatabaseCreator : IDatabaseCreator /// contains the schema for the current model. /// /// - /// if the database exists; otherwise . + /// if the database exists; otherwise . /// bool Exists(); @@ -42,7 +42,7 @@ public interface IRelationalDatabaseCreator : IDatabaseCreator /// /// /// A task that represents the asynchronous operation. The task result contains - /// if the database exists; otherwise . + /// if the database exists; otherwise . /// Task ExistsAsync(CancellationToken cancellationToken = default); diff --git a/src/EFCore.Relational/Storage/IRelationalTypeMappingSource.cs b/src/EFCore.Relational/Storage/IRelationalTypeMappingSource.cs index 0e3e6d24719..4b3599457f1 100644 --- a/src/EFCore.Relational/Storage/IRelationalTypeMappingSource.cs +++ b/src/EFCore.Relational/Storage/IRelationalTypeMappingSource.cs @@ -90,7 +90,8 @@ public interface IRelationalTypeMappingSource : ITypeMappingSource /// The database type name. /// If , then a special mapping for a key or index may be returned. /// - /// Specify for Unicode mapping, for Ansi mapping or for the default. + /// Specify for Unicode mapping, for Ansi mapping or for the + /// default. /// /// Specifies a size for the mapping, or for default. /// Specifies a row-version, or for default. diff --git a/src/EFCore.Relational/Storage/Internal/TypeMappedRelationalParameter.cs b/src/EFCore.Relational/Storage/Internal/TypeMappedRelationalParameter.cs index b6c20c70243..c7fe4d6cc33 100644 --- a/src/EFCore.Relational/Storage/Internal/TypeMappedRelationalParameter.cs +++ b/src/EFCore.Relational/Storage/Internal/TypeMappedRelationalParameter.cs @@ -70,8 +70,9 @@ public override void AddDbParameter(DbCommand command, object value) Check.NotNull(command, nameof(command)); command.Parameters - .Add(RelationalTypeMapping - .CreateParameter(command, Name, value, IsNullable)); + .Add( + RelationalTypeMapping + .CreateParameter(command, Name, value, IsNullable)); } } } diff --git a/src/EFCore.Relational/Storage/ParameterNameGenerator.cs b/src/EFCore.Relational/Storage/ParameterNameGenerator.cs index 64977294644..beb27e43f7e 100644 --- a/src/EFCore.Relational/Storage/ParameterNameGenerator.cs +++ b/src/EFCore.Relational/Storage/ParameterNameGenerator.cs @@ -1,8 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Globalization; - namespace Microsoft.EntityFrameworkCore.Storage { /// @@ -22,11 +20,13 @@ public class ParameterNameGenerator /// Generates the next unique parameter name. /// /// The generated name. - public virtual string GenerateNext() => "p" + _count++; + public virtual string GenerateNext() + => "p" + _count++; /// /// Resets the generator, meaning it can reuse previously generated names. /// - public virtual void Reset() => _count = 0; + public virtual void Reset() + => _count = 0; } } diff --git a/src/EFCore.Relational/Storage/ParameterNameGeneratorFactory.cs b/src/EFCore.Relational/Storage/ParameterNameGeneratorFactory.cs index 1a4e15489cd..b369e5021f9 100644 --- a/src/EFCore.Relational/Storage/ParameterNameGeneratorFactory.cs +++ b/src/EFCore.Relational/Storage/ParameterNameGeneratorFactory.cs @@ -36,6 +36,7 @@ public ParameterNameGeneratorFactory([NotNull] ParameterNameGeneratorDependencie /// Creates a new . /// /// The newly created generator. - public virtual ParameterNameGenerator Create() => new ParameterNameGenerator(); + public virtual ParameterNameGenerator Create() + => new ParameterNameGenerator(); } } diff --git a/src/EFCore.Relational/Storage/ReaderColumn.cs b/src/EFCore.Relational/Storage/ReaderColumn.cs index 29f96bba967..9a63087a6f8 100644 --- a/src/EFCore.Relational/Storage/ReaderColumn.cs +++ b/src/EFCore.Relational/Storage/ReaderColumn.cs @@ -39,25 +39,27 @@ protected ReaderColumn([NotNull] Type type, bool nullable, [CanBeNull] string na /// The CLR type of the column. /// public virtual Type Type { get; } + /// /// A value indicating if the column is nullable. /// public virtual bool IsNullable { get; } + /// /// The name of the column. /// public virtual string Name { get; } /// - /// Creates an instance of . + /// Creates an instance of . /// /// The type of the column. /// Whether the column can contain values. /// The column name if it is used to access the column values, otherwise. /// - /// A used to get the field value for this column. + /// A used to get the field value for this column. /// - /// An instance of . + /// An instance of . public static ReaderColumn Create([NotNull] Type type, bool nullable, [CanBeNull] string columnName, [NotNull] object readFunc) => (ReaderColumn)GetConstructor(type).Invoke(new[] { nullable, columnName, readFunc }); diff --git a/src/EFCore.Relational/Storage/RelationalCommand.cs b/src/EFCore.Relational/Storage/RelationalCommand.cs index fc32d5b7233..ff3cbed73ba 100644 --- a/src/EFCore.Relational/Storage/RelationalCommand.cs +++ b/src/EFCore.Relational/Storage/RelationalCommand.cs @@ -173,13 +173,13 @@ public virtual async Task ExecuteNonQueryAsync( var interceptionResult = logger == null ? default : await logger.CommandNonQueryExecutingAsync( - connection, - command, - context, - commandId, - connection.ConnectionId, - startTime, - cancellationToken) + connection, + command, + context, + commandId, + connection.ConnectionId, + startTime, + cancellationToken) .ConfigureAwait(false); var result = interceptionResult.HasResult @@ -189,15 +189,15 @@ public virtual async Task ExecuteNonQueryAsync( if (logger != null) { result = await logger.CommandNonQueryExecutedAsync( - connection, - command, - context, - commandId, - connection.ConnectionId, - result, - startTime, - stopwatch.Elapsed, - cancellationToken) + connection, + command, + context, + commandId, + connection.ConnectionId, + result, + startTime, + stopwatch.Elapsed, + cancellationToken) .ConfigureAwait(false); } @@ -208,16 +208,16 @@ public virtual async Task ExecuteNonQueryAsync( if (logger != null) { await logger.CommandErrorAsync( - connection, - command, - context, - DbCommandMethod.ExecuteNonQuery, - commandId, - connection.ConnectionId, - exception, - startTime, - stopwatch.Elapsed, - cancellationToken) + connection, + command, + context, + DbCommandMethod.ExecuteNonQuery, + commandId, + connection.ConnectionId, + exception, + startTime, + stopwatch.Elapsed, + cancellationToken) .ConfigureAwait(false); } @@ -319,13 +319,13 @@ public virtual async Task ExecuteScalarAsync( var interceptionResult = logger == null ? default : await logger.CommandScalarExecutingAsync( - connection, - command, - context, - commandId, - connection.ConnectionId, - startTime, - cancellationToken) + connection, + command, + context, + commandId, + connection.ConnectionId, + startTime, + cancellationToken) .ConfigureAwait(false); var result = interceptionResult.HasResult @@ -353,16 +353,16 @@ public virtual async Task ExecuteScalarAsync( if (logger != null) { await logger.CommandErrorAsync( - connection, - command, - context, - DbCommandMethod.ExecuteScalar, - commandId, - connection.ConnectionId, - exception, - startTime, - stopwatch.Elapsed, - cancellationToken) + connection, + command, + context, + DbCommandMethod.ExecuteScalar, + commandId, + connection.ConnectionId, + exception, + startTime, + stopwatch.Elapsed, + cancellationToken) .ConfigureAwait(false); } @@ -494,13 +494,13 @@ public virtual async Task ExecuteReaderAsync( var interceptionResult = logger == null ? default : await logger.CommandReaderExecutingAsync( - connection, - command, - context, - commandId, - connection.ConnectionId, - startTime, - cancellationToken) + connection, + command, + context, + commandId, + connection.ConnectionId, + startTime, + cancellationToken) .ConfigureAwait(false); var reader = interceptionResult.HasResult @@ -510,15 +510,15 @@ public virtual async Task ExecuteReaderAsync( if (logger != null) { reader = await logger.CommandReaderExecutedAsync( - connection, - command, - context, - commandId, - connection.ConnectionId, - reader, - startTime, - stopwatch.Elapsed, - cancellationToken) + connection, + command, + context, + commandId, + connection.ConnectionId, + reader, + startTime, + stopwatch.Elapsed, + cancellationToken) .ConfigureAwait(false); } @@ -544,16 +544,16 @@ public virtual async Task ExecuteReaderAsync( if (logger != null) { await logger.CommandErrorAsync( - connection, - command, - context, - DbCommandMethod.ExecuteReader, - commandId, - connection.ConnectionId, - exception, - startTime, - stopwatch.Elapsed, - cancellationToken) + connection, + command, + context, + DbCommandMethod.ExecuteReader, + commandId, + connection.ConnectionId, + exception, + startTime, + stopwatch.Elapsed, + cancellationToken) .ConfigureAwait(false); } @@ -651,10 +651,14 @@ public virtual DbCommand CreateDbCommand( /// The connection, to pass to the constructor. /// The command that was executed, to pass to the constructor. /// The underlying reader for the result set, to pass to the constructor. - /// A correlation ID that identifies the instance being used, to pass to the constructor. + /// + /// A correlation ID that identifies the instance being used, to pass to the + /// constructor. + /// /// The diagnostic source, to pass to the constructor. /// The created . - protected virtual RelationalDataReader CreateRelationalDataReader([NotNull] IRelationalConnection connection, + protected virtual RelationalDataReader CreateRelationalDataReader( + [NotNull] IRelationalConnection connection, [NotNull] DbCommand command, [NotNull] DbDataReader reader, Guid commandId, diff --git a/src/EFCore.Relational/Storage/RelationalCommandBuilder.cs b/src/EFCore.Relational/Storage/RelationalCommandBuilder.cs index 8962bdcf16e..11a10d28b18 100644 --- a/src/EFCore.Relational/Storage/RelationalCommandBuilder.cs +++ b/src/EFCore.Relational/Storage/RelationalCommandBuilder.cs @@ -48,7 +48,8 @@ public RelationalCommandBuilder( /// /// The source for s to use. /// - public virtual IRelationalTypeMappingSource TypeMappingSource => Dependencies.TypeMappingSource; + public virtual IRelationalTypeMappingSource TypeMappingSource + => Dependencies.TypeMappingSource; /// /// Creates the command. @@ -60,12 +61,14 @@ public virtual IRelationalCommand Build() /// /// Gets the command text. /// - public override string ToString() => _commandTextBuilder.ToString(); + public override string ToString() + => _commandTextBuilder.ToString(); /// /// The collection of parameters. /// - public virtual IReadOnlyList Parameters => _parameters; + public virtual IReadOnlyList Parameters + => _parameters; /// /// Adds the given parameter to this command. @@ -131,6 +134,7 @@ public virtual IRelationalCommandBuilder DecrementIndent() /// /// Gets the length of the command text. /// - public virtual int CommandTextLength => _commandTextBuilder.Length; + public virtual int CommandTextLength + => _commandTextBuilder.Length; } } diff --git a/src/EFCore.Relational/Storage/RelationalCommandBuilderExtensions.cs b/src/EFCore.Relational/Storage/RelationalCommandBuilderExtensions.cs index 5722434670b..125a6939ecc 100644 --- a/src/EFCore.Relational/Storage/RelationalCommandBuilderExtensions.cs +++ b/src/EFCore.Relational/Storage/RelationalCommandBuilderExtensions.cs @@ -329,7 +329,8 @@ public Indenter(IRelationalCommandBuilder builder) _builder.IncrementIndent(); } - public void Dispose() => _builder.DecrementIndent(); + public void Dispose() + => _builder.DecrementIndent(); } } } diff --git a/src/EFCore.Relational/Storage/RelationalConnection.cs b/src/EFCore.Relational/Storage/RelationalConnection.cs index 725c2b2ca97..dc1d7e61028 100644 --- a/src/EFCore.Relational/Storage/RelationalConnection.cs +++ b/src/EFCore.Relational/Storage/RelationalConnection.cs @@ -78,6 +78,7 @@ protected RelationalConnection([NotNull] RelationalConnectionDependencies depend { _connectionOwned = true; } + _ambientTransactions = new ConcurrentStack(); } @@ -235,7 +236,8 @@ public virtual void EnlistTransaction(Transaction transaction) /// /// Indicates whether the store connection supports ambient transactions /// - protected virtual bool SupportsAmbientTransactions => false; + protected virtual bool SupportsAmbientTransactions + => false; /// /// Gets the timeout for executing a command against the database. @@ -261,7 +263,8 @@ public virtual int? CommandTimeout /// The newly created transaction. [NotNull] // ReSharper disable once RedundantNameQualifier - public virtual IDbContextTransaction BeginTransaction() => BeginTransaction(IsolationLevel.Unspecified); + public virtual IDbContextTransaction BeginTransaction() + => BeginTransaction(IsolationLevel.Unspecified); /// /// Asynchronously begins a new transaction. @@ -333,11 +336,11 @@ public virtual async Task BeginTransactionAsync( var stopwatch = Stopwatch.StartNew(); var interceptionResult = await Dependencies.TransactionLogger.TransactionStartingAsync( - this, - isolationLevel, - transactionId, - startTime, - cancellationToken) + this, + isolationLevel, + transactionId, + startTime, + cancellationToken) .ConfigureAwait(false); var dbTransaction = interceptionResult.HasResult @@ -345,12 +348,12 @@ public virtual async Task BeginTransactionAsync( : await DbConnection.BeginTransactionAsync(isolationLevel, cancellationToken).ConfigureAwait(false); dbTransaction = await Dependencies.TransactionLogger.TransactionStartedAsync( - this, - dbTransaction, - transactionId, - startTime, - stopwatch.Elapsed, - cancellationToken) + this, + dbTransaction, + transactionId, + startTime, + stopwatch.Elapsed, + cancellationToken) .ConfigureAwait(false); return CreateRelationalTransaction(dbTransaction, transactionId, true); @@ -444,12 +447,12 @@ public virtual async Task UseTransactionAsync( await OpenAsync(cancellationToken).ConfigureAwait(false); transaction = await Dependencies.TransactionLogger.TransactionUsedAsync( - this, - // ReSharper disable once AssignNullToNotNullAttribute - transaction, - transactionId, - DateTimeOffset.UtcNow, - cancellationToken) + this, + // ReSharper disable once AssignNullToNotNullAttribute + transaction, + transactionId, + DateTimeOffset.UtcNow, + cancellationToken) .ConfigureAwait(false); CurrentTransaction = CreateRelationalTransaction(transaction, transactionId, transactionOwned: false); @@ -537,7 +540,7 @@ public virtual Task RollbackTransactionAsync(CancellationToken cancellationToken /// /// Indicates if the connection errors are expected and should be logged as debug message. /// - /// if the underlying connection was actually opened; otherwise. + /// if the underlying connection was actually opened; otherwise. public virtual bool Open(bool errorsExpected = false) { if (DbConnection.State == ConnectionState.Broken) @@ -569,7 +572,7 @@ public virtual bool Open(bool errorsExpected = false) /// A to observe while waiting for the task to complete. /// /// - /// A task that represents the asynchronous operation, with a value of if the connection + /// A task that represents the asynchronous operation, with a value of if the connection /// was actually opened. /// public virtual async Task OpenAsync(CancellationToken cancellationToken, bool errorsExpected = false) @@ -651,7 +654,7 @@ private void OpenInternal(bool errorsExpected) } /// - /// Template method that by default calls but can be overriden + /// Template method that by default calls but can be overriden /// by providers to make a different call instead. /// /// Indicates if the connection errors are expected and should be logged as debug message. @@ -680,12 +683,12 @@ await Dependencies.ConnectionLogger.ConnectionOpenedAsync(this, startTime, stopw catch (Exception e) { await Dependencies.ConnectionLogger.ConnectionErrorAsync( - this, - e, - startTime, - stopwatch.Elapsed, - errorsExpected, - cancellationToken) + this, + e, + startTime, + stopwatch.Elapsed, + errorsExpected, + cancellationToken) .ConfigureAwait(false); throw; @@ -698,7 +701,7 @@ await Dependencies.ConnectionLogger.ConnectionErrorAsync( } /// - /// Template method that by default calls but can be overriden + /// Template method that by default calls but can be overriden /// by providers to make a different call instead. /// /// Indicates if the connection errors are expected and should be logged as debug message. @@ -712,7 +715,9 @@ private void HandleAmbientTransactions() if (current == null) { - var rootTransaction = _ambientTransactions.Count > 0 && _ambientTransactions.TryPeek(out var transaction) ? transaction : null; + var rootTransaction = _ambientTransactions.Count > 0 && _ambientTransactions.TryPeek(out var transaction) + ? transaction + : null; if (rootTransaction != null) { @@ -760,7 +765,7 @@ private void HandleTransactionCompleted(object sender, TransactionEventArgs e) /// /// Closes the connection to the database. /// - /// if the underlying connection was actually closed; otherwise. + /// if the underlying connection was actually closed; otherwise. public virtual bool Close() { var wasClosed = false; @@ -806,7 +811,7 @@ public virtual bool Close() /// Closes the connection to the database. /// /// - /// A task that represents the asynchronous operation, with a value of if the connection + /// A task that represents the asynchronous operation, with a value of if the connection /// was actually closed. /// public virtual async Task CloseAsync() @@ -840,19 +845,19 @@ public virtual async Task CloseAsync() wasClosed = true; await Dependencies.ConnectionLogger.ConnectionClosedAsync( - this, - startTime, - stopwatch.Elapsed) + this, + startTime, + stopwatch.Elapsed) .ConfigureAwait(false); } catch (Exception e) { await Dependencies.ConnectionLogger.ConnectionErrorAsync( - this, - e, - startTime, - stopwatch.Elapsed, - false) + this, + e, + startTime, + stopwatch.Elapsed, + false) .ConfigureAwait(false); throw; @@ -871,9 +876,11 @@ private bool ShouldClose() && --_openedCount == 0) && _openedInternally; - void IResettableService.ResetState() => Dispose(); + void IResettableService.ResetState() + => Dispose(); - Task IResettableService.ResetStateAsync(CancellationToken cancellationToken) => DisposeAsync().AsTask(); + Task IResettableService.ResetStateAsync(CancellationToken cancellationToken) + => DisposeAsync().AsTask(); /// /// Gets a semaphore used to serialize access to this connection. diff --git a/src/EFCore.Relational/Storage/RelationalDataReader.cs b/src/EFCore.Relational/Storage/RelationalDataReader.cs index 68bb554842a..c6d16ecbecf 100644 --- a/src/EFCore.Relational/Storage/RelationalDataReader.cs +++ b/src/EFCore.Relational/Storage/RelationalDataReader.cs @@ -66,17 +66,19 @@ public RelationalDataReader( /// /// Gets the underlying reader for the result set. /// - public virtual DbDataReader DbDataReader => _reader; + public virtual DbDataReader DbDataReader + => _reader; /// /// Gets the underlying command for the result set. /// - public virtual DbCommand DbCommand => _command; + public virtual DbCommand DbCommand + => _command; /// - /// Calls on the underlying . + /// Calls on the underlying . /// - /// if there are more rows; otherwise . + /// if there are more rows; otherwise . public virtual bool Read() { _readCount++; @@ -85,10 +87,10 @@ public virtual bool Read() } /// - /// Calls on the underlying - /// . + /// Calls on the underlying + /// . /// - /// if there are more rows; otherwise . + /// if there are more rows; otherwise . public virtual Task ReadAsync(CancellationToken cancellationToken = default) { _readCount++; diff --git a/src/EFCore.Relational/Storage/RelationalDatabaseCreator.cs b/src/EFCore.Relational/Storage/RelationalDatabaseCreator.cs index 99c3180b166..5761312caed 100644 --- a/src/EFCore.Relational/Storage/RelationalDatabaseCreator.cs +++ b/src/EFCore.Relational/Storage/RelationalDatabaseCreator.cs @@ -51,7 +51,7 @@ protected RelationalDatabaseCreator([NotNull] RelationalDatabaseCreatorDependenc /// contains the schema for the current model. /// /// - /// if the database exists; otherwise . + /// if the database exists; otherwise . /// public abstract bool Exists(); @@ -64,7 +64,7 @@ protected RelationalDatabaseCreator([NotNull] RelationalDatabaseCreatorDependenc /// /// /// A task that represents the asynchronous operation. The task result contains - /// if the database exists; otherwise . + /// if the database exists; otherwise . /// public virtual Task ExistsAsync(CancellationToken cancellationToken = default) { @@ -139,7 +139,8 @@ public virtual Task CreateTablesAsync(CancellationToken cancellationToken = defa /// /// The options to use when generating commands. /// The generated commands. - protected virtual IReadOnlyList GetCreateTablesCommands(MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default) + protected virtual IReadOnlyList GetCreateTablesCommands( + MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default) => Dependencies.MigrationsSqlGenerator.Generate( Dependencies.ModelDiffer.GetDifferences(null, Dependencies.Model.GetRelationalModel()), Dependencies.Model, options); @@ -177,7 +178,7 @@ public virtual Task HasTablesAsync(CancellationToken cancellationToken = d /// /// /// - /// if the database is deleted, if it did not exist. + /// if the database is deleted, if it did not exist. /// public virtual bool EnsureDeleted() { @@ -202,8 +203,8 @@ public virtual bool EnsureDeleted() /// /// A to observe while waiting for the task to complete. /// - /// A task that represents the asynchronous save operation. The task result contains - /// if the database is deleted, if it did not exist. + /// A task that represents the asynchronous save operation. The task result contains + /// if the database is deleted, if it did not exist. /// public virtual async Task EnsureDeletedAsync(CancellationToken cancellationToken = default) { @@ -223,7 +224,7 @@ public virtual async Task EnsureDeletedAsync(CancellationToken cancellatio /// to ensure it is compatible with the model for this context. /// /// - /// if the database is created, if it already existed. + /// if the database is created, if it already existed. /// public virtual bool EnsureCreated() { @@ -253,8 +254,8 @@ public virtual bool EnsureCreated() /// /// A to observe while waiting for the task to complete. /// - /// A task that represents the asynchronous save operation. The task result contains - /// if the database is created, if it already existed. + /// A task that represents the asynchronous save operation. The task result contains + /// if the database is created, if it already existed. /// public virtual async Task EnsureCreatedAsync(CancellationToken cancellationToken = default) { diff --git a/src/EFCore.Relational/Storage/RelationalExecutionStrategyFactory.cs b/src/EFCore.Relational/Storage/RelationalExecutionStrategyFactory.cs index 37875168916..808ced14382 100644 --- a/src/EFCore.Relational/Storage/RelationalExecutionStrategyFactory.cs +++ b/src/EFCore.Relational/Storage/RelationalExecutionStrategyFactory.cs @@ -57,6 +57,7 @@ protected virtual IExecutionStrategy CreateDefaultStrategy([NotNull] ExecutionSt /// /// Creates an for the current database provider. /// - public virtual IExecutionStrategy Create() => _createExecutionStrategy(Dependencies); + public virtual IExecutionStrategy Create() + => _createExecutionStrategy(Dependencies); } } diff --git a/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs b/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs index 5cc26b94038..61a8db574c7 100644 --- a/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs +++ b/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs @@ -38,23 +38,28 @@ public RelationalSqlGenerationHelper([NotNull] RelationalSqlGenerationHelperDepe /// /// The terminator to be used for SQL statements. /// - public virtual string StatementTerminator => ";"; + public virtual string StatementTerminator + => ";"; /// /// The terminator to be used for batches of SQL statements. /// - public virtual string BatchTerminator => Environment.NewLine; + public virtual string BatchTerminator + => Environment.NewLine; /// - public virtual string StartTransactionStatement => "START TRANSACTION" + StatementTerminator; + public virtual string StartTransactionStatement + => "START TRANSACTION" + StatementTerminator; /// - public virtual string CommitTransactionStatement => "COMMIT" + StatementTerminator; + public virtual string CommitTransactionStatement + => "COMMIT" + StatementTerminator; /// /// The default single-line comment prefix. /// - public virtual string SingleLineCommentToken => "--"; + public virtual string SingleLineCommentToken + => "--"; /// /// Generates a valid parameter name for the given candidate name. diff --git a/src/EFCore.Relational/Storage/RelationalTransaction.cs b/src/EFCore.Relational/Storage/RelationalTransaction.cs index cab505aabb7..e315541a62c 100644 --- a/src/EFCore.Relational/Storage/RelationalTransaction.cs +++ b/src/EFCore.Relational/Storage/RelationalTransaction.cs @@ -172,11 +172,11 @@ public virtual async Task CommitAsync(CancellationToken cancellationToken = defa try { var interceptionResult = await Logger.TransactionCommittingAsync( - Connection, - _dbTransaction, - TransactionId, - startTime, - cancellationToken) + Connection, + _dbTransaction, + TransactionId, + startTime, + cancellationToken) .ConfigureAwait(false); if (!interceptionResult.IsSuppressed) @@ -185,25 +185,25 @@ public virtual async Task CommitAsync(CancellationToken cancellationToken = defa } await Logger.TransactionCommittedAsync( - Connection, - _dbTransaction, - TransactionId, - startTime, - stopwatch.Elapsed, - cancellationToken) + Connection, + _dbTransaction, + TransactionId, + startTime, + stopwatch.Elapsed, + cancellationToken) .ConfigureAwait(false); } catch (Exception e) { await Logger.TransactionErrorAsync( - Connection, - _dbTransaction, - TransactionId, - "Commit", - e, - startTime, - stopwatch.Elapsed, - cancellationToken) + Connection, + _dbTransaction, + TransactionId, + "Commit", + e, + startTime, + stopwatch.Elapsed, + cancellationToken) .ConfigureAwait(false); throw; @@ -221,11 +221,11 @@ public virtual async Task RollbackAsync(CancellationToken cancellationToken = de try { var interceptionResult = await Logger.TransactionRollingBackAsync( - Connection, - _dbTransaction, - TransactionId, - startTime, - cancellationToken) + Connection, + _dbTransaction, + TransactionId, + startTime, + cancellationToken) .ConfigureAwait(false); if (!interceptionResult.IsSuppressed) @@ -234,25 +234,25 @@ public virtual async Task RollbackAsync(CancellationToken cancellationToken = de } await Logger.TransactionRolledBackAsync( - Connection, - _dbTransaction, - TransactionId, - startTime, - stopwatch.Elapsed, - cancellationToken) + Connection, + _dbTransaction, + TransactionId, + startTime, + stopwatch.Elapsed, + cancellationToken) .ConfigureAwait(false); } catch (Exception e) { await Logger.TransactionErrorAsync( - Connection, - _dbTransaction, - TransactionId, - "Rollback", - e, - startTime, - stopwatch.Elapsed, - cancellationToken) + Connection, + _dbTransaction, + TransactionId, + "Rollback", + e, + startTime, + stopwatch.Elapsed, + cancellationToken) .ConfigureAwait(false); throw; @@ -356,7 +356,8 @@ await Logger.TransactionErrorAsync( /// /// The name of the savepoint to be created. /// An SQL string to create the savepoint. - protected virtual string GetCreateSavepointSql([NotNull] string name) => "SAVEPOINT " + name; + protected virtual string GetCreateSavepointSql([NotNull] string name) + => "SAVEPOINT " + name; /// public virtual void RollbackToSavepoint(string name) @@ -453,7 +454,8 @@ await Logger.TransactionErrorAsync( /// /// The name of the savepoint to be created. /// An SQL string to create the savepoint. - protected virtual string GetRollbackToSavepointSql([NotNull] string name) => "ROLLBACK TO " + name; + protected virtual string GetRollbackToSavepointSql([NotNull] string name) + => "ROLLBACK TO " + name; /// public virtual void ReleaseSavepoint(string name) @@ -550,16 +552,18 @@ await Logger.TransactionErrorAsync( /// SQL statement which releases a savepoint with the given name. /// /// - /// If savepoint release isn't supported, and should + /// If savepoint release isn't supported, and should /// be overridden to do nothing. /// /// /// The name of the savepoint to be created. /// An SQL string to create the savepoint. - protected virtual string GetReleaseSavepointSql([NotNull] string name) => "RELEASE SAVEPOINT " + name; + protected virtual string GetReleaseSavepointSql([NotNull] string name) + => "RELEASE SAVEPOINT " + name; /// - public virtual bool SupportsSavepoints => true; + public virtual bool SupportsSavepoints + => true; /// public virtual void Dispose() @@ -643,6 +647,7 @@ protected virtual async Task ClearTransactionAsync(CancellationToken cancellatio } } - DbTransaction IInfrastructure.Instance => _dbTransaction; + DbTransaction IInfrastructure.Instance + => _dbTransaction; } } diff --git a/src/EFCore.Relational/Storage/RelationalTypeMapping.cs b/src/EFCore.Relational/Storage/RelationalTypeMapping.cs index c60187bd18e..8a28b7820a3 100644 --- a/src/EFCore.Relational/Storage/RelationalTypeMapping.cs +++ b/src/EFCore.Relational/Storage/RelationalTypeMapping.cs @@ -362,7 +362,8 @@ protected RelationalTypeMapping( int? scale = null) : this( new RelationalTypeMappingParameters( - new CoreTypeMappingParameters(clrType), storeType, StoreTypePostfix.None, dbType, unicode, size, fixedLength, precision, scale)) + new CoreTypeMappingParameters(clrType), storeType, StoreTypePostfix.None, dbType, unicode, size, fixedLength, precision, + scale)) { } @@ -416,7 +417,8 @@ public virtual RelationalTypeMapping Clone(in RelationalTypeMappingInfo mappingI /// /// Gets the name of the database type. /// - public virtual StoreTypePostfix StoreTypePostfix => Parameters.StoreTypePostfix; + public virtual StoreTypePostfix StoreTypePostfix + => Parameters.StoreTypePostfix; /// /// Gets the name of the database type. @@ -431,32 +433,38 @@ public virtual RelationalTypeMapping Clone(in RelationalTypeMappingInfo mappingI /// /// Gets the to be used. /// - public virtual DbType? DbType => Parameters.DbType; + public virtual DbType? DbType + => Parameters.DbType; /// /// Gets a value indicating whether the type should handle Unicode data or not. /// - public virtual bool IsUnicode => Parameters.Unicode; + public virtual bool IsUnicode + => Parameters.Unicode; /// /// Gets the size of data the property is configured to store, or null if no size is configured. /// - public virtual int? Size => Parameters.Size; + public virtual int? Size + => Parameters.Size; - /// + /// /// Gets the precision of data the property is configured to store, or null if no precision is configured. /// - public virtual int? Precision => Parameters.Precision; + public virtual int? Precision + => Parameters.Precision; - /// + /// /// Gets the scale of data the property is configured to store, or null if no scale is configured. /// - public virtual int? Scale => Parameters.Scale; + public virtual int? Scale + => Parameters.Scale; /// /// Gets a value indicating whether the type is constrained to fixed-length data. /// - public virtual bool IsFixedLength => Parameters.FixedLength; + public virtual bool IsFixedLength + => Parameters.FixedLength; /// /// Gets the string format to be used to generate SQL literals of this type. @@ -514,8 +522,8 @@ public virtual DbParameter CreateParameter( // This allows us to use converter on enum value or print enum value directly if supported by provider private object ConvertUnderlyingEnumValueToEnum(object value) => value?.GetType().IsInteger() == true && ClrType.UnwrapNullableType().IsEnum - ? Enum.ToObject(ClrType.UnwrapNullableType(), value) - : value; + ? Enum.ToObject(ClrType.UnwrapNullableType(), value) + : value; /// /// Configures type information of a . diff --git a/src/EFCore.Relational/Storage/RelationalTypeMappingInfo.cs b/src/EFCore.Relational/Storage/RelationalTypeMappingInfo.cs index 5564ef73596..9cbc92d253f 100644 --- a/src/EFCore.Relational/Storage/RelationalTypeMappingInfo.cs +++ b/src/EFCore.Relational/Storage/RelationalTypeMappingInfo.cs @@ -192,17 +192,20 @@ public RelationalTypeMappingInfo( /// /// Indicates the store-size to use for the mapping, or null if none. /// - public int? Size => _coreTypeMappingInfo.Size; + public int? Size + => _coreTypeMappingInfo.Size; /// /// The suggested precision of the mapped data type. /// - public int? Precision => _coreTypeMappingInfo.Precision; + public int? Precision + => _coreTypeMappingInfo.Precision; /// /// The suggested scale of the mapped data type. /// - public int? Scale => _coreTypeMappingInfo.Scale; + public int? Scale + => _coreTypeMappingInfo.Scale; /// /// Whether or not the mapped data type is fixed length. @@ -212,22 +215,26 @@ public RelationalTypeMappingInfo( /// /// Indicates whether or not the mapping is part of a key or index. /// - public bool IsKeyOrIndex => _coreTypeMappingInfo.IsKeyOrIndex; + public bool IsKeyOrIndex + => _coreTypeMappingInfo.IsKeyOrIndex; /// /// Indicates whether or not the mapping supports Unicode, or null if not defined. /// - public bool? IsUnicode => _coreTypeMappingInfo.IsUnicode; + public bool? IsUnicode + => _coreTypeMappingInfo.IsUnicode; /// /// Indicates whether or not the mapping will be used for a row version, or null if not defined. /// - public bool? IsRowVersion => _coreTypeMappingInfo.IsRowVersion; + public bool? IsRowVersion + => _coreTypeMappingInfo.IsRowVersion; /// /// The CLR type in the model. /// - public Type ClrType => _coreTypeMappingInfo.ClrType; + public Type ClrType + => _coreTypeMappingInfo.ClrType; /// /// Returns a new with the given converter applied. @@ -261,6 +268,7 @@ public override bool Equals(object obj) /// Returns a hash code for this object. /// /// The hash code. - public override int GetHashCode() => HashCode.Combine(_coreTypeMappingInfo, StoreTypeName, IsFixedLength); + public override int GetHashCode() + => HashCode.Combine(_coreTypeMappingInfo, StoreTypeName, IsFixedLength); } } diff --git a/src/EFCore.Relational/Storage/TimeSpanTypeMapping.cs b/src/EFCore.Relational/Storage/TimeSpanTypeMapping.cs index f357815a60e..1ab2c569c8b 100644 --- a/src/EFCore.Relational/Storage/TimeSpanTypeMapping.cs +++ b/src/EFCore.Relational/Storage/TimeSpanTypeMapping.cs @@ -50,6 +50,7 @@ protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters p /// /// Gets the string format to be used to generate SQL literals of this type. /// - protected override string SqlLiteralFormatString => "'{0}'"; + protected override string SqlLiteralFormatString + => "'{0}'"; } } diff --git a/src/EFCore.Relational/Storage/TypedRelationalValueBufferFactoryFactory.cs b/src/EFCore.Relational/Storage/TypedRelationalValueBufferFactoryFactory.cs index e01255310b6..6014c101764 100644 --- a/src/EFCore.Relational/Storage/TypedRelationalValueBufferFactoryFactory.cs +++ b/src/EFCore.Relational/Storage/TypedRelationalValueBufferFactoryFactory.cs @@ -151,7 +151,9 @@ private static Func CreateArrayInitializer(CacheKey cach [MethodImpl(MethodImplOptions.AggressiveInlining)] private static TValue ThrowReadValueException( - Exception exception, object value, IPropertyBase property = null) + Exception exception, + object value, + IPropertyBase property = null) { var expectedType = typeof(TValue); var actualType = value?.GetType(); diff --git a/src/EFCore.Relational/Update/AffectedCountModificationCommandBatch.cs b/src/EFCore.Relational/Update/AffectedCountModificationCommandBatch.cs index a45fe0ffdd8..b4b25304be5 100644 --- a/src/EFCore.Relational/Update/AffectedCountModificationCommandBatch.cs +++ b/src/EFCore.Relational/Update/AffectedCountModificationCommandBatch.cs @@ -209,7 +209,9 @@ protected virtual int ConsumeResultSetWithPropagation(int commandIndex, [NotNull /// The task contains the ordinal of the next command that must be consumed. /// protected virtual async Task ConsumeResultSetWithPropagationAsync( - int commandIndex, [NotNull] RelationalDataReader reader, CancellationToken cancellationToken) + int commandIndex, + [NotNull] RelationalDataReader reader, + CancellationToken cancellationToken) { var rowsAffected = 0; do @@ -286,7 +288,9 @@ protected virtual int ConsumeResultSetWithoutPropagation(int commandIndex, [NotN /// The task contains the ordinal of the next command that must be consumed. /// protected virtual async Task ConsumeResultSetWithoutPropagationAsync( - int commandIndex, [NotNull] RelationalDataReader reader, CancellationToken cancellationToken) + int commandIndex, + [NotNull] RelationalDataReader reader, + CancellationToken cancellationToken) { var expectedRowsAffected = 1; while (++commandIndex < CommandResultSet.Count diff --git a/src/EFCore.Relational/Update/ColumnModification.cs b/src/EFCore.Relational/Update/ColumnModification.cs index 74fed80aa5d..c30214fe08d 100644 --- a/src/EFCore.Relational/Update/ColumnModification.cs +++ b/src/EFCore.Relational/Update/ColumnModification.cs @@ -57,7 +57,8 @@ public ColumnModification( bool isKey, bool isCondition, bool sensitiveLoggingEnabled) - : this(Check.NotNull(column, nameof(column)).Name, + : this( + Check.NotNull(column, nameof(column)).Name, originalValue: null, value: null, property: property, @@ -102,16 +103,17 @@ public ColumnModification( bool isCondition, bool isConcurrencyToken, bool sensitiveLoggingEnabled) - : this(entry, - property, - Check.NotNull(property, nameof(property)).GetTableColumnMappings().First().Column, - generateParameterName, - Check.NotNull(property, nameof(property)).GetTableColumnMappings().First().TypeMapping, - isRead: isRead, - isWrite: isWrite, - isKey: isKey, - isCondition: isCondition, - sensitiveLoggingEnabled: sensitiveLoggingEnabled) + : this( + entry, + property, + Check.NotNull(property, nameof(property)).GetTableColumnMappings().First().Column, + generateParameterName, + Check.NotNull(property, nameof(property)).GetTableColumnMappings().First().TypeMapping, + isRead: isRead, + isWrite: isWrite, + isKey: isKey, + isCondition: isCondition, + sensitiveLoggingEnabled: sensitiveLoggingEnabled) { } @@ -223,7 +225,8 @@ public ColumnModification( bool isKey, bool isCondition, bool sensitiveLoggingEnabled) - : this(columnName, + : this( + columnName, originalValue: originalValue, value: value, property: property, @@ -285,12 +288,14 @@ public ColumnModification( /// /// Indicates whether the original value of the property must be passed as a parameter to the SQL /// - public virtual bool UseOriginalValueParameter => _useParameters && IsCondition; + public virtual bool UseOriginalValueParameter + => _useParameters && IsCondition; /// /// Indicates whether the current value of the property must be passed as a parameter to the SQL /// - public virtual bool UseCurrentValueParameter => _useParameters && IsWrite; + public virtual bool UseCurrentValueParameter + => _useParameters && IsWrite; /// /// The parameter name to use for the current value parameter (), if needed. @@ -317,22 +322,24 @@ public virtual string OriginalParameterName /// /// The original value of the property mapped to this column. /// - public virtual object OriginalValue => Entry == null - ? _originalValue - : Entry.SharedIdentityEntry == null - ? Entry.GetOriginalValue(Property) - : Entry.SharedIdentityEntry.GetOriginalValue(Property); + public virtual object OriginalValue + => Entry == null + ? _originalValue + : Entry.SharedIdentityEntry == null + ? Entry.GetOriginalValue(Property) + : Entry.SharedIdentityEntry.GetOriginalValue(Property); /// /// Gets or sets the current value of the property mapped to this column. /// public virtual object Value { - get => Entry == null - ? _value - : Entry.EntityState == EntityState.Deleted - ? null - : Entry.GetCurrentValue(Property); + get + => Entry == null + ? _value + : Entry.EntityState == EntityState.Deleted + ? null + : Entry.GetCurrentValue(Property); [param: CanBeNull] set { diff --git a/src/EFCore.Relational/Update/IUpdateSqlGenerator.cs b/src/EFCore.Relational/Update/IUpdateSqlGenerator.cs index 744f0487c28..bee454b3711 100644 --- a/src/EFCore.Relational/Update/IUpdateSqlGenerator.cs +++ b/src/EFCore.Relational/Update/IUpdateSqlGenerator.cs @@ -39,7 +39,9 @@ public interface IUpdateSqlGenerator /// The name of the sequence. /// The schema that contains the sequence, or to use the default schema. void AppendNextSequenceValueOperation( - [NotNull] StringBuilder commandStringBuilder, [NotNull] string name, [CanBeNull] string schema); + [NotNull] StringBuilder commandStringBuilder, + [NotNull] string name, + [CanBeNull] string schema); /// /// Appends a SQL fragment for the start of a batch to @@ -56,7 +58,9 @@ void AppendNextSequenceValueOperation( /// The ordinal of this command in the batch. /// The for the command. ResultSetMapping AppendDeleteOperation( - [NotNull] StringBuilder commandStringBuilder, [NotNull] ModificationCommand command, int commandPosition); + [NotNull] StringBuilder commandStringBuilder, + [NotNull] ModificationCommand command, + int commandPosition); /// /// Appends a SQL command for inserting a row to the commands being built. @@ -66,7 +70,9 @@ ResultSetMapping AppendDeleteOperation( /// The ordinal of this command in the batch. /// The for the command. ResultSetMapping AppendInsertOperation( - [NotNull] StringBuilder commandStringBuilder, [NotNull] ModificationCommand command, int commandPosition); + [NotNull] StringBuilder commandStringBuilder, + [NotNull] ModificationCommand command, + int commandPosition); /// /// Appends a SQL command for updating a row to the commands being built. @@ -76,6 +82,8 @@ ResultSetMapping AppendInsertOperation( /// The ordinal of this command in the batch. /// The for the command. ResultSetMapping AppendUpdateOperation( - [NotNull] StringBuilder commandStringBuilder, [NotNull] ModificationCommand command, int commandPosition); + [NotNull] StringBuilder commandStringBuilder, + [NotNull] ModificationCommand command, + int commandPosition); } } diff --git a/src/EFCore.Relational/Update/Internal/CommandBatchPreparer.cs b/src/EFCore.Relational/Update/Internal/CommandBatchPreparer.cs index 8a3c5abcbf2..a87cd6b1a39 100644 --- a/src/EFCore.Relational/Update/Internal/CommandBatchPreparer.cs +++ b/src/EFCore.Relational/Update/Internal/CommandBatchPreparer.cs @@ -144,7 +144,8 @@ public virtual IEnumerable BatchCommands( } private ModificationCommandBatch StartNewBatch( - ParameterNameGenerator parameterNameGenerator, ModificationCommand modificationCommand) + ParameterNameGenerator parameterNameGenerator, + ModificationCommand modificationCommand) { parameterNameGenerator.Reset(); var batch = _modificationCommandBatchFactory.Create(); @@ -197,7 +198,8 @@ protected virtual IEnumerable CreateModificationCommands( sharedTablesCommandsMap.Add(tableKey, sharedCommandsMap); } - command = sharedCommandsMap.GetOrAddValue(entry, + command = sharedCommandsMap.GetOrAddValue( + entry, (n, s, c) => new ModificationCommand(n, s, generateParameterName, _sensitiveLoggingEnabled, c)); isMainEntry = sharedCommandsMap.IsMainEntry(entry); } diff --git a/src/EFCore.Relational/Update/Internal/SharedTableEntryMap.cs b/src/EFCore.Relational/Update/Internal/SharedTableEntryMap.cs index 200a7882a4e..ea0d658dd1a 100644 --- a/src/EFCore.Relational/Update/Internal/SharedTableEntryMap.cs +++ b/src/EFCore.Relational/Update/Internal/SharedTableEntryMap.cs @@ -43,7 +43,8 @@ public SharedTableEntryMap( /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual IEnumerable Values => _entryValueMap.Values; + public virtual IEnumerable Values + => _entryValueMap.Values; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -71,7 +72,8 @@ public virtual TValue GetOrAddValue([NotNull] IUpdateEntry entry, [NotNull] Shar /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public virtual bool IsMainEntry([NotNull] IUpdateEntry entry) => !_table.GetRowInternalForeignKeys(entry.EntityType).Any(); + public virtual bool IsMainEntry([NotNull] IUpdateEntry entry) + => !_table.GetRowInternalForeignKeys(entry.EntityType).Any(); private IUpdateEntry GetMainEntry(IUpdateEntry entry) { diff --git a/src/EFCore.Relational/Update/ModificationCommand.cs b/src/EFCore.Relational/Update/ModificationCommand.cs index 4d852d054dc..8384290de5d 100644 --- a/src/EFCore.Relational/Update/ModificationCommand.cs +++ b/src/EFCore.Relational/Update/ModificationCommand.cs @@ -94,7 +94,8 @@ public ModificationCommand( /// The s that represent the entities that are mapped to the row /// to update. /// - public virtual IReadOnlyList Entries => _entries; + public virtual IReadOnlyList Entries + => _entries; /// /// The that indicates whether the row will be @@ -117,8 +118,8 @@ public virtual EntityState EntityState return mainEntry.SharedIdentityEntry.EntityType == mainEntry.EntityType || mainEntry.SharedIdentityEntry.EntityType.GetTableMappings() .Any(m => m.Table.Name == TableName && m.Table.Schema == Schema) - ? EntityState.Modified - : mainEntry.EntityState; + ? EntityState.Modified + : mainEntry.EntityState; } return EntityState.Modified; @@ -144,7 +145,7 @@ public virtual void AssertColumnsNotInitialized() { if (_columnModifications != null) { - throw new Exception($"_columnModifications have been initialized prematurely"); + throw new Exception("_columnModifications have been initialized prematurely"); } } @@ -380,7 +381,10 @@ private ITableMappingBase GetTableMapping(IEntityType entityType) } private void InitializeSharedColumns( - IUpdateEntry entry, ITableMappingBase tableMapping, bool updating, Dictionary columnMap) + IUpdateEntry entry, + ITableMappingBase tableMapping, + bool updating, + Dictionary columnMap) { foreach (var columnMapping in tableMapping.ColumnMappings) { diff --git a/src/EFCore.Relational/Update/ReaderModificationCommandBatch.cs b/src/EFCore.Relational/Update/ReaderModificationCommandBatch.cs index 0a11a4d78a9..d14a5331f4d 100644 --- a/src/EFCore.Relational/Update/ReaderModificationCommandBatch.cs +++ b/src/EFCore.Relational/Update/ReaderModificationCommandBatch.cs @@ -46,7 +46,8 @@ protected ReaderModificationCommandBatch([NotNull] ModificationCommandBatchFacto /// /// The update SQL generator. /// - protected virtual IUpdateSqlGenerator UpdateSqlGenerator => Dependencies.UpdateSqlGenerator; + protected virtual IUpdateSqlGenerator UpdateSqlGenerator + => Dependencies.UpdateSqlGenerator; /// /// Gets or sets the cached command text for the commands in the batch. @@ -61,7 +62,8 @@ protected ReaderModificationCommandBatch([NotNull] ModificationCommandBatchFacto /// /// The list of conceptual insert/update/delete s in the batch. /// - public override IReadOnlyList ModificationCommands => _modificationCommands; + public override IReadOnlyList ModificationCommands + => _modificationCommands; /// /// The s for each command in . diff --git a/src/EFCore.Relational/Update/UpdateSqlGenerator.cs b/src/EFCore.Relational/Update/UpdateSqlGenerator.cs index faa985bf751..8f5ab6454c3 100644 --- a/src/EFCore.Relational/Update/UpdateSqlGenerator.cs +++ b/src/EFCore.Relational/Update/UpdateSqlGenerator.cs @@ -48,7 +48,8 @@ protected UpdateSqlGenerator([NotNull] UpdateSqlGeneratorDependencies dependenci /// /// Helpers for generating update SQL. /// - protected virtual ISqlGenerationHelper SqlGenerationHelper => Dependencies.SqlGenerationHelper; + protected virtual ISqlGenerationHelper SqlGenerationHelper + => Dependencies.SqlGenerationHelper; /// /// Appends a SQL command for inserting a row to the commands being built. @@ -58,7 +59,9 @@ protected UpdateSqlGenerator([NotNull] UpdateSqlGeneratorDependencies dependenci /// The ordinal of this command in the batch. /// The for the command. public virtual ResultSetMapping AppendInsertOperation( - StringBuilder commandStringBuilder, ModificationCommand command, int commandPosition) + StringBuilder commandStringBuilder, + ModificationCommand command, + int commandPosition) { Check.NotNull(commandStringBuilder, nameof(commandStringBuilder)); Check.NotNull(command, nameof(command)); @@ -90,7 +93,9 @@ public virtual ResultSetMapping AppendInsertOperation( /// The ordinal of this command in the batch. /// The for the command. public virtual ResultSetMapping AppendUpdateOperation( - StringBuilder commandStringBuilder, ModificationCommand command, int commandPosition) + StringBuilder commandStringBuilder, + ModificationCommand command, + int commandPosition) { Check.NotNull(commandStringBuilder, nameof(commandStringBuilder)); Check.NotNull(command, nameof(command)); @@ -123,7 +128,9 @@ public virtual ResultSetMapping AppendUpdateOperation( /// The ordinal of this command in the batch. /// The for the command. public virtual ResultSetMapping AppendDeleteOperation( - StringBuilder commandStringBuilder, ModificationCommand command, int commandPosition) + StringBuilder commandStringBuilder, + ModificationCommand command, + int commandPosition) { Check.NotNull(commandStringBuilder, nameof(commandStringBuilder)); Check.NotNull(command, nameof(command)); @@ -607,7 +614,7 @@ private void AppendSqlLiteral(StringBuilder commandStringBuilder, ColumnModifica { if (modification.TypeMapping == null) { - var columnName = modification.ColumnName; + var columnName = modification.ColumnName; if (tableName != null) { columnName = tableName + "." + columnName; @@ -618,7 +625,8 @@ private void AppendSqlLiteral(StringBuilder commandStringBuilder, ColumnModifica } } - throw new InvalidOperationException(RelationalStrings.UnsupportedDataOperationStoreType(modification.ColumnType, columnName)); + throw new InvalidOperationException( + RelationalStrings.UnsupportedDataOperationStoreType(modification.ColumnType, columnName)); } commandStringBuilder.Append(modification.TypeMapping.GenerateProviderValueSqlLiteral(modification.Value)); diff --git a/src/EFCore.Relational/ValueGeneration/Internal/TemporaryBinaryValueGenerator.cs b/src/EFCore.Relational/ValueGeneration/Internal/TemporaryBinaryValueGenerator.cs index ac7614041fc..f59cc76bc7d 100644 --- a/src/EFCore.Relational/ValueGeneration/Internal/TemporaryBinaryValueGenerator.cs +++ b/src/EFCore.Relational/ValueGeneration/Internal/TemporaryBinaryValueGenerator.cs @@ -20,7 +20,8 @@ public class TemporaryBinaryValueGenerator : ValueGenerator /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override bool GeneratesTemporaryValues => true; + public override bool GeneratesTemporaryValues + => true; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -28,6 +29,7 @@ public class TemporaryBinaryValueGenerator : ValueGenerator /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override byte[] Next(EntityEntry entry) => Guid.NewGuid().ToByteArray(); + public override byte[] Next(EntityEntry entry) + => Guid.NewGuid().ToByteArray(); } } diff --git a/src/EFCore.Relational/ValueGeneration/Internal/TemporaryDateTimeOffsetValueGenerator.cs b/src/EFCore.Relational/ValueGeneration/Internal/TemporaryDateTimeOffsetValueGenerator.cs index 322e25473a3..d9f93e40030 100644 --- a/src/EFCore.Relational/ValueGeneration/Internal/TemporaryDateTimeOffsetValueGenerator.cs +++ b/src/EFCore.Relational/ValueGeneration/Internal/TemporaryDateTimeOffsetValueGenerator.cs @@ -32,6 +32,7 @@ public override DateTimeOffset Next(EntityEntry entry) /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override bool GeneratesTemporaryValues => true; + public override bool GeneratesTemporaryValues + => true; } } diff --git a/src/EFCore.Relational/ValueGeneration/Internal/TemporaryDateTimeValueGenerator.cs b/src/EFCore.Relational/ValueGeneration/Internal/TemporaryDateTimeValueGenerator.cs index 8695600bb93..47ea678e9a5 100644 --- a/src/EFCore.Relational/ValueGeneration/Internal/TemporaryDateTimeValueGenerator.cs +++ b/src/EFCore.Relational/ValueGeneration/Internal/TemporaryDateTimeValueGenerator.cs @@ -23,7 +23,8 @@ public class TemporaryDateTimeValueGenerator : ValueGenerator /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override DateTime Next(EntityEntry entry) => new DateTime(Interlocked.Increment(ref _current)); + public override DateTime Next(EntityEntry entry) + => new DateTime(Interlocked.Increment(ref _current)); /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -31,6 +32,7 @@ public class TemporaryDateTimeValueGenerator : ValueGenerator /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override bool GeneratesTemporaryValues => true; + public override bool GeneratesTemporaryValues + => true; } } diff --git a/src/EFCore.Relational/ValueGeneration/Internal/TemporaryStringValueGenerator.cs b/src/EFCore.Relational/ValueGeneration/Internal/TemporaryStringValueGenerator.cs index 5a1e936c754..50f061c6e8f 100644 --- a/src/EFCore.Relational/ValueGeneration/Internal/TemporaryStringValueGenerator.cs +++ b/src/EFCore.Relational/ValueGeneration/Internal/TemporaryStringValueGenerator.cs @@ -20,7 +20,8 @@ public class TemporaryStringValueGenerator : ValueGenerator /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override bool GeneratesTemporaryValues => true; + public override bool GeneratesTemporaryValues + => true; /// /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to @@ -28,6 +29,7 @@ public class TemporaryStringValueGenerator : ValueGenerator /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// - public override string Next(EntityEntry entry) => Guid.NewGuid().ToString(); + public override string Next(EntityEntry entry) + => Guid.NewGuid().ToString(); } }