diff --git a/src/Directory.Build.props b/src/Directory.Build.props
index e65be73b154..adcdae77f74 100644
--- a/src/Directory.Build.props
+++ b/src/Directory.Build.props
@@ -13,4 +13,4 @@
-
+
\ No newline at end of file
diff --git a/src/EFCore.Abstractions/ChangeTracking/Internal/ObservableBackedBindingList.cs b/src/EFCore.Abstractions/ChangeTracking/Internal/ObservableBackedBindingList.cs
index d7ea5c99571..148be762cac 100644
--- a/src/EFCore.Abstractions/ChangeTracking/Internal/ObservableBackedBindingList.cs
+++ b/src/EFCore.Abstractions/ChangeTracking/Internal/ObservableBackedBindingList.cs
@@ -14,8 +14,8 @@ namespace Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
/// doing so can result in application failures when updating to a new Entity Framework Core release.
///
[RequiresUnreferencedCode(
- "BindingList raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code.")]
-[RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type")]
+ "BindingList raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code."),
+ RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type")]
public class ObservableBackedBindingList<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T> : SortableBindingList
{
private bool _addingNewInstance;
diff --git a/src/EFCore.Abstractions/ChangeTracking/Internal/SortableBindingList.cs b/src/EFCore.Abstractions/ChangeTracking/Internal/SortableBindingList.cs
index 1af38c18074..1df4cc6908e 100644
--- a/src/EFCore.Abstractions/ChangeTracking/Internal/SortableBindingList.cs
+++ b/src/EFCore.Abstractions/ChangeTracking/Internal/SortableBindingList.cs
@@ -13,8 +13,8 @@ namespace Microsoft.EntityFrameworkCore.ChangeTracking.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.
///
-[RequiresUnreferencedCode("Raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code.")]
-[RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type")]
+[RequiresUnreferencedCode("Raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code."),
+ RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type")]
public class SortableBindingList<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T> : BindingList
{
private bool _isSorted;
@@ -39,18 +39,16 @@ public SortableBindingList(List list)
/// 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.
///
- [RequiresUnreferencedCode("Requires accessing property 'Default' on the property descriptor's type")]
- [RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type")]
- [UnconditionalSuppressMessage(
- "ReflectionAnalysis",
- "IL2046",
- Justification =
- "This method is an override, and the base method isn't annotated with RequiresUnreferencedCode. "
- + "The entire type is marked with RequiresUnreferencedCode.")]
- [SuppressMessage(
- "AOT", "IL3051:'RequiresDynamicCodeAttribute' annotations must match across all interface implementations or overrides.",
- Justification = "This method is an override, and the base method isn't annotated with RequiresDynamicCode. "
- + "The entire type is marked with RequiresDynamicCode.")]
+ [RequiresUnreferencedCode("Requires accessing property 'Default' on the property descriptor's type"),
+ RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type"), UnconditionalSuppressMessage(
+ "ReflectionAnalysis",
+ "IL2046",
+ Justification =
+ "This method is an override, and the base method isn't annotated with RequiresUnreferencedCode. "
+ + "The entire type is marked with RequiresUnreferencedCode."), SuppressMessage(
+ "AOT", "IL3051:'RequiresDynamicCodeAttribute' annotations must match across all interface implementations or overrides.",
+ Justification = "This method is an override, and the base method isn't annotated with RequiresDynamicCode. "
+ + "The entire type is marked with RequiresDynamicCode.")]
protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
if (PropertyComparer.CanSort(prop.PropertyType))
@@ -117,8 +115,8 @@ private sealed class PropertyComparer : Comparer
private readonly ListSortDirection _direction;
private readonly PropertyDescriptor _prop;
- [RequiresUnreferencedCode("Requires accessing property 'Default' on the property descriptor's type")]
- [RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type")]
+ [RequiresUnreferencedCode("Requires accessing property 'Default' on the property descriptor's type"),
+ RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type")]
public PropertyComparer(PropertyDescriptor prop, ListSortDirection direction)
{
if (!prop.ComponentType.IsAssignableFrom(typeof(T)))
diff --git a/src/EFCore.Abstractions/ChangeTracking/ObservableCollectionListSource.cs b/src/EFCore.Abstractions/ChangeTracking/ObservableCollectionListSource.cs
index 5b4ace5447f..029a97ab26e 100644
--- a/src/EFCore.Abstractions/ChangeTracking/ObservableCollectionListSource.cs
+++ b/src/EFCore.Abstractions/ChangeTracking/ObservableCollectionListSource.cs
@@ -75,18 +75,16 @@ bool IListSource.ContainsListCollection
/// An in sync with the ObservableCollection.
///
[RequiresUnreferencedCode(
- "BindingList raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code.")]
- [RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type")]
- [UnconditionalSuppressMessage(
- "ReflectionAnalysis",
- "IL2046",
- Justification =
- "This method is an interface implementation, and the interface method isn't annotated with RequiresUnreferencedCode. "
- + "The entire type is marked with RequiresUnreferencedCode.")]
- [SuppressMessage(
- "AOT", "IL3051:'RequiresDynamicCodeAttribute' annotations must match across all interface implementations or overrides.",
- Justification = "This method is an override, and the base method isn't annotated with RequiresDynamicCode. "
- + "The entire type is marked with RequiresDynamicCode.")]
+ "BindingList raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code."),
+ RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type"), UnconditionalSuppressMessage(
+ "ReflectionAnalysis",
+ "IL2046",
+ Justification =
+ "This method is an interface implementation, and the interface method isn't annotated with RequiresUnreferencedCode. "
+ + "The entire type is marked with RequiresUnreferencedCode."), SuppressMessage(
+ "AOT", "IL3051:'RequiresDynamicCodeAttribute' annotations must match across all interface implementations or overrides.",
+ Justification = "This method is an override, and the base method isn't annotated with RequiresDynamicCode. "
+ + "The entire type is marked with RequiresDynamicCode.")]
IList IListSource.GetList()
=> _bindingList ??= this.ToBindingList();
}
diff --git a/src/EFCore.Abstractions/EntityTypeConfigurationAttribute.cs b/src/EFCore.Abstractions/EntityTypeConfigurationAttribute.cs
index 9f59eccfb1d..9dde465b7b4 100644
--- a/src/EFCore.Abstractions/EntityTypeConfigurationAttribute.cs
+++ b/src/EFCore.Abstractions/EntityTypeConfigurationAttribute.cs
@@ -19,7 +19,10 @@ public class EntityTypeConfigurationAttribute : Attribute
/// Initializes a new instance of the class.
///
/// The IEntityTypeConfiguration<> type to use.
- public EntityTypeConfigurationAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.Interfaces)] Type entityConfigurationType)
+ public EntityTypeConfigurationAttribute(
+ [DynamicallyAccessedMembers(
+ DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.Interfaces)]
+ Type entityConfigurationType)
{
Check.NotNull(entityConfigurationType);
diff --git a/src/EFCore.Abstractions/ObservableCollectionExtensions.cs b/src/EFCore.Abstractions/ObservableCollectionExtensions.cs
index 211eb90c443..d40f5a39dc3 100644
--- a/src/EFCore.Abstractions/ObservableCollectionExtensions.cs
+++ b/src/EFCore.Abstractions/ObservableCollectionExtensions.cs
@@ -25,8 +25,8 @@ public static class ObservableCollectionExtensions
/// The collection that the binding list will stay in sync with.
/// The binding list.
[RequiresUnreferencedCode(
- "BindingList raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code.")]
- [RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type")]
+ "BindingList raises ListChanged events with PropertyDescriptors. PropertyDescriptors require unreferenced code."),
+ RequiresDynamicCode("Requires calling MakeGenericType on the property descriptor's type")]
public static BindingList ToBindingList(this ObservableCollection source)
where T : class
=> new ObservableBackedBindingList(source);
diff --git a/src/EFCore.Analyzers/EFCore.Analyzers.nuspec b/src/EFCore.Analyzers/EFCore.Analyzers.nuspec
index 17bf4bb98f2..0a1bd7e678d 100644
--- a/src/EFCore.Analyzers/EFCore.Analyzers.nuspec
+++ b/src/EFCore.Analyzers/EFCore.Analyzers.nuspec
@@ -1,4 +1,5 @@
+
$CommonMetadataElements$
@@ -14,4 +15,4 @@
-
+
\ No newline at end of file
diff --git a/src/EFCore.Analyzers/InternalUsageDiagnosticAnalyzer.cs b/src/EFCore.Analyzers/InternalUsageDiagnosticAnalyzer.cs
index 2f6579ef1ef..b2b194f3834 100644
--- a/src/EFCore.Analyzers/InternalUsageDiagnosticAnalyzer.cs
+++ b/src/EFCore.Analyzers/InternalUsageDiagnosticAnalyzer.cs
@@ -23,7 +23,8 @@ private static readonly DiagnosticDescriptor Descriptor
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
- public override ImmutableArray SupportedDiagnostics => [Descriptor];
+ public override ImmutableArray SupportedDiagnostics
+ => [Descriptor];
public override void Initialize(AnalysisContext context)
{
@@ -308,14 +309,13 @@ private static bool IsInternal(OperationAnalysisContext context, ITypeSymbol sym
&& (IsInInternalNamespace(symbol) || HasInternalAttribute(symbol));
private static bool HasInternalAttribute(ISymbol symbol)
- => symbol.GetAttributes().Any(
- a =>
- a.AttributeClass!.ToDisplayString()
- == "Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkInternalAttribute");
+ => symbol.GetAttributes().Any(a =>
+ a.AttributeClass!.ToDisplayString()
+ == "Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkInternalAttribute");
private static bool IsInInternalNamespace(ISymbol symbol)
{
- if (symbol?.ContainingNamespace?.ToDisplayString() is string ns)
+ if (symbol?.ContainingNamespace?.ToDisplayString() is { } ns)
{
var i = ns.IndexOf("EntityFrameworkCore", StringComparison.Ordinal);
diff --git a/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesCodeFixProvider.cs b/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesCodeFixProvider.cs
index adcd46f5371..e5b7da68834 100644
--- a/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesCodeFixProvider.cs
+++ b/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesCodeFixProvider.cs
@@ -11,11 +11,11 @@
namespace Microsoft.EntityFrameworkCore;
-[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(InterpolatedStringUsageInRawQueriesCodeFixProvider))]
-[Shared]
+[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(InterpolatedStringUsageInRawQueriesCodeFixProvider)), Shared]
public sealed class InterpolatedStringUsageInRawQueriesCodeFixProvider : CodeFixProvider
{
- public override ImmutableArray FixableDiagnosticIds => [EFDiagnostics.InterpolatedStringUsageInRawQueries];
+ public override ImmutableArray FixableDiagnosticIds
+ => [EFDiagnostics.InterpolatedStringUsageInRawQueries];
public override FixAllProvider GetFixAllProvider()
=> WellKnownFixAllProviders.BatchFixer;
diff --git a/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesDiagnosticAnalyzer.cs b/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesDiagnosticAnalyzer.cs
index 5d7f07b5523..e4a0ea8f28d 100644
--- a/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesDiagnosticAnalyzer.cs
+++ b/src/EFCore.Analyzers/InterpolatedStringUsageInRawQueriesDiagnosticAnalyzer.cs
@@ -21,7 +21,8 @@ private static readonly DiagnosticDescriptor Descriptor
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
- public override ImmutableArray SupportedDiagnostics => [Descriptor];
+ public override ImmutableArray SupportedDiagnostics
+ => [Descriptor];
public override void Initialize(AnalysisContext context)
{
diff --git a/src/EFCore.Cosmos/ChangeTracking/Internal/StringDictionaryComparer.cs b/src/EFCore.Cosmos/ChangeTracking/Internal/StringDictionaryComparer.cs
index 865f95f73ca..200c12c890b 100644
--- a/src/EFCore.Cosmos/ChangeTracking/Internal/StringDictionaryComparer.cs
+++ b/src/EFCore.Cosmos/ChangeTracking/Internal/StringDictionaryComparer.cs
@@ -15,7 +15,8 @@ namespace Microsoft.EntityFrameworkCore.Cosmos.ChangeTracking.Internal;
public sealed class StringDictionaryComparer : ValueComparer, IInfrastructure
{
private static readonly MethodInfo CompareMethod = typeof(StringDictionaryComparer).GetMethod(
- nameof(Compare), BindingFlags.Static | BindingFlags.NonPublic, [typeof(object), typeof(object), typeof(Func)])!;
+ nameof(Compare), BindingFlags.Static | BindingFlags.NonPublic,
+ [typeof(object), typeof(object), typeof(Func)])!;
private static readonly MethodInfo GetHashCodeMethod = typeof(StringDictionaryComparer).GetMethod(
nameof(GetHashCode), BindingFlags.Static | BindingFlags.NonPublic, [typeof(IEnumerable), typeof(Func)])!;
@@ -72,7 +73,7 @@ private static Expression> GetHashCodeLambda(ValueComparer ele
Expression.Convert(
prm,
typeof(IEnumerable)),
- elementComparer.HashCodeExpression),
+ elementComparer.HashCodeExpression),
prm);
}
diff --git a/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs b/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs
index bf458d70a81..94219fc57a9 100644
--- a/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs
+++ b/src/EFCore.Cosmos/Diagnostics/Internal/CosmosLoggerExtensions.cs
@@ -205,19 +205,18 @@ private static string ExecutedReadNext(EventDefinitionBase definition, EventData
{
var d = (FallbackEventDefinition)definition;
var p = (CosmosQueryExecutedEventData)payload;
- return d.GenerateMessage(
- l => l.Log(
- d.Level,
- d.EventId,
- d.MessageFormat,
- p.Elapsed.TotalMilliseconds,
- p.RequestCharge,
- p.ActivityId,
- p.ContainerId,
- p.LogSensitiveData ? p.PartitionKeyValue.ToString() : "?",
- FormatParameters(p.Parameters, p is { LogSensitiveData: true, Parameters.Count: > 0 }),
- Environment.NewLine,
- p.QuerySql));
+ return d.GenerateMessage(l => l.Log(
+ d.Level,
+ d.EventId,
+ d.MessageFormat,
+ p.Elapsed.TotalMilliseconds,
+ p.RequestCharge,
+ p.ActivityId,
+ p.ContainerId,
+ p.LogSensitiveData ? p.PartitionKeyValue.ToString() : "?",
+ FormatParameters(p.Parameters, p is { LogSensitiveData: true, Parameters.Count: > 0 }),
+ Environment.NewLine,
+ p.QuerySql));
}
///
diff --git a/src/EFCore.Cosmos/Extensions/CosmosDbFunctionsExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosDbFunctionsExtensions.cs
index 88be60b6540..a9f144d61ad 100644
--- a/src/EFCore.Cosmos/Extensions/CosmosDbFunctionsExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/CosmosDbFunctionsExtensions.cs
@@ -109,7 +109,7 @@ public static double Rrf(this DbFunctions _, params double[] scores)
/// The second vector.
///
/// An optional boolean specifying how the computed value is used in an ORDER BY expression.
- /// If , then brute force is used. A value of uses any index defined on the vector
+ /// If , then brute force is used. A value of uses any index defined on the vector
/// property, if it exists. Default value is .
///
/// An optional object used to specify options for the vector distance calculation.
@@ -129,7 +129,7 @@ public static double VectorDistance(
/// The second vector.
///
/// An optional boolean specifying how the computed value is used in an ORDER BY expression.
- /// If , then brute force is used. A value of uses any index defined on the vector
+ /// If , then brute force is used. A value of uses any index defined on the vector
/// property, if it exists. Default value is .
///
/// An optional object used to specify options for the vector distance calculation.
@@ -149,7 +149,7 @@ public static double VectorDistance(
/// The second vector.
///
/// An optional boolean specifying how the computed value is used in an ORDER BY expression.
- /// If , then brute force is used. A value of uses any index defined on the vector
+ /// If , then brute force is used. A value of uses any index defined on the vector
/// property, if it exists. Default value is .
///
/// An optional object used to specify options for the vector distance calculation.
diff --git a/src/EFCore.Cosmos/Extensions/CosmosEntityTypeBuilderExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosEntityTypeBuilderExtensions.cs
index 3ea42adeda6..80d0452bc1a 100644
--- a/src/EFCore.Cosmos/Extensions/CosmosEntityTypeBuilderExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/CosmosEntityTypeBuilderExtensions.cs
@@ -1020,7 +1020,11 @@ public static bool CanSetThroughput(
///
/// See Database triggers for more information and examples.
///
- public static TriggerBuilder HasTrigger(this EntityTypeBuilder entityTypeBuilder, string modelName, TriggerType triggerType, TriggerOperation triggerOperation)
+ public static TriggerBuilder HasTrigger(
+ this EntityTypeBuilder entityTypeBuilder,
+ string modelName,
+ TriggerType triggerType,
+ TriggerOperation triggerOperation)
{
var triggerBuilder = EntityTypeBuilder.HasTrigger(entityTypeBuilder.Metadata, modelName);
triggerBuilder.Metadata.SetTriggerType(triggerType);
@@ -1039,7 +1043,11 @@ public static TriggerBuilder HasTrigger(this EntityTypeBuilder entityTypeBuilder
///
/// See Database triggers for more information and examples.
///
- public static TriggerBuilder HasTrigger(this EntityTypeBuilder entityTypeBuilder, string modelName, TriggerType triggerType, TriggerOperation triggerOperation)
+ public static TriggerBuilder HasTrigger(
+ this EntityTypeBuilder entityTypeBuilder,
+ string modelName,
+ TriggerType triggerType,
+ TriggerOperation triggerOperation)
where TEntity : class
{
var triggerBuilder = EntityTypeBuilder.HasTrigger(entityTypeBuilder.Metadata, modelName);
diff --git a/src/EFCore.Cosmos/Extensions/CosmosEntityTypeExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosEntityTypeExtensions.cs
index 02f86c605e1..8bd4c77e728 100644
--- a/src/EFCore.Cosmos/Extensions/CosmosEntityTypeExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/CosmosEntityTypeExtensions.cs
@@ -80,7 +80,7 @@ public static void SetContainer(this IMutableEntityType entityType, string? name
}
private static string? GetDefaultContainingPropertyName(IReadOnlyEntityType entityType)
- => entityType.FindOwnership() is IReadOnlyForeignKey ownership
+ => entityType.FindOwnership() is { } ownership
? ownership.PrincipalToDependent!.Name
: null;
diff --git a/src/EFCore.Cosmos/Extensions/CosmosIndexBuilderExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosIndexBuilderExtensions.cs
index 3edbb250a1a..44d93d11285 100644
--- a/src/EFCore.Cosmos/Extensions/CosmosIndexBuilderExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/CosmosIndexBuilderExtensions.cs
@@ -103,7 +103,8 @@ public static bool CanSetVectorIndexType(
///
/// Configures the index as a full-text index.
- /// See Full-text search in Azure Cosmos DB for NoSQL for more information.
+ /// See Full-text search in Azure Cosmos DB for NoSQL
+ /// for more information.
///
///
/// See Modeling entity types and relationships , and
@@ -121,7 +122,8 @@ public static IndexBuilder IsFullTextIndex(this IndexBuilder indexBuilder, bool
///
/// Configures the index as a full-text index.
- /// See Full-text search in Azure Cosmos DB for NoSQL for more information.
+ /// See Full-text search in Azure Cosmos DB for NoSQL
+ /// for more information.
///
///
/// See Modeling entity types and relationships , and
@@ -137,7 +139,8 @@ public static IndexBuilder IsFullTextIndex(
///
/// Configures the index as a full-text index.
- /// See Full-text search in Azure Cosmos DB for NoSQL for more information.
+ /// See Full-text search in Azure Cosmos DB for NoSQL
+ /// for more information.
///
///
/// See Modeling entity types and relationships , and
diff --git a/src/EFCore.Cosmos/Extensions/CosmosIndexExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosIndexExtensions.cs
index 078262d9f69..184742b86a2 100644
--- a/src/EFCore.Cosmos/Extensions/CosmosIndexExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/CosmosIndexExtensions.cs
@@ -74,7 +74,8 @@ public static void SetVectorIndexType(this IMutableIndex index, VectorIndexType?
///
/// Returns the value indicating whether the index is configured for full-text search.
- /// See Full-text search in Azure Cosmos DB for NoSQL for more information.
+ /// See Full-text search in Azure Cosmos DB for NoSQL
+ /// for more information.
///
/// The index.
/// The index type to use, or if none is set.
@@ -85,7 +86,8 @@ public static void SetVectorIndexType(this IMutableIndex index, VectorIndexType?
///
/// Configures the index for full-text search.
- /// See Full-text search in Azure Cosmos DB for NoSQL for more information.
+ /// See Full-text search in Azure Cosmos DB for NoSQL
+ /// for more information.
///
/// The index.
/// The value indicating whether the index is configured for full-text search.
@@ -94,7 +96,8 @@ public static void SetIsFullTextIndex(this IMutableIndex index, bool? fullTextIn
///
/// Configures the index for full-text search.
- /// See Full-text search in Azure Cosmos DB for NoSQL for more information.
+ /// See Full-text search in Azure Cosmos DB for NoSQL
+ /// for more information.
///
/// The index.
/// The value indicating whether the index is configured for full-text search.
diff --git a/src/EFCore.Cosmos/Extensions/CosmosPropertyBuilderExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosPropertyBuilderExtensions.cs
index 8a3161e694f..ba3c2b815ee 100644
--- a/src/EFCore.Cosmos/Extensions/CosmosPropertyBuilderExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/CosmosPropertyBuilderExtensions.cs
@@ -198,13 +198,13 @@ public static bool CanSetIsVectorProperty(
int dimensions,
bool fromDataAnnotation = false)
=> propertyBuilder.CanSetAnnotation(
- CosmosAnnotationNames.VectorDistanceFunction,
- ValidateVectorDistanceFunction(distanceFunction),
- fromDataAnnotation)
- && propertyBuilder.CanSetAnnotation(
- CosmosAnnotationNames.VectorDimensions,
- dimensions,
- fromDataAnnotation);
+ CosmosAnnotationNames.VectorDistanceFunction,
+ ValidateVectorDistanceFunction(distanceFunction),
+ fromDataAnnotation)
+ && propertyBuilder.CanSetAnnotation(
+ CosmosAnnotationNames.VectorDimensions,
+ dimensions,
+ fromDataAnnotation);
private static DistanceFunction ValidateVectorDistanceFunction(DistanceFunction distanceFunction)
=> Enum.IsDefined(distanceFunction)
@@ -256,7 +256,10 @@ public static PropertyBuilder IsETagConcurrency(
/// Accessing Azure Cosmos DB with EF Core for more information and examples.
///
/// The builder for the property being configured.
- /// The language used for full-text search. Setting this to ( will use the default language for the container, or "en-US" if default language was not specified.
+ ///
+ /// The language used for full-text search. Setting this to ( will use the default language for
+ /// the container, or "en-US" if default language was not specified.
+ ///
/// The value indicating whether full-text search should be enabled for this property.
/// The same builder instance so that multiple calls can be chained.
public static PropertyBuilder EnableFullTextSearch(
@@ -283,7 +286,10 @@ public static PropertyBuilder EnableFullTextSearch(
///
/// The type of the property being configured.
/// The builder for the property being configured.
- /// The language used for full-text search. Setting this to ( will use the default language for the container, or "en-US" if default language was not specified.
+ ///
+ /// The language used for full-text search. Setting this to ( will use the default language for
+ /// the container, or "en-US" if default language was not specified.
+ ///
/// The value indicating whether full-text search should be enabled for this property.
/// The same builder instance so that multiple calls can be chained.
public static PropertyBuilder EnableFullTextSearch(
@@ -300,7 +306,10 @@ public static PropertyBuilder EnableFullTextSearch(
/// Accessing Azure Cosmos DB with EF Core for more information and examples.
///
/// The builder for the property being configured.
- /// The language used for full-text search. Setting this to ( will use the default language for the container, or "en-US" if default language was not specified.
+ ///
+ /// The language used for full-text search. Setting this to ( will use the default language for
+ /// the container, or "en-US" if default language was not specified.
+ ///
/// The value indicating whether full-text search should be enabled for this property.
/// Indicates whether the configuration was specified using a data annotation.
///
diff --git a/src/EFCore.Cosmos/Extensions/CosmosServiceCollectionExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosServiceCollectionExtensions.cs
index 6169e54ca44..cfff8a16aa9 100644
--- a/src/EFCore.Cosmos/Extensions/CosmosServiceCollectionExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/CosmosServiceCollectionExtensions.cs
@@ -63,12 +63,11 @@ public static IServiceCollection AddCosmos(
Action? cosmosOptionsAction = null,
Action? optionsAction = null)
where TContext : DbContext
- => serviceCollection.AddDbContext(
- (serviceProvider, options) =>
- {
- optionsAction?.Invoke(options);
- options.UseCosmos(connectionString, databaseName, cosmosOptionsAction);
- });
+ => serviceCollection.AddDbContext((serviceProvider, options) =>
+ {
+ optionsAction?.Invoke(options);
+ options.UseCosmos(connectionString, databaseName, cosmosOptionsAction);
+ });
///
///
@@ -113,17 +112,16 @@ public static IServiceCollection AddEntityFrameworkCosmos(this IServiceCollectio
.TryAdd()
.TryAdd()
.TryAdd()
- .TryAddProviderSpecificServices(
- b => b
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddScoped()
- .TryAddScoped()
- .TryAddScoped()
- .TryAddScoped());
+ .TryAddProviderSpecificServices(b => b
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddScoped()
+ .TryAddScoped()
+ .TryAddScoped()
+ .TryAddScoped());
builder.TryAddCoreServices();
diff --git a/src/EFCore.Cosmos/Extensions/CosmosTriggerBuilderExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosTriggerBuilderExtensions.cs
index e5743c73d0d..f2507ebe114 100644
--- a/src/EFCore.Cosmos/Extensions/CosmosTriggerBuilderExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/CosmosTriggerBuilderExtensions.cs
@@ -15,7 +15,6 @@ namespace Microsoft.EntityFrameworkCore;
///
public static class CosmosTriggerBuilderExtensions
{
-
///
/// Configures the Cosmos DB trigger type for this trigger.
///
diff --git a/src/EFCore.Cosmos/Extensions/CosmosTriggerExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosTriggerExtensions.cs
index f7a7e314d2e..8eb4c5a810c 100644
--- a/src/EFCore.Cosmos/Extensions/CosmosTriggerExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/CosmosTriggerExtensions.cs
@@ -79,7 +79,8 @@ public static void SetTriggerOperation(this IMutableTrigger trigger, TriggerOper
this IConventionTrigger trigger,
TriggerOperation? triggerOperation,
bool fromDataAnnotation = false)
- => (TriggerOperation?)trigger.SetOrRemoveAnnotation(CosmosAnnotationNames.TriggerOperation, triggerOperation, fromDataAnnotation)?.Value;
+ => (TriggerOperation?)trigger.SetOrRemoveAnnotation(CosmosAnnotationNames.TriggerOperation, triggerOperation, fromDataAnnotation)
+ ?.Value;
///
/// Gets the for the Cosmos DB trigger operation.
diff --git a/src/EFCore.Cosmos/Extensions/Internal/CosmosShapedQueryExpressionExtensions.cs b/src/EFCore.Cosmos/Extensions/Internal/CosmosShapedQueryExpressionExtensions.cs
index 586f11b0529..be295279ee4 100644
--- a/src/EFCore.Cosmos/Extensions/Internal/CosmosShapedQueryExpressionExtensions.cs
+++ b/src/EFCore.Cosmos/Extensions/Internal/CosmosShapedQueryExpressionExtensions.cs
@@ -166,7 +166,7 @@ public static bool TryExtractArray(
{
projectedStructuralTypeShaper = shaper;
projection = shaper.ValueBufferExpression;
- if (projection is ProjectionBindingExpression { ProjectionMember: ProjectionMember projectionMember }
+ if (projection is ProjectionBindingExpression { ProjectionMember: { } projectionMember }
&& select.GetMappedProjection(projectionMember) is EntityProjectionExpression entityProjection)
{
projection = entityProjection.Object;
@@ -261,7 +261,7 @@ private static bool TryGetProjection(ShapedQueryExpression shapedQueryExpression
switch (shaperExpression)
{
- case ProjectionBindingExpression { ProjectionMember: ProjectionMember projectionMember }
+ case ProjectionBindingExpression { ProjectionMember: { } projectionMember }
when shapedQueryExpression.QueryExpression is SelectExpression selectExpression:
{
projection = selectExpression.GetMappedProjection(projectionMember);
diff --git a/src/EFCore.Cosmos/Metadata/Conventions/CosmosPartitionKeyInPrimaryKeyConvention.cs b/src/EFCore.Cosmos/Metadata/Conventions/CosmosPartitionKeyInPrimaryKeyConvention.cs
index 67861f51a66..8662af0361c 100644
--- a/src/EFCore.Cosmos/Metadata/Conventions/CosmosPartitionKeyInPrimaryKeyConvention.cs
+++ b/src/EFCore.Cosmos/Metadata/Conventions/CosmosPartitionKeyInPrimaryKeyConvention.cs
@@ -97,7 +97,7 @@ private static void ProcessJObjectProperty(IConventionEntityTypeBuilder entityTy
var jObjectProperty = entityType.FindDeclaredProperty(JObjectPropertyName);
if (jObjectProperty != null)
{
- entityType.Builder.RemoveUnusedImplicitProperties(new[] { jObjectProperty });
+ entityType.Builder.RemoveUnusedImplicitProperties([jObjectProperty]);
}
}
}
diff --git a/src/EFCore.Cosmos/Metadata/Conventions/Internal/CosmosConventionSetBuilder.cs b/src/EFCore.Cosmos/Metadata/Conventions/Internal/CosmosConventionSetBuilder.cs
index 6756b34abf2..160f4bdeb29 100644
--- a/src/EFCore.Cosmos/Metadata/Conventions/Internal/CosmosConventionSetBuilder.cs
+++ b/src/EFCore.Cosmos/Metadata/Conventions/Internal/CosmosConventionSetBuilder.cs
@@ -81,10 +81,9 @@ private static IServiceScope CreateServiceScope()
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkCosmos()
- .AddDbContext(
- (p, o) =>
- o.UseCosmos("localhost", "_", "_")
- .UseInternalServiceProvider(p))
+ .AddDbContext((p, o) =>
+ o.UseCosmos("localhost", "_", "_")
+ .UseInternalServiceProvider(p))
.BuildServiceProvider();
return serviceProvider.GetRequiredService().CreateScope();
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosAliasManager.cs b/src/EFCore.Cosmos/Query/Internal/CosmosAliasManager.cs
index bb43035c4f0..6227029eae3 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosAliasManager.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosAliasManager.cs
@@ -51,7 +51,7 @@ public virtual string GenerateSourceAlias(Expression expression, string? fallbac
=> GenerateSourceAlias(
expression switch
{
- IAccessExpression { PropertyName: string propertyName } => propertyName,
+ IAccessExpression { PropertyName: { } propertyName } => propertyName,
FromSqlExpression => "sql",
SqlFunctionExpression { Name: "ARRAY_SLICE", Arguments: [var array, ..] } => GenerateSourceAlias(array),
ObjectFunctionExpression { Name: "ARRAY_SLICE", Arguments: [var array, ..] } => GenerateSourceAlias(array),
@@ -185,7 +185,7 @@ public virtual Expression PostprocessAliases(Expression expression)
private sealed class SourceAliasCollector : ExpressionVisitor
{
- private readonly HashSet _sourceAliases = new();
+ private readonly HashSet _sourceAliases = [];
internal static HashSet Collect(Expression expression)
{
@@ -201,7 +201,7 @@ protected override Expression VisitExtension(Expression node)
case ShapedQueryExpression shapedQuery:
return shapedQuery.UpdateQueryExpression(Visit(shapedQuery.QueryExpression));
- case SourceExpression { Alias: string alias }:
+ case SourceExpression { Alias: { } alias }:
_sourceAliases.Add(alias);
return base.VisitExtension(node);
@@ -221,7 +221,7 @@ protected override Expression VisitExtension(Expression node)
{
ShapedQueryExpression shapedQuery => shapedQuery.UpdateQueryExpression(Visit(shapedQuery.QueryExpression)),
- SourceExpression { Alias: string alias } source when aliasRewritingMap.TryGetValue(alias, out var newAlias)
+ SourceExpression { Alias: { } alias } source when aliasRewritingMap.TryGetValue(alias, out var newAlias)
=> base.VisitExtension(new SourceExpression(source.Expression, newAlias, source.WithIn)),
ScalarReferenceExpression reference when aliasRewritingMap.TryGetValue(reference.Name, out var newAlias)
=> new ScalarReferenceExpression(newAlias, reference.Type, reference.TypeMapping),
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs
index 38ceb4f0942..72abbf75413 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosProjectionBindingExpressionVisitor.cs
@@ -577,7 +577,7 @@ UnaryExpression unaryExpression
&& methodCallExpression.Arguments is [var argument]
&& argument.Type.TryGetElementType(typeof(IQueryable<>)) != null)
{
- if (_queryableMethodTranslatingExpressionVisitor.TranslateSubquery(argument) is not ShapedQueryExpression subquery
+ if (_queryableMethodTranslatingExpressionVisitor.TranslateSubquery(argument) is not { } subquery
|| !subquery.TryConvertToArray(_typeMappingSource, out var array))
{
throw new InvalidOperationException(CoreStrings.TranslationFailed(methodCallExpression.Print()));
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosQueryCompilationContext.cs b/src/EFCore.Cosmos/Query/Internal/CosmosQueryCompilationContext.cs
index 2673f87de42..bc804f1f869 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosQueryCompilationContext.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosQueryCompilationContext.cs
@@ -29,7 +29,7 @@ public class CosmosQueryCompilationContext(QueryCompilationContextDependencies d
/// 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 List PartitionKeyPropertyValues { get; internal set; } = new();
+ public virtual List PartitionKeyPropertyValues { get; internal set; } = [];
///
/// A manager for aliases, capable of generate uniquified source aliases.
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosQuerySqlGenerator.cs b/src/EFCore.Cosmos/Query/Internal/CosmosQuerySqlGenerator.cs
index cf0c28cd552..53466ffa814 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosQuerySqlGenerator.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosQuerySqlGenerator.cs
@@ -347,7 +347,9 @@ protected override Expression VisitSelect(SelectExpression selectExpression)
_sqlBuilder.Append("RANK ");
}
- Check.DebugAssert(orderByScoringFunction || selectExpression.Orderings.All(x => x.Expression is not SqlFunctionExpression { IsScoringFunction: true }),
+ Check.DebugAssert(
+ orderByScoringFunction
+ || selectExpression.Orderings.All(x => x.Expression is not SqlFunctionExpression { IsScoringFunction: true }),
"Scoring function can only appear as first (and only) ordering, or not at all.");
GenerateList(selectExpression.Orderings, e => Visit(e));
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs
index 7083e6978ea..3f826412a13 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosQueryableMethodTranslatingExpressionVisitor.cs
@@ -206,10 +206,10 @@ when methodCallExpression.Arguments[0] is MethodCallExpression
var returnDefault = method.Name == nameof(Queryable.ElementAtOrDefault);
if (Visit(innerMethodCall) is ShapedQueryExpression translatedSelect
&& translatedSelect.TryExtractArray(out _, out _, out _, out var boundMember)
- && boundMember is IAccessExpression { PropertyName: string boundPropertyName }
+ && boundMember is IAccessExpression { PropertyName: { } boundPropertyName }
&& Visit(innerMethodCall.Arguments[0]) is ShapedQueryExpression innerSource
&& TranslateElementAtOrDefault(
- innerSource, methodCallExpression.Arguments[1], returnDefault) is ShapedQueryExpression elementAtTranslation)
+ innerSource, methodCallExpression.Arguments[1], returnDefault) is { } elementAtTranslation)
{
#pragma warning disable EF1001 // Internal EF Core API usage.
var translation = _sqlTranslator.Translate(
@@ -330,8 +330,8 @@ protected override QueryableMethodTranslatingExpressionVisitor CreateSubqueryVis
selectExpression,
_sqlExpressionFactory.In(
(SqlExpression)discriminatorColumn,
- concreteEntityTypes.Select(
- et => _sqlExpressionFactory.Constant(et.GetDiscriminatorValue(), discriminatorColumn.Type))
+ concreteEntityTypes.Select(et => _sqlExpressionFactory.Constant(
+ et.GetDiscriminatorValue(), discriminatorColumn.Type))
.ToArray()));
Check.DebugAssert(success, "Couldn't apply predicate when creating a new ShapedQueryExpression");
}
@@ -412,7 +412,7 @@ private ShapedQueryExpression CreateShapedQueryExpression(SelectExpression selec
{
var simplifiedTranslation = _sqlExpressionFactory.GreaterThan(
_sqlExpressionFactory.Function(
- "ARRAY_LENGTH", new[] { array }, typeof(int), _typeMappingSource.FindMapping(typeof(int))),
+ "ARRAY_LENGTH", [array], typeof(int), _typeMappingSource.FindMapping(typeof(int))),
_sqlExpressionFactory.Constant(0));
var select = new SelectExpression(simplifiedTranslation);
@@ -476,7 +476,7 @@ protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression sou
// Simplify x.Array.Contains[1] => ARRAY_CONTAINS(x.Array, 1) insert of IN+subquery
if (source.TryExtractArray(out var array, ignoreOrderings: true)
&& array is SqlExpression scalarArray // TODO: Contains over arrays of structural types, #34027
- && TranslateExpression(item) is SqlExpression translatedItem)
+ && TranslateExpression(item) is { } translatedItem)
{
if (array is ArrayConstantExpression arrayConstant)
{
@@ -548,7 +548,7 @@ protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression sou
Expression index,
bool returnDefault)
{
- if (TranslateExpression(index) is not SqlExpression translatedIndex)
+ if (TranslateExpression(index) is not { } translatedIndex)
{
return null;
}
@@ -669,7 +669,7 @@ protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression sou
{
if (predicate != null)
{
- if (TranslateWhere(source, predicate) is not ShapedQueryExpression translatedSource)
+ if (TranslateWhere(source, predicate) is not { } translatedSource)
{
return null;
}
@@ -769,7 +769,7 @@ protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression sou
{
if (predicate != null)
{
- if (TranslateWhere(source, predicate) is not ShapedQueryExpression translatedSource)
+ if (TranslateWhere(source, predicate) is not { } translatedSource)
{
return null;
}
@@ -925,7 +925,7 @@ protected override ShapedQueryExpression TranslateCast(ShapedQueryExpression sou
return null;
}
- if (TranslateLambdaExpression(source, keySelector) is SqlExpression translation)
+ if (TranslateLambdaExpression(source, keySelector) is { } translation)
{
((SelectExpression)source.QueryExpression).ApplyOrdering(new OrderingExpression(translation, ascending));
@@ -1052,7 +1052,7 @@ protected override ShapedQueryExpression TranslateSelect(ShapedQueryExpression s
{
if (predicate != null)
{
- if (TranslateWhere(source, predicate) is not ShapedQueryExpression translatedSource)
+ if (TranslateWhere(source, predicate) is not { } translatedSource)
{
return null;
}
@@ -1087,7 +1087,7 @@ protected override ShapedQueryExpression TranslateSelect(ShapedQueryExpression s
///
protected override ShapedQueryExpression? TranslateSkip(ShapedQueryExpression source, Expression count)
{
- if (TranslateExpression(count) is not SqlExpression translatedCount)
+ if (TranslateExpression(count) is not { } translatedCount)
{
return null;
}
@@ -1200,7 +1200,7 @@ protected override ShapedQueryExpression TranslateSelect(ShapedQueryExpression s
var serverOutputType = resultType.UnwrapNullableType();
var projection = (SqlExpression)selectExpression.GetMappedProjection(new ProjectionMember());
- projection = _sqlExpressionFactory.Function("SUM", new[] { projection }, serverOutputType, projection.TypeMapping);
+ projection = _sqlExpressionFactory.Function("SUM", [projection], serverOutputType, projection.TypeMapping);
return AggregateResultShaper(source, projection, resultType);
}
@@ -1213,7 +1213,7 @@ protected override ShapedQueryExpression TranslateSelect(ShapedQueryExpression s
///
protected override ShapedQueryExpression? TranslateTake(ShapedQueryExpression source, Expression count)
{
- if (TranslateExpression(count) is not SqlExpression translatedCount)
+ if (TranslateExpression(count) is not { } translatedCount)
{
return null;
}
@@ -1323,7 +1323,7 @@ protected override ShapedQueryExpression TranslateSelect(ShapedQueryExpression s
///
protected override ShapedQueryExpression? TranslateThenBy(ShapedQueryExpression source, LambdaExpression keySelector, bool ascending)
{
- if (TranslateLambdaExpression(source, keySelector) is SqlExpression translation)
+ if (TranslateLambdaExpression(source, keySelector) is { } translation)
{
((SelectExpression)source.QueryExpression).AppendOrdering(new OrderingExpression(translation, ascending));
@@ -1426,7 +1426,7 @@ protected override ShapedQueryExpression TranslateSelect(ShapedQueryExpression s
for (var i = 0; i < values.Count; i++)
{
- if (TranslateExpression(values[i]) is not SqlExpression translatedItem)
+ if (TranslateExpression(values[i]) is not { } translatedItem)
{
return null;
}
@@ -1476,7 +1476,11 @@ protected override ShapedQueryExpression TranslateSelect(ShapedQueryExpression s
#endregion Queryable collection support
- private ShapedQueryExpression? TranslateAggregate(ShapedQueryExpression source, LambdaExpression? selector, Type resultType, string functionName)
+ private ShapedQueryExpression? TranslateAggregate(
+ ShapedQueryExpression source,
+ LambdaExpression? selector,
+ Type resultType,
+ string functionName)
{
var selectExpression = (SelectExpression)source.QueryExpression;
if (selectExpression.IsDistinct
@@ -1515,7 +1519,7 @@ private bool TryApplyPredicate(ShapedQueryExpression source, LambdaExpression pr
return false;
}
- if (TranslateLambdaExpression(source, predicate) is SqlExpression translation)
+ if (TranslateLambdaExpression(source, predicate) is { } translation)
{
if (translation is not SqlConstantExpression { Value: true })
{
@@ -1582,7 +1586,7 @@ private bool TryPushdownIntoSubquery(SelectExpression select)
if (predicate is null && source.TryExtractArray(out var array, ignoreOrderings: true))
{
var simplifiedTranslation = _sqlExpressionFactory.Function(
- "ARRAY_LENGTH", new[] { array }, typeof(int), _typeMappingSource.FindMapping(typeof(int)));
+ "ARRAY_LENGTH", [array], typeof(int), _typeMappingSource.FindMapping(typeof(int)));
var select = new SelectExpression(simplifiedTranslation);
return source.Update(select, new ProjectionBindingExpression(select, new ProjectionMember(), typeof(int)));
@@ -1600,7 +1604,7 @@ private bool TryPushdownIntoSubquery(SelectExpression select)
if (predicate != null)
{
- if (TranslateWhere(source, predicate) is not ShapedQueryExpression translatedSource)
+ if (TranslateWhere(source, predicate) is not { } translatedSource)
{
return null;
}
@@ -1609,7 +1613,7 @@ private bool TryPushdownIntoSubquery(SelectExpression select)
}
var translation = _sqlExpressionFactory.ApplyDefaultTypeMapping(
- _sqlExpressionFactory.Function("COUNT", new[] { _sqlExpressionFactory.Constant(1) }, typeof(int)));
+ _sqlExpressionFactory.Function("COUNT", [_sqlExpressionFactory.Constant(1)], typeof(int)));
var projectionMapping = new Dictionary { { new ProjectionMember(), translation } };
@@ -1714,7 +1718,7 @@ private ShapedQueryExpression TranslateTwoParameterSelector(ShapedQueryExpressio
var replacement2 = AccessField(transparentIdentifierType, transparentIdentifierParameter, "Inner");
var newResultSelector = Expression.Lambda(
new ReplacingExpressionVisitor(
- new[] { original1, original2 }, new[] { replacement1, replacement2 })
+ [original1, original2], [replacement1, replacement2])
.Visit(resultSelector.Body),
transparentIdentifierParameter);
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosReadItemAndPartitionKeysExtractor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosReadItemAndPartitionKeysExtractor.cs
index a0311a5c457..43225c4823f 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosReadItemAndPartitionKeysExtractor.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosReadItemAndPartitionKeysExtractor.cs
@@ -46,7 +46,7 @@ public virtual Expression ExtractPartitionKeysAndId(
QueryExpression: SelectExpression
{
Sources: [{ Expression: ObjectReferenceExpression } rootSource, ..],
- Predicate: SqlExpression predicate
+ Predicate: { } predicate
} select
} shapedQuery)
{
@@ -98,7 +98,7 @@ public virtual Expression ExtractPartitionKeysAndId(
var liftPartitionKeys = queryCompilationContext.PartitionKeyPropertyValues.Count == 0;
foreach (var property in partitionKeyProperties)
{
- if (liftPartitionKeys && _partitionKeyPropertyValues[property].ValueExpression is Expression valueExpression)
+ if (liftPartitionKeys && _partitionKeyPropertyValues[property].ValueExpression is { } valueExpression)
{
queryCompilationContext.PartitionKeyPropertyValues.Add(valueExpression);
}
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitorBase.cs b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitorBase.cs
index 6e434aee428..de333edebc8 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitorBase.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.CosmosProjectionBindingRemovingExpressionVisitorBase.cs
@@ -797,7 +797,7 @@ var body
else
{
replaceExpression = isNonNullableScalar
- ? Expression.Convert(
+ ? Convert(
Default(originalBodyType),
type)
: Default(type);
@@ -820,7 +820,8 @@ var body
jTokenExpression,
(isNonNullableScalar
? typeMapping?.ClrType
- : typeMapping?.ClrType.MakeNullable()) ?? type);
+ : typeMapping?.ClrType.MakeNullable())
+ ?? type);
if (valueExpression.Type != type)
{
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ParameterInliner.cs b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ParameterInliner.cs
index 723c8206a38..0c588614ea6 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ParameterInliner.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.ParameterInliner.cs
@@ -27,13 +27,13 @@ protected override Expression VisitExtension(Expression expression)
switch (inExpression)
{
- case { Values: IReadOnlyList values2 }:
+ case { Values: { } values2 }:
values = values2;
break;
// TODO: IN with subquery (return immediately, nothing to do here)
- case { ValuesParameter: SqlParameterExpression valuesParameter }:
+ case { ValuesParameter: { } valuesParameter }:
{
var typeMapping = valuesParameter.TypeMapping;
var mutableValues = new List();
@@ -57,7 +57,11 @@ protected override Expression VisitExtension(Expression expression)
// Converts Offset and Limit parameters to constants when ORDER BY RANK is detected in the SelectExpression (i.e. we order by scoring function)
// Cosmos only supports constants in Offset and Limit for this scenario currently (ORDER BY RANK limitation)
- case SelectExpression { Orderings: [{ Expression: SqlFunctionExpression { IsScoringFunction: true } }], Limit: var limit, Offset: var offset } hybridSearch
+ case SelectExpression
+ {
+ Orderings: [{ Expression: SqlFunctionExpression { IsScoringFunction: true } }], Limit: var limit,
+ Offset: var offset
+ } hybridSearch
when limit is SqlParameterExpression || offset is SqlParameterExpression:
{
if (hybridSearch.Limit is SqlParameterExpression limitPrm)
@@ -79,15 +83,19 @@ protected override Expression VisitExtension(Expression expression)
return base.VisitExtension(expression);
}
- // Inlines array parameter of full-text functions, transforming FullTextContainsAll(x, @keywordsArray) to FullTextContainsAll(x, keyword1, keyword2))
+ // Inlines array parameter of full-text functions, transforming FullTextContainsAll(x, @keywordsArray) to FullTextContainsAll(x, keyword1, keyword2))
// we do this for FullTextContainsAll, FullTextContainsAny and FullTextScore
case SqlFunctionExpression
- {
- Name: string name,
- IsScoringFunction: bool scoringFunction,
- Arguments: [var property, SqlParameterExpression { TypeMapping: { ElementTypeMapping: var elementTypeMapping }, Type: Type type } keywords]
- } fullTextContainsAllAnyFunction
- when (name is "FullTextContainsAny" or "FullTextContainsAll" or "FullTextScore") && type == typeof(string[]):
+ {
+ Name: { } name,
+ IsScoringFunction: var scoringFunction,
+ Arguments:
+ [
+ var property,
+ SqlParameterExpression { TypeMapping: { ElementTypeMapping: var elementTypeMapping }, Type: { } type } keywords
+ ]
+ } fullTextContainsAllAnyFunction
+ when (name is "FullTextContainsAny" or "FullTextContainsAll" or "FullTextScore") && type == typeof(string[]):
{
var keywordValues = new List();
foreach (var value in (IEnumerable)parametersValues[keywords.Name])
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.cs
index 224dbf03151..f79539eb0b7 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosShapedQueryCompilingExpressionVisitor.cs
@@ -33,7 +33,7 @@ public partial class CosmosShapedQueryCompilingExpressionVisitor(
///
protected override Expression VisitShapedQuery(ShapedQueryExpression shapedQueryExpression)
{
- if (cosmosQueryCompilationContext.RootEntityType is not IEntityType rootEntityType)
+ if (cosmosQueryCompilationContext.RootEntityType is not { } rootEntityType)
{
throw new UnreachableException("No root entity type was set during query processing.");
}
@@ -88,7 +88,7 @@ protected override Expression VisitShapedQuery(ShapedQueryExpression shapedQuery
return selectExpression switch
{
- { ReadItemInfo: ReadItemInfo readItemInfo } => New(
+ { ReadItemInfo: { } readItemInfo } => New(
typeof(ReadItemQueryingEnumerable<>).MakeGenericType(shaperLambda.ReturnType).GetConstructors()[0],
cosmosQueryContextConstant,
rootEntityTypeConstant,
diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs
index 18583a1d262..f963e03ee06 100644
--- a/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs
+++ b/src/EFCore.Cosmos/Query/Internal/CosmosSqlTranslatingExpressionVisitor.cs
@@ -418,7 +418,7 @@ protected override Expression VisitExtension(Expression extensionExpression)
var subquery = (SelectExpression)shapedQuery.QueryExpression;
- var projection = mappedProjectionBindingExpression.ProjectionMember is ProjectionMember projectionMember
+ var projection = mappedProjectionBindingExpression.ProjectionMember is { } projectionMember
? subquery.GetMappedProjection(projectionMember)
: throw new NotImplementedException("Subquery with index projection binding");
if (projection is not SqlExpression sqlExpression)
@@ -768,7 +768,7 @@ protected override Expression VisitNewArray(NewArrayExpression newArrayExpressio
for (var i = 0; i < expressions.Count; i++)
{
- if (Translate(expressions[i]) is not SqlExpression translatedItem)
+ if (Translate(expressions[i]) is not { } translatedItem)
{
return QueryCompilationContext.NotTranslatedExpression;
}
@@ -907,17 +907,17 @@ public virtual bool TryBindMember(
switch (typeReference)
{
- case { Parameter: StructuralTypeShaperExpression shaper }:
+ case { Parameter: { } shaper }:
var valueBufferExpression = Visit(shaper.ValueBufferExpression);
var entityProjection = (EntityProjectionExpression)valueBufferExpression;
expression = member switch
{
- { MemberInfo: MemberInfo memberInfo }
+ { MemberInfo: { } memberInfo }
=> entityProjection.BindMember(
memberInfo, typeReference.Type, clientEval: false, out property),
- { Name: string name }
+ { Name: { } name }
=> entityProjection.BindMember(
name, typeReference.Type, clientEval: false, out property),
@@ -926,7 +926,7 @@ public virtual bool TryBindMember(
break;
- case { Subquery: ShapedQueryExpression }:
+ case { Subquery: not null }:
throw new NotImplementedException("Bind property on structural type coming out of scalar subquery");
default:
@@ -1094,11 +1094,10 @@ private bool TryRewriteEntityEquality(
}
result = Visit(
- primaryKeyProperties1.Select(
- p =>
- Expression.MakeBinary(
- nodeType, CreatePropertyAccessExpression(nonNullEntityReference, p),
- Expression.Constant(null, p.ClrType.MakeNullable())))
+ primaryKeyProperties1.Select(p =>
+ Expression.MakeBinary(
+ nodeType, CreatePropertyAccessExpression(nonNullEntityReference, p),
+ Expression.Constant(null, p.ClrType.MakeNullable())))
.Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.OrElse(l, r) : Expression.AndAlso(l, r)));
return true;
@@ -1132,16 +1131,14 @@ private bool TryRewriteEntityEquality(
}
result = Visit(
- primaryKeyProperties.Select(
- p =>
- Expression.MakeBinary(
- nodeType,
- CreatePropertyAccessExpression(left, p),
- CreatePropertyAccessExpression(right, p)))
- .Aggregate(
- (l, r) => nodeType == ExpressionType.Equal
- ? Expression.AndAlso(l, r)
- : Expression.OrElse(l, r)));
+ primaryKeyProperties.Select(p =>
+ Expression.MakeBinary(
+ nodeType,
+ CreatePropertyAccessExpression(left, p),
+ CreatePropertyAccessExpression(right, p)))
+ .Aggregate((l, r) => nodeType == ExpressionType.Equal
+ ? Expression.AndAlso(l, r)
+ : Expression.OrElse(l, r)));
return true;
}
@@ -1168,8 +1165,8 @@ private Expression CreatePropertyAccessExpression(Expression target, IProperty p
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:
@@ -1283,8 +1280,8 @@ public Expression Convert(Type type)
return this;
}
- return EntityType is IEntityType entityType
- && entityType.GetDerivedTypes().FirstOrDefault(et => et.ClrType == type) is IEntityType derivedEntityType
+ return EntityType is { } entityType
+ && entityType.GetDerivedTypes().FirstOrDefault(et => et.ClrType == type) is { } derivedEntityType
? new EntityReferenceExpression(this, derivedEntityType)
: QueryCompilationContext.NotTranslatedExpression;
}
diff --git a/src/EFCore.Cosmos/Query/Internal/Expressions/FragmentExpression.cs b/src/EFCore.Cosmos/Query/Internal/Expressions/FragmentExpression.cs
index 3efd431ca2f..3770033be34 100644
--- a/src/EFCore.Cosmos/Query/Internal/Expressions/FragmentExpression.cs
+++ b/src/EFCore.Cosmos/Query/Internal/Expressions/FragmentExpression.cs
@@ -1,9 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-
-
// ReSharper disable once CheckNamespace
+
namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal;
///
diff --git a/src/EFCore.Cosmos/Query/Internal/Expressions/PagingExpression.cs b/src/EFCore.Cosmos/Query/Internal/Expressions/PagingExpression.cs
index 5c929e6461f..0f7ba437e26 100644
--- a/src/EFCore.Cosmos/Query/Internal/Expressions/PagingExpression.cs
+++ b/src/EFCore.Cosmos/Query/Internal/Expressions/PagingExpression.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// ReSharper disable once CheckNamespace
+
namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal;
///
diff --git a/src/EFCore.Cosmos/Query/Internal/Expressions/SelectExpression.cs b/src/EFCore.Cosmos/Query/Internal/Expressions/SelectExpression.cs
index 6b11c765be5..622f4a8c72f 100644
--- a/src/EFCore.Cosmos/Query/Internal/Expressions/SelectExpression.cs
+++ b/src/EFCore.Cosmos/Query/Internal/Expressions/SelectExpression.cs
@@ -21,7 +21,7 @@ public sealed class SelectExpression : Expression, IPrintableExpression
private readonly List _projection = [];
private readonly List _orderings = [];
- private readonly List<(Expression ValueExpression, IProperty Property)> _partitionKeyValues = new();
+ private readonly List<(Expression ValueExpression, IProperty Property)> _partitionKeyValues = [];
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -407,8 +407,8 @@ public void AppendOrdering(OrderingExpression orderingExpression)
{
throw new InvalidOperationException(
appendingScoringFunctionOrdering && existingScoringFunctionOrdering
- ? CosmosStrings.OrderByMultipleScoringFunctionWithoutRrf(nameof(CosmosDbFunctionsExtensions.Rrf))
- : CosmosStrings.OrderByScoringFunctionMixedWithRegularOrderby);
+ ? CosmosStrings.OrderByMultipleScoringFunctionWithoutRrf(nameof(CosmosDbFunctionsExtensions.Rrf))
+ : CosmosStrings.OrderByScoringFunctionMixedWithRegularOrderby);
}
}
@@ -535,7 +535,7 @@ public Expression AddJoin(ShapedQueryExpression inner, Expression outerShaper, C
return New(
transparentIdentifierType.GetTypeInfo().DeclaredConstructors.Single(),
- new[] { outerShaper, innerShaper }, outerMemberInfo, innerMemberInfo);
+ [outerShaper, innerShaper], outerMemberInfo, innerMemberInfo);
}
///
diff --git a/src/EFCore.Cosmos/Query/Internal/ISqlExpressionFactory.cs b/src/EFCore.Cosmos/Query/Internal/ISqlExpressionFactory.cs
index f462c37ff0f..8763c2ba674 100644
--- a/src/EFCore.Cosmos/Query/Internal/ISqlExpressionFactory.cs
+++ b/src/EFCore.Cosmos/Query/Internal/ISqlExpressionFactory.cs
@@ -249,7 +249,11 @@ public interface ISqlExpressionFactory
/// 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.
///
- SqlExpression ScoringFunction(string functionName, IEnumerable arguments, Type returnType, CoreTypeMapping? typeMapping = null);
+ SqlExpression ScoringFunction(
+ string functionName,
+ IEnumerable arguments,
+ Type returnType,
+ CoreTypeMapping? typeMapping = null);
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
diff --git a/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs b/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs
index 52e5dcdcae3..951ab06cf82 100644
--- a/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs
+++ b/src/EFCore.Cosmos/Query/Internal/SqlExpressionFactory.cs
@@ -198,11 +198,11 @@ private InExpression ApplyTypeMappingOnIn(InExpression inExpression)
CoreTypeMapping? valuesTypeMapping = null;
switch (inExpression)
{
- case { ValuesParameter: SqlParameterExpression parameter }:
+ case { ValuesParameter: { } parameter }:
valuesTypeMapping = parameter.TypeMapping;
break;
- case { Values: IReadOnlyList values }:
+ case { Values: { } values }:
// Note: there could be conflicting type mappings inside the values; we take the first.
foreach (var value in values)
{
@@ -228,11 +228,11 @@ private InExpression ApplyTypeMappingOnIn(InExpression inExpression)
switch (inExpression)
{
- case { ValuesParameter: SqlParameterExpression parameter }:
+ case { ValuesParameter: { } parameter }:
inExpression = inExpression.Update(item, (SqlParameterExpression)ApplyTypeMapping(parameter, item.TypeMapping));
break;
- case { Values: IReadOnlyList values }:
+ case { Values: { } values }:
SqlExpression[]? newValues = null;
if (missingTypeMappingInValues)
diff --git a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosFullTextSearchTranslator.cs b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosFullTextSearchTranslator.cs
index b1edf94d67f..c4b511c0998 100644
--- a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosFullTextSearchTranslator.cs
+++ b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosFullTextSearchTranslator.cs
@@ -39,23 +39,24 @@ public class CosmosFullTextSearchTranslator(ISqlExpressionFactory sqlExpressionF
typeMappingSource.FindMapping(typeof(bool))),
nameof(CosmosDbFunctionsExtensions.FullTextScore)
- when arguments is [_, SqlExpression property, SqlConstantExpression { Type: var keywordClrType, Value: string[] values } keywords]
- && keywordClrType == typeof(string[]) => sqlExpressionFactory.ScoringFunction(
- "FullTextScore",
- [property, .. values.Select(x => sqlExpressionFactory.Constant(x))],
- typeof(double),
- typeMappingSource.FindMapping(typeof(double))),
+ when arguments is
+ [_, { } property, SqlConstantExpression { Type: var keywordClrType, Value: string[] values } keywords]
+ && keywordClrType == typeof(string[]) => sqlExpressionFactory.ScoringFunction(
+ "FullTextScore",
+ [property, .. values.Select(x => sqlExpressionFactory.Constant(x))],
+ typeof(double),
+ typeMappingSource.FindMapping(typeof(double))),
nameof(CosmosDbFunctionsExtensions.FullTextScore)
- when arguments is [_, SqlExpression property, SqlParameterExpression { Type: var keywordClrType } keywords]
- && keywordClrType == typeof(string[]) => sqlExpressionFactory.ScoringFunction(
- "FullTextScore",
- [property, keywords],
- typeof(double),
- typeMappingSource.FindMapping(typeof(double))),
+ when arguments is [_, { } property, SqlParameterExpression { Type: var keywordClrType } keywords]
+ && keywordClrType == typeof(string[]) => sqlExpressionFactory.ScoringFunction(
+ "FullTextScore",
+ [property, keywords],
+ typeof(double),
+ typeMappingSource.FindMapping(typeof(double))),
nameof(CosmosDbFunctionsExtensions.FullTextScore)
- when arguments is [_, SqlExpression property, ArrayConstantExpression keywords] => sqlExpressionFactory.ScoringFunction(
+ when arguments is [_, { } property, ArrayConstantExpression keywords] => sqlExpressionFactory.ScoringFunction(
"FullTextScore",
[property, .. keywords.Items],
typeof(double),
@@ -69,23 +70,24 @@ public class CosmosFullTextSearchTranslator(ISqlExpressionFactory sqlExpressionF
typeMappingSource.FindMapping(typeof(double))),
nameof(CosmosDbFunctionsExtensions.FullTextContainsAny) or nameof(CosmosDbFunctionsExtensions.FullTextContainsAll)
- when arguments is [_, SqlExpression property, SqlConstantExpression { Type: var keywordClrType, Value: string[] values } keywords]
- && keywordClrType == typeof(string[]) => sqlExpressionFactory.Function(
- method.Name == nameof(CosmosDbFunctionsExtensions.FullTextContainsAny) ? "FullTextContainsAny" : "FullTextContainsAll",
- [property, .. values.Select(x => sqlExpressionFactory.Constant(x))],
- typeof(bool),
- typeMappingSource.FindMapping(typeof(bool))),
+ when arguments is
+ [_, { } property, SqlConstantExpression { Type: var keywordClrType, Value: string[] values }]
+ && keywordClrType == typeof(string[]) => sqlExpressionFactory.Function(
+ method.Name == nameof(CosmosDbFunctionsExtensions.FullTextContainsAny) ? "FullTextContainsAny" : "FullTextContainsAll",
+ [property, .. values.Select(x => sqlExpressionFactory.Constant(x))],
+ typeof(bool),
+ typeMappingSource.FindMapping(typeof(bool))),
nameof(CosmosDbFunctionsExtensions.FullTextContainsAny) or nameof(CosmosDbFunctionsExtensions.FullTextContainsAll)
- when arguments is [_, SqlExpression property, SqlParameterExpression { Type: var keywordClrType } keywords]
- && keywordClrType == typeof(string[]) => sqlExpressionFactory.Function(
- method.Name == nameof(CosmosDbFunctionsExtensions.FullTextContainsAny) ? "FullTextContainsAny" : "FullTextContainsAll",
- [property, keywords],
- typeof(bool),
- typeMappingSource.FindMapping(typeof(bool))),
+ when arguments is [_, { } property, SqlParameterExpression { Type: var keywordClrType } keywords]
+ && keywordClrType == typeof(string[]) => sqlExpressionFactory.Function(
+ method.Name == nameof(CosmosDbFunctionsExtensions.FullTextContainsAny) ? "FullTextContainsAny" : "FullTextContainsAll",
+ [property, keywords],
+ typeof(bool),
+ typeMappingSource.FindMapping(typeof(bool))),
nameof(CosmosDbFunctionsExtensions.FullTextContainsAny) or nameof(CosmosDbFunctionsExtensions.FullTextContainsAll)
- when arguments is [_, SqlExpression property, ArrayConstantExpression keywords] => sqlExpressionFactory.Function(
+ when arguments is [_, { } property, ArrayConstantExpression keywords] => sqlExpressionFactory.Function(
method.Name == nameof(CosmosDbFunctionsExtensions.FullTextContainsAny) ? "FullTextContainsAny" : "FullTextContainsAll",
[property, .. keywords.Items],
typeof(bool),
diff --git a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosRandomTranslator.cs b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosRandomTranslator.cs
index 5269e7d3ba5..eaa785c1534 100644
--- a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosRandomTranslator.cs
+++ b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosRandomTranslator.cs
@@ -30,7 +30,7 @@ public class CosmosRandomTranslator(ISqlExpressionFactory sqlExpressionFactory)
=> MethodInfo.Equals(method)
? sqlExpressionFactory.Function(
"RAND",
- Enumerable.Empty(),
+ [],
method.ReturnType)
: null;
}
diff --git a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosRegexTranslator.cs b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosRegexTranslator.cs
index 6177d4dcd5c..7b11562abb3 100644
--- a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosRegexTranslator.cs
+++ b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosRegexTranslator.cs
@@ -46,7 +46,7 @@ public class CosmosRegexTranslator(ISqlExpressionFactory sqlExpressionFactory)
if (method == IsMatch || arguments[2] is SqlConstantExpression { Value: RegexOptions.None })
{
- return sqlExpressionFactory.Function("RegexMatch", new[] { input, pattern }, typeof(bool));
+ return sqlExpressionFactory.Function("RegexMatch", [input, pattern], typeof(bool));
}
if (arguments[2] is SqlConstantExpression { Value: RegexOptions regexOptions })
@@ -80,7 +80,7 @@ public class CosmosRegexTranslator(ISqlExpressionFactory sqlExpressionFactory)
return regexOptions == 0
? sqlExpressionFactory.Function(
"RegexMatch",
- new[] { input, pattern, sqlExpressionFactory.Constant(modifier) },
+ [input, pattern, sqlExpressionFactory.Constant(modifier)],
typeof(bool))
: null; // TODO: Report unsupported RegexOption, #26410
}
diff --git a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosStringMemberTranslator.cs b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosStringMemberTranslator.cs
index ab59359ce7b..b915b571203 100644
--- a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosStringMemberTranslator.cs
+++ b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosStringMemberTranslator.cs
@@ -30,7 +30,7 @@ public class CosmosStringMemberTranslator(ISqlExpressionFactory sqlExpressionFac
{
return sqlExpressionFactory.Function(
"LENGTH",
- new[] { instance! },
+ [instance!],
returnType);
}
diff --git a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosStringMethodTranslator.cs b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosStringMethodTranslator.cs
index a9d0b80b5f8..2cbd2b84231 100644
--- a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosStringMethodTranslator.cs
+++ b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosStringMethodTranslator.cs
@@ -92,14 +92,12 @@ private static readonly MethodInfo SubstringMethodInfoWithTwoArgs
= typeof(string).GetRuntimeMethod(nameof(string.Substring), [typeof(int), typeof(int)])!;
private static readonly MethodInfo FirstOrDefaultMethodInfoWithoutArgs
- = typeof(Enumerable).GetRuntimeMethods().Single(
- m => m.Name == nameof(Enumerable.FirstOrDefault)
- && m.GetParameters().Length == 1).MakeGenericMethod(typeof(char));
+ = typeof(Enumerable).GetRuntimeMethods().Single(m => m.Name == nameof(Enumerable.FirstOrDefault)
+ && m.GetParameters().Length == 1).MakeGenericMethod(typeof(char));
private static readonly MethodInfo LastOrDefaultMethodInfoWithoutArgs
- = typeof(Enumerable).GetRuntimeMethods().Single(
- m => m.Name == nameof(Enumerable.LastOrDefault)
- && m.GetParameters().Length == 1).MakeGenericMethod(typeof(char));
+ = typeof(Enumerable).GetRuntimeMethods().Single(m => m.Name == nameof(Enumerable.LastOrDefault)
+ && m.GetParameters().Length == 1).MakeGenericMethod(typeof(char));
private static readonly MethodInfo StringConcatWithTwoArguments =
typeof(string).GetRuntimeMethod(nameof(string.Concat), [typeof(string), typeof(string)])!;
diff --git a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosTypeCheckingTranslator.cs b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosTypeCheckingTranslator.cs
index f53efbee3d2..b5aaea6ec19 100644
--- a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosTypeCheckingTranslator.cs
+++ b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosTypeCheckingTranslator.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// ReSharper disable once CheckNamespace
+
namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal;
///
diff --git a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosVectorSearchTranslator.cs b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosVectorSearchTranslator.cs
index 47fd91fd15a..e942bee082d 100644
--- a/src/EFCore.Cosmos/Query/Internal/Translators/CosmosVectorSearchTranslator.cs
+++ b/src/EFCore.Cosmos/Query/Internal/Translators/CosmosVectorSearchTranslator.cs
@@ -58,14 +58,12 @@ public class CosmosVectorSearchTranslator(ISqlExpressionFactory sqlExpressionFac
?? vector2.TypeMapping as CosmosVectorTypeMapping
?? throw new InvalidOperationException(CosmosStrings.VectorSearchRequiresVector);
-
var vectorType = vectorMapping.VectorType;
- List newArguments = new()
- {
- sqlExpressionFactory.ApplyTypeMapping(vector1, vectorMapping),
- sqlExpressionFactory.ApplyTypeMapping(vector2, vectorMapping),
- };
+ List newArguments =
+ [
+ sqlExpressionFactory.ApplyTypeMapping(vector1, vectorMapping), sqlExpressionFactory.ApplyTypeMapping(vector2, vectorMapping)
+ ];
if (useBruteForceValue is not null)
{
@@ -85,7 +83,7 @@ public class CosmosVectorSearchTranslator(ISqlExpressionFactory sqlExpressionFac
var requireComma = false;
- if (options.DistanceFunction is DistanceFunction distanceFunction)
+ if (options.DistanceFunction is { } distanceFunction)
{
optionsBuilder
.Append("'distanceFunction': '")
diff --git a/src/EFCore.Cosmos/Query/VectorDistanceOptions.cs b/src/EFCore.Cosmos/Query/VectorDistanceOptions.cs
index 60baf1d0a2c..0417385c115 100644
--- a/src/EFCore.Cosmos/Query/VectorDistanceOptions.cs
+++ b/src/EFCore.Cosmos/Query/VectorDistanceOptions.cs
@@ -2,10 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// ReSharper disable once CheckNamespace
+
namespace Microsoft.EntityFrameworkCore;
///
-/// Options to be passed to
+/// Options to be passed to
+///
///
public sealed class VectorDistanceOptions
{
diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs
index e9dd8ed71a0..439fff3f856 100644
--- a/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs
+++ b/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs
@@ -6,10 +6,10 @@
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
+using Microsoft.Azure.Cosmos.Scripts;
using Microsoft.EntityFrameworkCore.Cosmos.Diagnostics.Internal;
using Microsoft.EntityFrameworkCore.Cosmos.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.Cosmos.Internal;
-using Microsoft.Azure.Cosmos.Scripts;
using Microsoft.EntityFrameworkCore.Cosmos.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Newtonsoft.Json;
@@ -322,19 +322,14 @@ private static async Task CreateContainerIfNotExistsOnceAsync(
if (vectorIndexes.Count != 0 || fullTextIndexPaths.Count != 0)
{
- containerProperties.IndexingPolicy = new IndexingPolicy
- {
- VectorIndexes = vectorIndexes,
- FullTextIndexes = fullTextIndexPaths
- };
+ containerProperties.IndexingPolicy = new IndexingPolicy { VectorIndexes = vectorIndexes, FullTextIndexes = fullTextIndexPaths };
}
if (fullTextPaths.Count != 0)
{
containerProperties.FullTextPolicy = new FullTextPolicy
{
- DefaultLanguage = parameters.DefaultFullTextLanguage,
- FullTextPaths = fullTextPaths
+ DefaultLanguage = parameters.DefaultFullTextLanguage, FullTextPaths = fullTextPaths
};
}
@@ -355,16 +350,16 @@ private static string GetPathFromRoot(IReadOnlyEntityType entityType)
if (entityType.IsOwned())
{
var ownership = entityType.FindOwnership()!;
- var resultPath = GetPathFromRoot(ownership.PrincipalEntityType) + "/" + ownership.GetNavigation(pointsToPrincipal: false)!.TargetEntityType.GetContainingPropertyName();
+ var resultPath = GetPathFromRoot(ownership.PrincipalEntityType)
+ + "/"
+ + ownership.GetNavigation(pointsToPrincipal: false)!.TargetEntityType.GetContainingPropertyName();
return !ownership.IsUnique
? throw new NotSupportedException(CosmosStrings.CreatingContainerWithFullTextOrVectorOnCollectionNotSupported(resultPath))
: resultPath;
}
- else
- {
- return "";
- }
+
+ return "";
}
///
@@ -429,6 +424,7 @@ private static async Task CreateItemOnceAsync(
{
itemRequestOptions.PreTriggers = preTriggers;
}
+
if (postTriggers != null)
{
itemRequestOptions.PostTriggers = postTriggers;
@@ -519,6 +515,7 @@ private static async Task ReplaceItemOnceAsync(
{
itemRequestOptions.PreTriggers = preTriggers;
}
+
if (postTriggers != null)
{
itemRequestOptions.PostTriggers = postTriggers;
@@ -600,6 +597,7 @@ private static async Task DeleteItemOnceAsync(
{
itemRequestOptions.PreTriggers = preTriggers;
}
+
if (postTriggers != null)
{
itemRequestOptions.PostTriggers = postTriggers;
@@ -684,9 +682,7 @@ private static async Task DeleteItemOnceAsync(
private static bool ShouldExecuteTrigger(ITrigger trigger, TriggerOperation currentOperation)
{
var triggerOperation = trigger.GetTriggerOperation();
- return triggerOperation == null ||
- triggerOperation == TriggerOperation.All ||
- triggerOperation == currentOperation;
+ return triggerOperation == null || triggerOperation == TriggerOperation.All || triggerOperation == currentOperation;
}
private static PartitionKey ExtractPartitionKeyValue(IUpdateEntry entry)
diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseCreator.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseCreator.cs
index 8d475d7268d..0e38528d301 100644
--- a/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseCreator.cs
+++ b/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseCreator.cs
@@ -120,7 +120,7 @@ private static IEnumerable GetContainersToCreate(IModel mod
var defaultFullTextLanguage = model.GetDefaultFullTextSearchLanguage();
foreach (var (containerName, mappedTypes) in containers)
{
- IReadOnlyList partitionKeyStoreNames = Array.Empty();
+ IReadOnlyList partitionKeyStoreNames = [];
int? analyticalTtl = null;
int? defaultTtl = null;
ThroughputProperties? throughput = null;
@@ -176,8 +176,8 @@ static void ProcessEntityType(
}
foreach (var ownedType in entityType.GetNavigations()
- .Where(x => x.ForeignKey.IsOwnership && !x.IsOnDependent && !x.TargetEntityType.IsDocumentRoot())
- .Select(x => x.TargetEntityType))
+ .Where(x => x.ForeignKey.IsOwnership && !x.IsOnDependent && !x.TargetEntityType.IsDocumentRoot())
+ .Select(x => x.TargetEntityType))
{
ProcessEntityType(ownedType, indexes, vectors, fullTextProperties);
}
diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs
index 14d088b1d9b..4464928a038 100644
--- a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs
+++ b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs
@@ -51,7 +51,8 @@ public CosmosTypeMappingSource(TypeMappingSourceDependencies dependencies)
=> base.FindMapping(property) switch
{
CosmosTypeMapping mapping
- when property.GetVectorDistanceFunction() is DistanceFunction distanceFunction && property.GetVectorDimensions() is int dimensions
+ when property.GetVectorDistanceFunction() is { } distanceFunction
+ && property.GetVectorDimensions() is { } dimensions
=> new CosmosVectorTypeMapping(mapping, new CosmosVectorType(distanceFunction, dimensions)),
var other => other
};
diff --git a/src/EFCore.Cosmos/Update/Internal/DocumentSource.cs b/src/EFCore.Cosmos/Update/Internal/DocumentSource.cs
index a2c782407f8..75b9a7f415a 100644
--- a/src/EFCore.Cosmos/Update/Internal/DocumentSource.cs
+++ b/src/EFCore.Cosmos/Update/Internal/DocumentSource.cs
@@ -310,8 +310,7 @@ private static void SetTemporaryOrdinals(
}
private static IProperty? FindOrdinalKeyProperty(IEntityType entityType)
- => entityType.FindPrimaryKey()!.Properties.FirstOrDefault(
- p => p.GetJsonPropertyName().Length == 0 && p.IsOrdinalKeyProperty());
+ => entityType.FindPrimaryKey()!.Properties.FirstOrDefault(p => p.GetJsonPropertyName().Length == 0 && p.IsOrdinalKeyProperty());
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
diff --git a/src/EFCore.Design/Design/DesignTimeServiceCollectionExtensions.cs b/src/EFCore.Design/Design/DesignTimeServiceCollectionExtensions.cs
index 38f6ca6242a..12e2a75f27f 100644
--- a/src/EFCore.Design/Design/DesignTimeServiceCollectionExtensions.cs
+++ b/src/EFCore.Design/Design/DesignTimeServiceCollectionExtensions.cs
@@ -35,41 +35,40 @@ public static IServiceCollection AddEntityFrameworkDesignTimeServices(
reporter ??= new OperationReporter(handler: null);
new EntityFrameworkRelationalDesignServicesBuilder(services)
- .TryAddProviderSpecificServices(
- services => services
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton(reporter)
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingletonEnumerable()
- .TryAddSingletonEnumerable()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton(
- new DesignTimeConnectionStringResolver(applicationServiceProviderAccessor))
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddScoped()
- .TryAddScoped()
- .TryAddScoped()
- .TryAddScoped());
+ .TryAddProviderSpecificServices(services => services
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton(reporter)
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingletonEnumerable()
+ .TryAddSingletonEnumerable()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton(
+ new DesignTimeConnectionStringResolver(applicationServiceProviderAccessor))
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddScoped()
+ .TryAddScoped()
+ .TryAddScoped()
+ .TryAddScoped());
var loggerFactory = new LoggerFactory(
- new[] { new OperationLoggerProvider(reporter) }, new LoggerFilterOptions { MinLevel = LogLevel.Debug });
+ [new OperationLoggerProvider(reporter)], new LoggerFilterOptions { MinLevel = LogLevel.Debug });
services.AddScoped(_ => loggerFactory);
return services;
diff --git a/src/EFCore.Design/Design/Internal/DatabaseOperations.cs b/src/EFCore.Design/Design/Internal/DatabaseOperations.cs
index f02f26bf4ed..db8f590e435 100644
--- a/src/EFCore.Design/Design/Internal/DatabaseOperations.cs
+++ b/src/EFCore.Design/Design/Internal/DatabaseOperations.cs
@@ -135,7 +135,7 @@ public virtual SavedModelFiles ScaffoldContext(
? string.Join(
".",
subPath.Split(
- new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries))
+ [Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], StringSplitOptions.RemoveEmptyEntries))
: null;
}
diff --git a/src/EFCore.Design/Design/Internal/DbContextOperations.cs b/src/EFCore.Design/Design/Internal/DbContextOperations.cs
index 2081d72c9bf..9e4e764a430 100644
--- a/src/EFCore.Design/Design/Internal/DbContextOperations.cs
+++ b/src/EFCore.Design/Design/Internal/DbContextOperations.cs
@@ -384,7 +384,7 @@ private IReadOnlyList PrecompileQueries(
? string.Join(
".",
subPath.Split(
- new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries))
+ [Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], StringSplitOptions.RemoveEmptyEntries))
: null;
}
@@ -551,8 +551,7 @@ where i.IsGenericType
.Concat(_assembly.GetConstructibleTypes())
.ToList();
- var contextTypes = types.Where(t => typeof(DbContext).IsAssignableFrom(t)).Select(
- t => t.AsType())
+ var contextTypes = types.Where(t => typeof(DbContext).IsAssignableFrom(t)).Select(t => t.AsType())
.Concat(
types.Where(t => typeof(Migration).IsAssignableFrom(t))
.Select(t => t.GetCustomAttribute()?.ContextType)
@@ -719,9 +718,8 @@ private KeyValuePair> FindContextType(string? name)
string name,
StringComparison comparisonType)
=> types
- .Where(
- t => string.Equals(t.Key.Name, name, comparisonType)
- || string.Equals(t.Key.FullName, name, comparisonType)
- || string.Equals(t.Key.AssemblyQualifiedName, name, comparisonType))
+ .Where(t => string.Equals(t.Key.Name, name, comparisonType)
+ || string.Equals(t.Key.FullName, name, comparisonType)
+ || string.Equals(t.Key.AssemblyQualifiedName, name, comparisonType))
.ToDictionary();
}
diff --git a/src/EFCore.Design/Design/Internal/MigrationsOperations.cs b/src/EFCore.Design/Design/Internal/MigrationsOperations.cs
index 88a7603b5fa..b7729c1f716 100644
--- a/src/EFCore.Design/Design/Internal/MigrationsOperations.cs
+++ b/src/EFCore.Design/Design/Internal/MigrationsOperations.cs
@@ -123,7 +123,7 @@ public virtual MigrationFiles AddMigration(
? string.Join(
".",
subPath.Split(
- new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar },
+ [Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar],
StringSplitOptions.RemoveEmptyEntries))
: null;
}
diff --git a/src/EFCore.Design/Design/OperationExecutor.cs b/src/EFCore.Design/Design/OperationExecutor.cs
index 947212a1db8..8c619b4cae0 100644
--- a/src/EFCore.Design/Design/OperationExecutor.cs
+++ b/src/EFCore.Design/Design/OperationExecutor.cs
@@ -434,18 +434,17 @@ private IEnumerable GetContextTypesImpl()
var nameGroups = contextTypes.GroupBy(t => t.Name).ToList();
var fullNameGroups = contextTypes.GroupBy(t => t.FullName).ToList();
- return contextTypes.Select(
- t => new Hashtable
- {
- ["AssemblyQualifiedName"] = t.AssemblyQualifiedName,
- ["FullName"] = t.FullName,
- ["Name"] = t.Name,
- ["SafeName"] = nameGroups.Count(g => g.Key == t.Name) == 1
- ? t.Name
- : fullNameGroups.Count(g => g.Key == t.FullName) == 1
- ? t.FullName
- : t.AssemblyQualifiedName
- });
+ return contextTypes.Select(t => new Hashtable
+ {
+ ["AssemblyQualifiedName"] = t.AssemblyQualifiedName,
+ ["FullName"] = t.FullName,
+ ["Name"] = t.Name,
+ ["SafeName"] = nameGroups.Count(g => g.Key == t.Name) == 1
+ ? t.Name
+ : fullNameGroups.Count(g => g.Key == t.FullName) == 1
+ ? t.FullName
+ : t.AssemblyQualifiedName
+ });
}
///
@@ -494,16 +493,15 @@ private IEnumerable GetMigrationsImpl(
var migrations = MigrationsOperations.GetMigrations(contextType, connectionString, noConnect).ToList();
var nameGroups = migrations.GroupBy(m => m.Name).ToList();
- return migrations.Select(
- m => new Hashtable
- {
- ["Id"] = m.Id,
- ["Name"] = m.Name,
- ["SafeName"] = nameGroups.Count(g => g.Key == m.Name) == 1
- ? m.Name
- : m.Id,
- ["Applied"] = m.Applied
- });
+ return migrations.Select(m => new Hashtable
+ {
+ ["Id"] = m.Id,
+ ["Name"] = m.Name,
+ ["SafeName"] = nameGroups.Count(g => g.Key == m.Name) == 1
+ ? m.Name
+ : m.Id,
+ ["Applied"] = m.Applied
+ });
}
///
@@ -543,15 +541,14 @@ public OptimizeContext(
var precompileQueries = (bool)(args["precompileQueries"] ?? false);
var nativeAot = (bool)(args["nativeAot"] ?? false);
- Execute(
- () => executor.OptimizeContextImpl(
- outputDir,
- modelNamespace,
- contextType,
- suffix,
- scaffoldModel,
- precompileQueries,
- nativeAot));
+ Execute(() => executor.OptimizeContextImpl(
+ outputDir,
+ modelNamespace,
+ contextType,
+ suffix,
+ scaffoldModel,
+ precompileQueries,
+ nativeAot));
}
}
@@ -616,11 +613,10 @@ public ScaffoldContext(
var suppressOnConfiguring = (bool)(args["suppressOnConfiguring"] ?? false);
var noPluralize = (bool)(args["noPluralize"] ?? false);
- Execute(
- () => executor.ScaffoldContextImpl(
- provider, connectionString, outputDir, outputDbContextDir, dbContextClassName,
- schemaFilters, tableFilters, modelNamespace, contextNamespace, useDataAnnotations,
- overwriteFiles, useDatabaseNames, suppressOnConfiguring, noPluralize));
+ Execute(() => executor.ScaffoldContextImpl(
+ provider, connectionString, outputDir, outputDbContextDir, dbContextClassName,
+ schemaFilters, tableFilters, modelNamespace, contextNamespace, useDataAnnotations,
+ overwriteFiles, useDatabaseNames, suppressOnConfiguring, noPluralize));
}
}
diff --git a/src/EFCore.Design/Extensions/ScaffoldingModelExtensions.cs b/src/EFCore.Design/Extensions/ScaffoldingModelExtensions.cs
index d984178aba0..36b229d0656 100644
--- a/src/EFCore.Design/Extensions/ScaffoldingModelExtensions.cs
+++ b/src/EFCore.Design/Extensions/ScaffoldingModelExtensions.cs
@@ -134,13 +134,12 @@ public static IEnumerable GetDataAnnotations(
tableNamedArgs.Add(nameof(TableAttribute.Schema), schema);
}
- yield return new AttributeCodeFragment(typeof(TableAttribute), new object?[] { tableName }, tableNamedArgs);
+ yield return new AttributeCodeFragment(typeof(TableAttribute), [tableName], tableNamedArgs);
}
foreach (var index in entityType.GetIndexes()
- .Where(
- i => ((IConventionIndex)i).GetConfigurationSource() != ConfigurationSource.Convention
- && i.IsHandledByDataAnnotations(annotationCodeGenerator)))
+ .Where(i => ((IConventionIndex)i).GetConfigurationSource() != ConfigurationSource.Convention
+ && i.IsHandledByDataAnnotations(annotationCodeGenerator)))
{
var indexArgs = new List();
var indexNamedArgs = new Dictionary();
@@ -632,8 +631,7 @@ public static IEnumerable GetDataAnnotations(
}
var valueGenerated = property.ValueGenerated;
- if (((IConventionProperty)property).GetValueGeneratedConfigurationSource() is ConfigurationSource
- valueGeneratedConfigurationSource
+ if (((IConventionProperty)property).GetValueGeneratedConfigurationSource() is { } valueGeneratedConfigurationSource
&& valueGeneratedConfigurationSource != ConfigurationSource.Convention
&& ValueGenerationConvention.GetValueGenerated(property) != valueGenerated)
{
diff --git a/src/EFCore.Design/Migrations/Design/CSharpMigrationsGenerator.cs b/src/EFCore.Design/Migrations/Design/CSharpMigrationsGenerator.cs
index 80222f83196..0dc7d93a83e 100644
--- a/src/EFCore.Design/Migrations/Design/CSharpMigrationsGenerator.cs
+++ b/src/EFCore.Design/Migrations/Design/CSharpMigrationsGenerator.cs
@@ -324,14 +324,13 @@ public override string GenerateSnapshot(
private bool HasMultidimensionalArray(IEnumerable operations)
{
- return operations.Any(
- o =>
- (o is InsertDataOperation insertDataOperation
- && IsMultidimensional(insertDataOperation.Values))
- || (o is UpdateDataOperation updateDataOperation
- && (IsMultidimensional(updateDataOperation.Values) || IsMultidimensional(updateDataOperation.KeyValues)))
- || (o is DeleteDataOperation deleteDataOperation
- && IsMultidimensional(deleteDataOperation.KeyValues)));
+ return operations.Any(o =>
+ (o is InsertDataOperation insertDataOperation
+ && IsMultidimensional(insertDataOperation.Values))
+ || (o is UpdateDataOperation updateDataOperation
+ && (IsMultidimensional(updateDataOperation.Values) || IsMultidimensional(updateDataOperation.KeyValues)))
+ || (o is DeleteDataOperation deleteDataOperation
+ && IsMultidimensional(deleteDataOperation.KeyValues)));
static bool IsMultidimensional(Array array)
=> array.GetLength(0) > 1 && array.GetLength(1) > 1;
diff --git a/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs b/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs
index 9c178755547..9938ce572ea 100644
--- a/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs
+++ b/src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs
@@ -92,17 +92,16 @@ protected virtual void GenerateEntityTypes(
GenerateEntityType(modelBuilderName, entityType, stringBuilder);
}
- foreach (var entityType in nonOwnedTypes.Where(
- e => e.GetDeclaredForeignKeys().Any()
- || e.GetDeclaredReferencingForeignKeys().Any(fk => fk.IsOwnership)))
+ foreach (var entityType in nonOwnedTypes.Where(e => e.GetDeclaredForeignKeys().Any()
+ || e.GetDeclaredReferencingForeignKeys().Any(fk => fk.IsOwnership)))
{
stringBuilder.AppendLine();
GenerateEntityTypeRelationships(modelBuilderName, entityType, stringBuilder);
}
- foreach (var entityType in nonOwnedTypes.Where(
- e => e.GetDeclaredNavigations().Any(n => n is { IsOnDependent: false, ForeignKey.IsOwnership: false })))
+ foreach (var entityType in nonOwnedTypes.Where(e
+ => e.GetDeclaredNavigations().Any(n => n is { IsOnDependent: false, ForeignKey.IsOwnership: false })))
{
stringBuilder.AppendLine();
@@ -131,7 +130,7 @@ protected virtual void GenerateEntityType(
{
entityTypeName = entityType.ClrType.DisplayName();
}
- else if (entityTypeName == ownership!.PrincipalEntityType.GetOwnedName(entityType.ShortName(), ownerNavigation))
+ else if (entityTypeName == ownership.PrincipalEntityType.GetOwnedName(entityType.ShortName(), ownerNavigation))
{
entityTypeName = entityType.ShortName();
}
@@ -514,7 +513,7 @@ protected virtual void GeneratePropertyAnnotations(
if (annotations.ContainsKey(RelationalAnnotationNames.DefaultValue)
&& property.TryGetDefaultValue(out var defaultValue)
&& defaultValue != DBNull.Value
- && FindValueConverter(property) is ValueConverter valueConverter)
+ && FindValueConverter(property) is { } valueConverter)
{
annotations[RelationalAnnotationNames.DefaultValue] = new Annotation(
RelationalAnnotationNames.DefaultValue,
@@ -661,13 +660,10 @@ protected virtual void GenerateComplexPropertyAnnotations(
var discriminatorValue = property.ComplexType.GetDiscriminatorValue();
if (discriminatorValue != null)
{
- if (discriminatorProperty != null)
+ var valueConverter = FindValueConverter(discriminatorProperty);
+ if (valueConverter != null)
{
- var valueConverter = FindValueConverter(discriminatorProperty);
- if (valueConverter != null)
- {
- discriminatorValue = valueConverter.ConvertToProvider(discriminatorValue);
- }
+ discriminatorValue = valueConverter.ConvertToProvider(discriminatorValue);
}
stringBuilder
@@ -718,10 +714,9 @@ protected virtual void GenerateKeys(
if (primaryKey?.DeclaringEntityType.IsOwned() != true)
{
- foreach (var key in keys.Where(
- key => key != primaryKey
- && (!key.GetReferencingForeignKeys().Any()
- || key.GetAnnotations().Any(a => a.Name != RelationalAnnotationNames.UniqueConstraintMappings))))
+ foreach (var key in keys.Where(key => key != primaryKey
+ && (!key.GetReferencingForeignKeys().Any()
+ || key.GetAnnotations().Any(a => a.Name != RelationalAnnotationNames.UniqueConstraintMappings))))
{
GenerateKey(entityTypeBuilderName, key, stringBuilder);
}
@@ -986,13 +981,10 @@ protected virtual void GenerateEntityTypeAnnotations(
if (discriminatorValueAnnotation?.Value != null)
{
var value = discriminatorValueAnnotation.Value;
- if (discriminatorProperty != null)
+ var valueConverter = FindValueConverter(discriminatorProperty);
+ if (valueConverter != null)
{
- var valueConverter = FindValueConverter(discriminatorProperty);
- if (valueConverter != null)
- {
- value = valueConverter.ConvertToProvider(value);
- }
+ value = valueConverter.ConvertToProvider(value);
}
stringBuilder
@@ -1016,17 +1008,17 @@ private void GenerateTableMapping(
IndentedStringBuilder stringBuilder,
Dictionary annotations)
{
- annotations.TryGetAndRemove(RelationalAnnotationNames.TableName, out IAnnotation tableNameAnnotation);
+ annotations.TryGetAndRemove(RelationalAnnotationNames.TableName, out IAnnotation? tableNameAnnotation);
var table = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table);
var tableName = (string?)tableNameAnnotation?.Value ?? table?.Name;
- annotations.TryGetAndRemove(RelationalAnnotationNames.Schema, out IAnnotation schemaAnnotation);
+ annotations.TryGetAndRemove(RelationalAnnotationNames.Schema, out IAnnotation? schemaAnnotation);
var schema = (string?)schemaAnnotation?.Value ?? table?.Schema;
- annotations.TryGetAndRemove(RelationalAnnotationNames.IsTableExcludedFromMigrations, out IAnnotation isExcludedAnnotation);
+ annotations.TryGetAndRemove(RelationalAnnotationNames.IsTableExcludedFromMigrations, out IAnnotation? isExcludedAnnotation);
var isExcludedFromMigrations = (isExcludedAnnotation?.Value as bool?) == true;
- annotations.TryGetAndRemove(RelationalAnnotationNames.Comment, out IAnnotation commentAnnotation);
+ annotations.TryGetAndRemove(RelationalAnnotationNames.Comment, out IAnnotation? commentAnnotation);
var comment = (string?)commentAnnotation?.Value;
var hasTriggers = entityType.GetDeclaredTriggers().Any(t => t.GetTableName() == tableName! && t.GetTableSchema() == schema);
@@ -1112,7 +1104,7 @@ private void GenerateTableMapping(
{
stringBuilder
.AppendLine()
- .AppendLine($"t.{nameof(TableBuilder.HasComment)}({Code.Literal(comment!)});");
+ .AppendLine($"t.{nameof(TableBuilder.HasComment)}({Code.Literal(comment)});");
}
if (hasTriggers)
@@ -1177,8 +1169,8 @@ private void GenerateViewMapping(
IndentedStringBuilder stringBuilder,
Dictionary annotations)
{
- annotations.TryGetAndRemove(RelationalAnnotationNames.ViewName, out IAnnotation viewNameAnnotation);
- annotations.TryGetAndRemove(RelationalAnnotationNames.ViewSchema, out IAnnotation viewSchemaAnnotation);
+ annotations.TryGetAndRemove(RelationalAnnotationNames.ViewName, out IAnnotation? viewNameAnnotation);
+ annotations.TryGetAndRemove(RelationalAnnotationNames.ViewSchema, out IAnnotation? viewSchemaAnnotation);
annotations.Remove(RelationalAnnotationNames.ViewDefinitionSql);
var view = StoreObjectIdentifier.Create(entityType, StoreObjectType.View);
@@ -1435,7 +1427,7 @@ protected virtual void GenerateTriggerAnnotations(
.FilterIgnoredAnnotations(trigger.GetAnnotations())
.ToDictionary(a => a.Name, a => a);
- if (annotations.TryGetAndRemove(RelationalAnnotationNames.Name, out IAnnotation nameAnnotation))
+ if (annotations.TryGetAndRemove(RelationalAnnotationNames.Name, out IAnnotation? nameAnnotation))
{
stringBuilder
.AppendLine()
@@ -1876,7 +1868,7 @@ private void GenerateFluentApiForMaxLength(
IProperty property,
IndentedStringBuilder stringBuilder)
{
- if (property.GetMaxLength() is int maxLength)
+ if (property.GetMaxLength() is { } maxLength)
{
stringBuilder
.AppendLine()
@@ -1892,7 +1884,7 @@ private void GenerateFluentApiForPrecisionAndScale(
IProperty property,
IndentedStringBuilder stringBuilder)
{
- if (property.GetPrecision() is int precision)
+ if (property.GetPrecision() is { } precision)
{
stringBuilder
.AppendLine()
@@ -1901,7 +1893,7 @@ private void GenerateFluentApiForPrecisionAndScale(
.Append("(")
.Append(Code.Literal(precision));
- if (property.GetScale() is int scale)
+ if (property.GetScale() is { } scale)
{
if (scale != 0)
{
@@ -1919,7 +1911,7 @@ private void GenerateFluentApiForIsUnicode(
IProperty property,
IndentedStringBuilder stringBuilder)
{
- if (property.IsUnicode() is bool unicode)
+ if (property.IsUnicode() is { } unicode)
{
stringBuilder
.AppendLine()
@@ -2030,7 +2022,7 @@ private static string GetFullName(IReadOnlyEntityType entityType)
if (entityType.HasSharedClrType
&& entityTypeName
- == ownership!.PrincipalEntityType.GetOwnedName(
+ == ownership.PrincipalEntityType.GetOwnedName(
entityType.ClrType.ShortDisplayName(), ownership.PrincipalToDependent!.Name))
{
entityTypeName = entityType.ClrType.DisplayName();
diff --git a/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs b/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs
index e9c4c28173a..d1d53afdb56 100644
--- a/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs
+++ b/src/EFCore.Design/Migrations/Design/MigrationsBundle.cs
@@ -78,17 +78,16 @@ internal static void Configure(CommandLineApplication app)
app.HandleResponseFiles = true;
- app.OnExecute(
- args =>
- {
- Reporter.IsVerbose = verbose.HasValue();
- Reporter.NoColor = noColor.HasValue();
- Reporter.PrefixOutput = prefixOutput.HasValue();
+ app.OnExecute(args =>
+ {
+ Reporter.IsVerbose = verbose.HasValue();
+ Reporter.NoColor = noColor.HasValue();
+ Reporter.PrefixOutput = prefixOutput.HasValue();
- ExecuteInternal(args);
+ ExecuteInternal(args);
- return 0;
- });
+ return 0;
+ });
}
private static void ExecuteInternal(string[] args)
diff --git a/src/EFCore.Design/Migrations/Design/MigrationsCodeGenerator.cs b/src/EFCore.Design/Migrations/Design/MigrationsCodeGenerator.cs
index 6fdb07fc11f..16c7dbb5917 100644
--- a/src/EFCore.Design/Migrations/Design/MigrationsCodeGenerator.cs
+++ b/src/EFCore.Design/Migrations/Design/MigrationsCodeGenerator.cs
@@ -170,12 +170,11 @@ private static IEnumerable GetAnnotatables(IEnumerableThe model.
/// The namespaces.
protected virtual IEnumerable GetNamespaces(IModel model)
- => model.GetEntityTypes().SelectMany(
- e => GetNamespaces(e)
- .Concat(
- e.GetDeclaredComplexProperties().Any()
- ? Model.DefaultPropertyBagType.GetNamespaces()
- : Enumerable.Empty()))
+ => model.GetEntityTypes().SelectMany(e => GetNamespaces(e)
+ .Concat(
+ e.GetDeclaredComplexProperties().Any()
+ ? Model.DefaultPropertyBagType.GetNamespaces()
+ : []))
.Concat(GetAnnotationNamespaces(GetAnnotatables(model)));
private IEnumerable GetNamespaces(ITypeBase typeBase)
@@ -276,11 +275,10 @@ private static IEnumerable GetAnnotatables(IComplexProperty comple
}
private IEnumerable GetAnnotationNamespaces(IEnumerable items)
- => items.SelectMany(
- i => Dependencies.AnnotationCodeGenerator.FilterIgnoredAnnotations(i.GetAnnotations())
- .Where(a => a.Value != null)
- .Select(a => new { Annotatable = i, Annotation = a })
- .SelectMany(a => GetProviderType(a.Annotatable, a.Annotation.Value!.GetType()).GetNamespaces()));
+ => items.SelectMany(i => Dependencies.AnnotationCodeGenerator.FilterIgnoredAnnotations(i.GetAnnotations())
+ .Where(a => a.Value != null)
+ .Select(a => new { Annotatable = i, Annotation = a })
+ .SelectMany(a => GetProviderType(a.Annotatable, a.Annotation.Value!.GetType()).GetNamespaces()));
private ValueConverter? FindValueConverter(IProperty property)
=> property.GetTypeMapping().Converter;
diff --git a/src/EFCore.Design/Migrations/Design/MigrationsScaffolder.cs b/src/EFCore.Design/Migrations/Design/MigrationsScaffolder.cs
index a64419911ad..648929011f1 100644
--- a/src/EFCore.Design/Migrations/Design/MigrationsScaffolder.cs
+++ b/src/EFCore.Design/Migrations/Design/MigrationsScaffolder.cs
@@ -270,8 +270,8 @@ public virtual MigrationFiles RemoveMigration(
var applied = false;
try
{
- applied = Dependencies.HistoryRepository.GetAppliedMigrations().Any(
- e => e.MigrationId.Equals(migration.GetId(), StringComparison.OrdinalIgnoreCase));
+ applied = Dependencies.HistoryRepository.GetAppliedMigrations().Any(e => e.MigrationId.Equals(
+ migration.GetId(), StringComparison.OrdinalIgnoreCase));
}
catch (Exception ex) when (force)
{
diff --git a/src/EFCore.Design/Migrations/Internal/SnapshotModelProcessor.cs b/src/EFCore.Design/Migrations/Internal/SnapshotModelProcessor.cs
index 30b89651e13..40bf9f2bb00 100644
--- a/src/EFCore.Design/Migrations/Internal/SnapshotModelProcessor.cs
+++ b/src/EFCore.Design/Migrations/Internal/SnapshotModelProcessor.cs
@@ -34,9 +34,8 @@ public SnapshotModelProcessor(
[
..typeof(RelationalAnnotationNames)
.GetRuntimeFields()
- .Where(
- p => p.Name != nameof(RelationalAnnotationNames.Prefix)
- && p.Name != nameof(RelationalAnnotationNames.AllNames))
+ .Where(p => p.Name != nameof(RelationalAnnotationNames.Prefix)
+ && p.Name != nameof(RelationalAnnotationNames.AllNames))
.Select(p => (string)p.GetValue(null)!)
.Where(v => v.IndexOf(':') > 0)
.Select(v => v[(RelationalAnnotationNames.Prefix.Length - 1)..])
diff --git a/src/EFCore.Design/Query/Internal/CSharpToLinqTranslator.cs b/src/EFCore.Design/Query/Internal/CSharpToLinqTranslator.cs
index c9668012c2d..a0f072c6ed5 100644
--- a/src/EFCore.Design/Query/Internal/CSharpToLinqTranslator.cs
+++ b/src/EFCore.Design/Query/Internal/CSharpToLinqTranslator.cs
@@ -69,7 +69,7 @@ INamedTypeSymbol GetTypeSymbolOrThrow(string fullyQualifiedMetadataName)
}
private readonly Stack> _parameterStack
- = new(new[] { ImmutableDictionary.Empty });
+ = new([ImmutableDictionary.Empty]);
private readonly Dictionary _dataFlowsIn = new(SymbolEqualityComparer.Default);
@@ -242,7 +242,7 @@ public override Expression VisitArrayCreationExpression(ArrayCreationExpressionS
}
var elementType = ResolveType(arrayTypeSymbol.ElementType);
- Check.DebugAssert(elementType is not null, "elementType is not null");
+ Check.DebugAssert(elementType is not null);
return arrayCreation.Initializer is null
? NewArrayBounds(elementType, Visit(arrayCreation.Type.RankSpecifiers[0].Sizes[0]))
@@ -278,7 +278,7 @@ public override Expression VisitBinaryExpression(BinaryExpressionSyntax binary)
=> Add(
left, right,
_stringConcatMethod ??=
- typeof(string).GetMethod(nameof(string.Concat), new[] { typeof(string), typeof(string) })),
+ typeof(string).GetMethod(nameof(string.Concat), [typeof(string), typeof(string)])),
SyntaxKind.AddExpression => Add(left, right),
SyntaxKind.SubtractExpression => Subtract(left, right),
@@ -374,11 +374,10 @@ public override Expression VisitElementAccessExpression(ElementAccessExpressionS
var property = visitedExpression.Type
.GetProperties()
.Select(p => new { Property = p, IndexParameters = p.GetIndexParameters() })
- .Where(
- t => t.IndexParameters.Length == arguments.Count
- && t.IndexParameters
- .Select(p => p.ParameterType)
- .SequenceEqual(arguments.Select(a => ResolveType(a.Expression))))
+ .Where(t => t.IndexParameters.Length == arguments.Count
+ && t.IndexParameters
+ .Select(p => p.ParameterType)
+ .SequenceEqual(arguments.Select(a => ResolveType(a.Expression))))
.Select(t => t.Property)
.FirstOrDefault();
@@ -484,7 +483,7 @@ public override Expression VisitImplicitArrayCreationExpression(ImplicitArrayCre
}
var elementType = ResolveType(arrayTypeSymbol.ElementType);
- Check.DebugAssert(elementType is not null, "elementType is not null");
+ Check.DebugAssert(elementType is not null);
var initializers = implicitArrayCreation.Initializer.Expressions.Select(e => Visit(e));
@@ -589,45 +588,44 @@ public override Expression VisitInvocationExpression(InvocationExpressionSyntax
var typeTypeParameterMap = new Dictionary(GetTypeTypeParameters(methodSymbol.ContainingType));
var definitionMethodInfos = declaringType.GetMethods()
- .Where(
- m =>
+ .Where(m =>
+ {
+ if (m.Name == methodSymbol.Name
+ && m.IsGenericMethodDefinition
+ && m.GetGenericArguments() is var candidateGenericArguments
+ && candidateGenericArguments.Length == originalDefinition.TypeParameters.Length
+ && m.GetParameters() is var candidateParams
+ && candidateParams.Length == originalDefinition.Parameters.Length)
{
- if (m.Name == methodSymbol.Name
- && m.IsGenericMethodDefinition
- && m.GetGenericArguments() is var candidateGenericArguments
- && candidateGenericArguments.Length == originalDefinition.TypeParameters.Length
- && m.GetParameters() is var candidateParams
- && candidateParams.Length == originalDefinition.Parameters.Length)
- {
- var methodTypeParameterMap = new Dictionary(typeTypeParameterMap);
+ var methodTypeParameterMap = new Dictionary(typeTypeParameterMap);
- // Prepare a dictionary that will be used to resolve generic type parameters (ITypeParameterSymbol) to the
- // corresponding reflection Type. This is needed to correctly (and recursively) resolve the type of parameters
- // below.
- foreach (var (symbol, type) in methodSymbol.TypeParameters.Zip(candidateGenericArguments))
+ // Prepare a dictionary that will be used to resolve generic type parameters (ITypeParameterSymbol) to the
+ // corresponding reflection Type. This is needed to correctly (and recursively) resolve the type of parameters
+ // below.
+ foreach (var (symbol, type) in methodSymbol.TypeParameters.Zip(candidateGenericArguments))
+ {
+ if (symbol.Name != type.Name)
{
- if (symbol.Name != type.Name)
- {
- return false;
- }
-
- methodTypeParameterMap[symbol.Name] = type;
+ return false;
}
- for (var i = 0; i < candidateParams.Length; i++)
+ methodTypeParameterMap[symbol.Name] = type;
+ }
+
+ for (var i = 0; i < candidateParams.Length; i++)
+ {
+ var translatedParamType = ResolveType(originalDefinition.Parameters[i].Type, methodTypeParameterMap);
+ if (translatedParamType != candidateParams[i].ParameterType)
{
- var translatedParamType = ResolveType(originalDefinition.Parameters[i].Type, methodTypeParameterMap);
- if (translatedParamType != candidateParams[i].ParameterType)
- {
- return false;
- }
+ return false;
}
-
- return true;
}
- return false;
- }).ToArray();
+ return true;
+ }
+
+ return false;
+ }).ToArray();
if (definitionMethodInfos.Length != 1)
{
@@ -732,7 +730,7 @@ IEnumerable> GetTypeTypeParameters(INamedTypeSymbol t
{
// TODO: We match Roslyn type parameters by name, not sure that's right; also for the method's generic type parameters
- if (typeSymbol.ContainingType is INamedTypeSymbol containingTypeSymbol)
+ if (typeSymbol.ContainingType is { } containingTypeSymbol)
{
foreach (var kvp in GetTypeTypeParameters(containingTypeSymbol))
{
@@ -744,8 +742,7 @@ IEnumerable> GetTypeTypeParameters(INamedTypeSymbol t
var genericArguments = type.GetGenericArguments();
Check.DebugAssert(
- genericArguments.Length == typeSymbol.TypeParameters.Length,
- "genericArguments.Length == typeSymbol.TypeParameters.Length");
+ genericArguments.Length == typeSymbol.TypeParameters.Length);
foreach (var (typeParamSymbol, typeParamType) in typeSymbol.TypeParameters.Zip(genericArguments))
{
@@ -761,7 +758,7 @@ IEnumerable> GetTypeTypeParameters(INamedTypeSymbol t
/// doing so can result in application failures when updating to a new Entity Framework Core release.
///
public override Expression VisitLiteralExpression(LiteralExpressionSyntax literal)
- => _semanticModel.GetTypeInfo(literal) is { ConvertedType: ITypeSymbol type }
+ => _semanticModel.GetTypeInfo(literal) is { ConvertedType: { } type }
? Constant(literal.Token.Value, ResolveType(type))
: Constant(literal.Token.Value);
@@ -775,7 +772,7 @@ public override Expression VisitMemberAccessExpression(MemberAccessExpressionSyn
{
var expression = Visit(memberAccess.Expression);
- if (_semanticModel.GetSymbolInfo(memberAccess).Symbol is not ISymbol memberSymbol)
+ if (_semanticModel.GetSymbolInfo(memberAccess).Symbol is not { } memberSymbol)
{
throw new InvalidOperationException($"MemberAccess: Couldn't find symbol for member: {memberAccess}");
}
@@ -835,7 +832,7 @@ public override Expression VisitObjectCreationExpression(ObjectCreationExpressio
throw new InvalidOperationException($"ObjectCreation: couldn't find IMethodSymbol for constructor: {objectCreation}");
}
- Check.DebugAssert(constructorSymbol.MethodKind == MethodKind.Constructor, "constructorSymbol.MethodKind == MethodKind.Constructor");
+ Check.DebugAssert(constructorSymbol.MethodKind == MethodKind.Constructor);
var type = ResolveType(constructorSymbol.ContainingType);
@@ -846,7 +843,7 @@ public override Expression VisitObjectCreationExpression(ObjectCreationExpressio
var newExpression = constructor is not null
? New(
constructor,
- objectCreation.ArgumentList?.Arguments.Select(a => Visit(a)) ?? Array.Empty())
+ objectCreation.ArgumentList?.Arguments.Select(a => Visit(a)) ?? [])
: parameterTypes.Length == 0 // For structs, there's no actual parameterless constructor
? New(type)
: throw new InvalidOperationException($"ObjectCreation: Missing constructor: {objectCreation}");
@@ -861,33 +858,32 @@ public override Expression VisitObjectCreationExpression(ObjectCreationExpressio
case { Expressions: [AssignmentExpressionSyntax, ..] }:
return MemberInit(
newExpression,
- objectCreation.Initializer.Expressions.Select(
- e =>
+ objectCreation.Initializer.Expressions.Select(e =>
+ {
+ if (e is not AssignmentExpressionSyntax { Left: var lValue, Right: var value })
{
- if (e is not AssignmentExpressionSyntax { Left: var lValue, Right: var value })
- {
- throw new NotSupportedException(
- $"ObjectCreation: non-assignment initializer expression of type '{e.GetType().Name}': {objectCreation}");
- }
+ throw new NotSupportedException(
+ $"ObjectCreation: non-assignment initializer expression of type '{e.GetType().Name}': {objectCreation}");
+ }
- var lValueSymbol = _semanticModel.GetSymbolInfo(lValue).Symbol;
- var memberInfo = lValueSymbol switch
- {
- IPropertySymbol p => (MemberInfo?)type.GetProperty(p.Name),
- IFieldSymbol f => type.GetField(f.Name),
+ var lValueSymbol = _semanticModel.GetSymbolInfo(lValue).Symbol;
+ var memberInfo = lValueSymbol switch
+ {
+ IPropertySymbol p => (MemberInfo?)type.GetProperty(p.Name),
+ IFieldSymbol f => type.GetField(f.Name),
- _ => throw new InvalidOperationException(
- $"ObjectCreation: unsupported initializer for member of type '{lValueSymbol?.GetType().Name}': {e}")
- };
+ _ => throw new InvalidOperationException(
+ $"ObjectCreation: unsupported initializer for member of type '{lValueSymbol?.GetType().Name}': {e}")
+ };
- if (memberInfo is null)
- {
- throw new InvalidOperationException(
- $"ObjectCreation: couldn't find initialized member '{lValueSymbol.Name}': {e}");
- }
+ if (memberInfo is null)
+ {
+ throw new InvalidOperationException(
+ $"ObjectCreation: couldn't find initialized member '{lValueSymbol.Name}': {e}");
+ }
- return Bind(memberInfo, Visit(value));
- }));
+ return Bind(memberInfo, Visit(value));
+ }));
// Non-assignment initializer => list initializer (new List { 1, 2, 3 })
default:
@@ -1083,8 +1079,8 @@ private Expression VisitLambdaExpression(AnonymousFunctionExpressionSyntax lambd
_parameterStack.Push(
_parameterStack.Peek()
.AddRange(
- translatedParameters.Select(
- p => new KeyValuePair(p.Name ?? throw new NotImplementedException(), p))));
+ translatedParameters.Select(p
+ => new KeyValuePair(p.Name ?? throw new NotImplementedException(), p))));
try
{
diff --git a/src/EFCore.Design/Query/Internal/LinqToCSharpSyntaxTranslator.cs b/src/EFCore.Design/Query/Internal/LinqToCSharpSyntaxTranslator.cs
index 50292001598..897d600b4c1 100644
--- a/src/EFCore.Design/Query/Internal/LinqToCSharpSyntaxTranslator.cs
+++ b/src/EFCore.Design/Query/Internal/LinqToCSharpSyntaxTranslator.cs
@@ -13,6 +13,8 @@
using Microsoft.EntityFrameworkCore.Design.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+using Attribute = System.Attribute;
+using ConditionalExpression = System.Linq.Expressions.ConditionalExpression;
namespace Microsoft.EntityFrameworkCore.Query.Internal;
@@ -149,8 +151,8 @@ protected virtual SyntaxNode TranslateCore(
Check.DebugAssert(_stack.Count == 1, "_parameterStack.Count == 1");
Check.DebugAssert(_stack.Peek().Variables.Count == 0, "_stack.Peek().Parameters.Count == 0");
Check.DebugAssert(_stack.Peek().VariableNames.Count == 0, "_stack.Peek().ParameterNames.Count == 0");
- Check.DebugAssert(_stack.Peek().Labels.Count == 0, "_stack.Peek().Labels.Count == 0");
- Check.DebugAssert(_stack.Peek().UniqueLabelNames.Count == 0, "_stack.Peek().UniqueLabelNames.Count == 0");
+ Check.DebugAssert(_stack.Peek().Labels.Count == 0);
+ Check.DebugAssert(_stack.Peek().UniqueLabelNames.Count == 0);
foreach (var unsafeAccessor in _fieldUnsafeAccessors.Values.Concat(_methodUnsafeAccessors.Values))
{
@@ -551,7 +553,7 @@ protected override Expression VisitBlock(BlockExpression block)
// We're on the last line of a block in expression context - the block is being lifted out.
// All statements before the last line (this one) have already been added to _liftedStatements, just return the last
// expression.
- Check.DebugAssert(onLastBlockLine, "onLastBlockLine");
+ Check.DebugAssert(onLastBlockLine);
Result = translated;
break;
}
@@ -639,9 +641,8 @@ protected override Expression VisitBlock(BlockExpression block)
// But there may still be variables that get assigned inside nested blocks or other situations; prepare declarations for those
// and either add them to the block, or lift them if we're an expression block.
var unassignedVariableDeclarations =
- unassignedVariables.Select(
- v => (LocalDeclarationStatementSyntax)_g.LocalDeclarationStatement(
- Generate(v.Type), LookupVariableName(v), initializer: _g.DefaultExpression(Generate(v.Type))));
+ unassignedVariables.Select(v => (LocalDeclarationStatementSyntax)_g.LocalDeclarationStatement(
+ Generate(v.Type), LookupVariableName(v), initializer: _g.DefaultExpression(Generate(v.Type))));
if (blockContext == ExpressionContext.Expression)
{
@@ -660,7 +661,7 @@ protected override Expression VisitBlock(BlockExpression block)
if (ownStackFrame is not null)
{
var popped = _stack.Pop();
- Check.DebugAssert(popped.Equals(ownStackFrame), "popped.Equals(ownStackFrame)");
+ Check.DebugAssert(popped.Equals(ownStackFrame));
}
_onLastLambdaLine = parentOnLastLambdaLine;
@@ -758,7 +759,7 @@ protected virtual SyntaxNode TranslateCatchBlock(CatchBlock catchBlock, bool noT
if (catchBlock.Variable is not null)
{
- Check.DebugAssert(catchDeclaration is not null, "catchDeclaration is not null");
+ Check.DebugAssert(catchDeclaration is not null);
if (catchBlock.Variable.Name is null)
{
@@ -808,7 +809,8 @@ protected virtual CSharpSyntaxNode TranslateConditional(
if (isFalseAbsent)
{
throw new NotSupportedException(
- $"Missing {nameof(System.Linq.Expressions.ConditionalExpression.IfFalse)} in {nameof(System.Linq.Expressions.ConditionalExpression)} in expression context");
+ $"Missing {nameof(ConditionalExpression.IfFalse)} in "
+ + "{nameof(System.Linq.Expressions.ConditionalExpression)} in expression context");
}
var parentLiftedState = _liftedState;
@@ -1116,7 +1118,7 @@ ExpressionSyntax HandleEnum(Enum e)
}
var components = formatted.Split(", ");
- Check.DebugAssert(components.Length > 0, "components.Length > 0");
+ Check.DebugAssert(components.Length > 0);
return components.Aggregate(
(ExpressionSyntax?)null,
@@ -1499,7 +1501,7 @@ protected override Expression VisitLambda(Expression lambda)
if (_liftedState.Statements.Count > 0)
{
- Check.DebugAssert(lambda.ReturnType != typeof(void), "lambda.ReturnType != typeof(void)");
+ Check.DebugAssert(lambda.ReturnType != typeof(void));
if (expressionBody != null)
{
@@ -1527,14 +1529,13 @@ protected override Expression VisitLambda(Expression lambda)
returnType: lambda.ReturnType == typeof(void) || !TryGenerate(lambda.ReturnType, out var returnSyntax) ? null : returnSyntax,
ParameterList(
SeparatedList(
- lambda.Parameters.Select(
- p => Parameter(Identifier(LookupVariableName(p)))
- .WithType(p.Type.IsAnonymousType() ? null : Generate(p.Type))))),
+ lambda.Parameters.Select(p => Parameter(Identifier(LookupVariableName(p)))
+ .WithType(p.Type.IsAnonymousType() ? null : Generate(p.Type))))),
blockBody,
expressionBody);
var popped = _stack.Pop();
- Check.DebugAssert(popped.Equals(stackFrame), "popped.Equals(stackFrame)");
+ Check.DebugAssert(popped.Equals(stackFrame));
_onLastLambdaLine = parentOnLastLambdaLine;
@@ -1609,7 +1610,7 @@ protected override Expression VisitMember(MemberExpression member)
case { Member: FieldInfo closureField, Expression: ConstantExpression constantExpression }
when constantExpression.Type.Attributes.HasFlag(TypeAttributes.NestedPrivate)
- && System.Attribute.IsDefined(constantExpression.Type, typeof(CompilerGeneratedAttribute), inherit: true):
+ && Attribute.IsDefined(constantExpression.Type, typeof(CompilerGeneratedAttribute), inherit: true):
// Unwrap closure
VisitConstant(Expression.Constant(closureField.GetValue(constantExpression.Value), member.Type));
break;
@@ -1749,7 +1750,7 @@ private MethodDeclarationSyntax GetUnsafeAccessorDeclaration(MemberInfo member,
_stringBuilder.Clear().Append("UnsafeAccessor_");
- if (member.DeclaringType?.Namespace?.Replace(".", "_") is string typeNamespace)
+ if (member.DeclaringType?.Namespace?.Replace(".", "_") is { } typeNamespace)
{
_stringBuilder.Append(typeNamespace).Append('_');
}
@@ -1812,10 +1813,9 @@ private MethodDeclarationSyntax GetUnsafeAccessorDeclaration(MemberInfo member,
[
_g.ParameterDeclaration("instance", Generate(member.DeclaringType)),
.. method.GetParameters()
- .Select(
- p => _g.ParameterDeclaration(
- p.Name ?? throw new UnreachableException("Missing parameter name"),
- Generate(p.ParameterType)))
+ .Select(p => _g.ParameterDeclaration(
+ p.Name ?? throw new UnreachableException("Missing parameter name"),
+ Generate(p.ParameterType)))
]);
unsafeAccessorDeclaration =
@@ -1841,10 +1841,9 @@ .. method.GetParameters()
modifiers: DeclarationModifiers.Static | DeclarationModifiers.Extern,
returnType: Generate(member.DeclaringType),
parameters: constructor.GetParameters()
- .Select(
- p => _g.ParameterDeclaration(
- p.Name ?? throw new UnreachableException("Missing parameter name"),
- Generate(p.ParameterType))));
+ .Select(p => _g.ParameterDeclaration(
+ p.Name ?? throw new UnreachableException("Missing parameter name"),
+ Generate(p.ParameterType))));
unsafeAccessorDeclaration =
(MethodDeclarationSyntax)_g.AddAttributes(
@@ -1959,7 +1958,7 @@ protected override Expression VisitMethodCall(MethodCallExpression call)
// If the member isn't declared on the same type as the expression, (e.g. explicit interface implementation), add
// a cast up to the declaring type.
- { Method.DeclaringType: Type declaringType, Object.Type: Type objectType, } when declaringType != objectType
+ { Method.DeclaringType: { } declaringType, Object.Type: var objectType, } when declaringType != objectType
=> ParenthesizedExpression(CastExpression(Generate(declaringType), Translate(call.Object))),
_ => Translate(call.Object)
@@ -2016,13 +2015,14 @@ void ProcessType(Type type)
}
}
- static bool IsNull(ExpressionSyntax expr) => expr switch
- {
- LiteralExpressionSyntax literal when literal.IsKind(SyntaxKind.NullLiteralExpression) => true,
- CastExpressionSyntax cast => IsNull(cast.Expression),
- ParenthesizedExpressionSyntax parenthesized => IsNull(parenthesized.Expression),
- _ => false
- };
+ static bool IsNull(ExpressionSyntax expr)
+ => expr switch
+ {
+ LiteralExpressionSyntax literal when literal.IsKind(SyntaxKind.NullLiteralExpression) => true,
+ CastExpressionSyntax cast => IsNull(cast.Expression),
+ ParenthesizedExpressionSyntax parenthesized => IsNull(parenthesized.Expression),
+ _ => false
+ };
}
///
@@ -2044,7 +2044,7 @@ protected override Expression VisitNewArray(NewArrayExpression newArray)
return newArray;
}
- Check.DebugAssert(newArray.NodeType == ExpressionType.NewArrayInit, "newArray.NodeType == ExpressionType.NewArrayInit");
+ Check.DebugAssert(newArray.NodeType == ExpressionType.NewArrayInit);
Result = _g.ArrayCreationExpression(elementType, expressions);
@@ -2069,9 +2069,8 @@ protected override Expression VisitNew(NewExpression node)
Result = AnonymousObjectCreationExpression(
SeparatedList(
- arguments.Select(
- (arg, i) =>
- AnonymousObjectMemberDeclarator(NameEquals(node.Members[i].Name), arg.Expression))
+ arguments.Select((arg, i) =>
+ AnonymousObjectMemberDeclarator(NameEquals(node.Members[i].Name), arg.Expression))
.ToArray()));
return node;
@@ -2079,7 +2078,7 @@ protected override Expression VisitNew(NewExpression node)
// If the constructor isn't public, or it has required properties and the constructor doesn't have [SetsRequiredMembers], we can't
// just generate a regular instantiation expression (won't compile). Generate an unsafe accessor instead.
- if (node.Constructor is ConstructorInfo constructor
+ if (node.Constructor is { } constructor
&& (!constructor.IsPublic
|| node.Type.GetCustomAttribute() is not null
&& constructor.GetCustomAttribute() is null))
@@ -2167,11 +2166,10 @@ protected virtual CSharpSyntaxNode TranslateSwitch(SwitchExpression switchNode,
_liftedState = parentLiftedState.CreateChild();
var cases = List(
- switchNode.Cases.Select(
- c => SwitchSection(
- labels: List(
- c.TestValues.Select(tv => CaseSwitchLabel(Translate(tv)))),
- statements: ProcessArmBody(c.Body))));
+ switchNode.Cases.Select(c => SwitchSection(
+ labels: List(
+ c.TestValues.Select(tv => CaseSwitchLabel(Translate(tv)))),
+ statements: ProcessArmBody(c.Body))));
// LINQ SwitchExpression supports non-literal labels, which C# does not support. This rewrites the switch as a series of
// nested ConditionalExpressions.
@@ -2262,11 +2260,10 @@ SyntaxList ProcessArmBody(Expression body)
}
var cases = List(
- switchNode.Cases.Select(
- c => SwitchSection(
- labels: List(
- c.TestValues.Select(tv => CaseSwitchLabel(Translate(tv)))),
- statements: ProcessArmBody(c.Body)))
+ switchNode.Cases.Select(c => SwitchSection(
+ labels: List(
+ c.TestValues.Select(tv => CaseSwitchLabel(Translate(tv)))),
+ statements: ProcessArmBody(c.Body)))
.Append(
SwitchSection(
SingletonList(DefaultSwitchLabel()),
@@ -2381,8 +2378,7 @@ protected override Expression VisitTry(TryExpression tryNode)
if (tryNode.Fault is not null)
{
Check.DebugAssert(
- tryNode.Finally is null && tryNode.Handlers.Count == 0,
- "tryNode.Finally is null && tryNode.Handlers.Count == 0");
+ tryNode.Finally is null && tryNode.Handlers.Count == 0);
Result = _g.TryCatchStatement(
translatedBody,
@@ -2577,7 +2573,7 @@ protected override Expression VisitListInit(ListInitExpression listInit)
///
protected override ElementInit VisitElementInit(ElementInit elementInit)
{
- Check.DebugAssert(elementInit.Arguments.Count == 1, "elementInit.Arguments.Count == 1");
+ Check.DebugAssert(elementInit.Arguments.Count == 1);
Visit(elementInit.Arguments.Single());
@@ -2604,12 +2600,11 @@ protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBind
InitializerExpression(
SyntaxKind.ObjectInitializerExpression,
SeparatedList(
- memberMemberBinding.Bindings.Select(
- b =>
- {
- VisitMemberBinding(b);
- return (ExpressionSyntax)Result!;
- }))));
+ memberMemberBinding.Bindings.Select(b =>
+ {
+ VisitMemberBinding(b);
+ return (ExpressionSyntax)Result!;
+ }))));
return memberMemberBinding;
}
@@ -2623,12 +2618,11 @@ protected override MemberListBinding VisitMemberListBinding(MemberListBinding me
InitializerExpression(
SyntaxKind.CollectionInitializerExpression,
SeparatedList(
- memberListBinding.Initializers.Select(
- i =>
- {
- VisitElementInit(i);
- return (ExpressionSyntax)Result!;
- }))));
+ memberListBinding.Initializers.Select(i =>
+ {
+ VisitElementInit(i);
+ return (ExpressionSyntax)Result!;
+ }))));
return memberListBinding;
}
@@ -2685,7 +2679,7 @@ private ArgumentSyntax[] TranslateMethodArguments(ParameterInfo[] parameters, IR
private ExpressionSyntax[] TranslateList(IReadOnlyList list)
{
- Check.DebugAssert(_context == ExpressionContext.Expression, "_context == ExpressionContext.Expression");
+ Check.DebugAssert(_context == ExpressionContext.Expression);
var translatedList = new ExpressionSyntax[list.Count];
var lastLiftedArgumentPosition = 0;
diff --git a/src/EFCore.Design/Query/Internal/PrecompiledQueryCodeGenerator.cs b/src/EFCore.Design/Query/Internal/PrecompiledQueryCodeGenerator.cs
index d11cf7f07f2..954e7218fea 100644
--- a/src/EFCore.Design/Query/Internal/PrecompiledQueryCodeGenerator.cs
+++ b/src/EFCore.Design/Query/Internal/PrecompiledQueryCodeGenerator.cs
@@ -173,7 +173,7 @@ public virtual IReadOnlyList GeneratePrecompiledQueries(
var penultimateOperator = terminatingOperator switch
{
// This is needed e.g. for GetEnumerator(), DbSet.AsAsyncEnumerable (non-static terminating operators)
- { Object: Expression @object } => @object,
+ { Object: { } @object } => @object,
{ Arguments: [var sourceArgument, ..] } => sourceArgument,
_ => throw new UnreachableException()
};
@@ -284,13 +284,12 @@ public virtual IReadOnlyList GeneratePrecompiledQueries(
]);
foreach (var ns in _namespaces
- .OrderBy(
- ns => ns switch
- {
- _ when ns.StartsWith("System.", StringComparison.Ordinal) => 10,
- _ when ns.StartsWith("Microsoft.", StringComparison.Ordinal) => 9,
- _ => 0
- })
+ .OrderBy(ns => ns switch
+ {
+ _ when ns.StartsWith("System.", StringComparison.Ordinal) => 10,
+ _ when ns.StartsWith("Microsoft.", StringComparison.Ordinal) => 9,
+ _ => 0
+ })
.ThenBy(ns => ns))
{
_code.Append("using ").Append(ns).AppendLine(";");
@@ -398,7 +397,7 @@ private void GenerateOperatorInterceptorsRecursively(
var nestedOperatorExpression = operatorMethodCall switch
{
// This is needed e.g. for GetEnumerator(), DbSet.AsAsyncEnumerable (non-static terminating operators)
- { Object: Expression @object } => @object,
+ { Object: { } @object } => @object,
{ Arguments: [var sourceArgument, ..] } => sourceArgument,
_ => throw new UnreachableException()
};
@@ -489,10 +488,9 @@ private void GenerateOperatorInterceptor(
IArrayTypeSymbol arrayTypeSymbol => arrayTypeSymbol.ElementType,
INamedTypeSymbol namedReturnType2
when namedReturnType2.AllInterfaces.Prepend(namedReturnType2)
- .Any(
- i => i.OriginalDefinition.Equals(_symbols.GenericEnumerable, SymbolEqualityComparer.Default)
- || i.OriginalDefinition.Equals(_symbols.GenericAsyncEnumerable, SymbolEqualityComparer.Default)
- || i.OriginalDefinition.Equals(_symbols.GenericEnumerator, SymbolEqualityComparer.Default))
+ .Any(i => i.OriginalDefinition.Equals(_symbols.GenericEnumerable, SymbolEqualityComparer.Default)
+ || i.OriginalDefinition.Equals(_symbols.GenericAsyncEnumerable, SymbolEqualityComparer.Default)
+ || i.OriginalDefinition.Equals(_symbols.GenericEnumerator, SymbolEqualityComparer.Default))
=> namedReturnType2.TypeArguments[0],
_ => null
};
@@ -767,7 +765,8 @@ or nameof(EntityFrameworkQueryableExtensions.ExecuteUpdateAsync),
// If there were captured variables, generate code to evaluate and build the same NewArrayExpression at runtime,
// and then fall through to the normal logic, generating variable extractors against that NewArrayExpression
// (local var) instead of against the method argument.
- code.AppendLine($"""
+ code.AppendLine(
+ $"""
var setterBuilder = new UpdateSettersBuilder<{sourceElementTypeName}>();
{parameterName}(setterBuilder);
var setters = setterBuilder.BuildSettersExpression();
@@ -854,7 +853,8 @@ void GenerateCapturedVariableExtractors(
{
code
.Append('"').Append(capturedVariablesPathTree.ParameterName!).AppendLine("\",")
- .AppendLine($"Expression.Lambda>(Expression.Convert({roslynPathSegment}, typeof(object)))")
+ .AppendLine(
+ $"Expression.Lambda>(Expression.Convert({roslynPathSegment}, typeof(object)))")
.AppendLine(".Compile(preferInterpretation: true)")
.AppendLine(".Invoke());");
}
@@ -869,8 +869,7 @@ void GenerateCapturedVariableExtractors(
// side we have a query root (i.e. not the MethodCallExpression for the FromSql(), but rather its evaluated result)
case FromSqlQueryRootExpression fromSqlQueryRoot:
{
- if (_funcletizer.CalculatePathsToEvaluatableRoots(fromSqlQueryRoot.Argument) is not ExpressionTreeFuncletizer.PathNode
- evaluatableRootPaths)
+ if (_funcletizer.CalculatePathsToEvaluatableRoots(fromSqlQueryRoot.Argument) is not { } evaluatableRootPaths)
{
// There are no captured variables in this FromSqlQueryRootExpression, skip it.
break;
@@ -1134,7 +1133,7 @@ or nameof(EntityFrameworkQueryableExtensions.ToListAsync)
_ => terminatingOperator switch
{
// This is needed e.g. for GetEnumerator(), DbSet.AsAsyncEnumerable (non-static terminating operators)
- { Object: Expression }
+ { Object: not null }
=> terminatingOperator.Update(penultimateOperator, terminatingOperator.Arguments),
{ Arguments: [_, ..] }
=> terminatingOperator.Update(@object: null, [penultimateOperator, .. terminatingOperator.Arguments.Skip(1)]),
@@ -1183,8 +1182,7 @@ private static NewArrayExpression ProcessExecuteUpdate(MethodCallExpression exec
},
Arguments:
[
- UnaryExpression { NodeType: ExpressionType.Quote, Operand: LambdaExpression propertySelector },
- Expression valueSelector
+ UnaryExpression { NodeType: ExpressionType.Quote, Operand: LambdaExpression propertySelector }, { } valueSelector
]
} methodCallExpression
&& methodCallExpression.Method.DeclaringType.GetGenericTypeDefinition() == typeof(UpdateSettersBuilder<>))
diff --git a/src/EFCore.Design/Query/Internal/QueryLocator.cs b/src/EFCore.Design/Query/Internal/QueryLocator.cs
index 4e30a445f55..72b47450ab6 100644
--- a/src/EFCore.Design/Query/Internal/QueryLocator.cs
+++ b/src/EFCore.Design/Query/Internal/QueryLocator.cs
@@ -81,7 +81,7 @@ public virtual IReadOnlyList LocateQueries(
_cancellationToken = cancellationToken;
_semanticModel = _compilation.GetSemanticModel(syntaxTree);
- _locatedQueries = new List();
+ _locatedQueries = [];
_precompilationErrors = precompilationErrors;
Visit(syntaxTree.GetRoot(cancellationToken));
diff --git a/src/EFCore.Design/Query/Internal/RuntimeModelLinqToCSharpSyntaxTranslator.cs b/src/EFCore.Design/Query/Internal/RuntimeModelLinqToCSharpSyntaxTranslator.cs
index 06ef309ed3d..e8a0c1bbd11 100644
--- a/src/EFCore.Design/Query/Internal/RuntimeModelLinqToCSharpSyntaxTranslator.cs
+++ b/src/EFCore.Design/Query/Internal/RuntimeModelLinqToCSharpSyntaxTranslator.cs
@@ -104,7 +104,7 @@ protected override void TranslateNonPublicMemberAccess(MemberExpression memberEx
AddNamespace(methodName.Namespace);
Result = InvocationExpression(
IdentifierName(methodName.Name),
- ArgumentList(SeparatedList(new[] { Argument(Translate(memberExpression.Expression)) })));
+ ArgumentList(SeparatedList([Argument(Translate(memberExpression.Expression))])));
}
else
{
@@ -139,11 +139,10 @@ protected override void TranslateNonPublicMemberAssignment(
IdentifierName(methodName.Name),
ArgumentList(
SeparatedList(
- new[]
- {
- Argument(Translate(memberExpression.Expression)),
- Argument(Translate(value))
- })));
+ [
+ Argument(Translate(memberExpression.Expression)),
+ Argument(Translate(value))
+ ])));
}
else
{
@@ -151,7 +150,7 @@ protected override void TranslateNonPublicMemberAssignment(
assignmentKind,
InvocationExpression(
IdentifierName(methodName.Name),
- ArgumentList(SeparatedList(new[] { Argument(Translate(memberExpression.Expression)) }))),
+ ArgumentList(SeparatedList([Argument(Translate(memberExpression.Expression))]))),
Translate(value));
}
}
diff --git a/src/EFCore.Design/Scaffolding/Internal/CSharpRuntimeModelCodeGenerator.cs b/src/EFCore.Design/Scaffolding/Internal/CSharpRuntimeModelCodeGenerator.cs
index 8415a2c8052..07dbde06d0b 100644
--- a/src/EFCore.Design/Scaffolding/Internal/CSharpRuntimeModelCodeGenerator.cs
+++ b/src/EFCore.Design/Scaffolding/Internal/CSharpRuntimeModelCodeGenerator.cs
@@ -1312,7 +1312,8 @@ private void Create(
private void Create(IElementType elementType, bool typeMappingSet, CSharpRuntimeAnnotationCodeGeneratorParameters parameters)
{
var mainBuilder = parameters.MainBuilder;
- var elementVariableName = _code.Identifier(parameters.TargetName + "ElementType", elementType, parameters.ScopeObjects, capitalize: false);
+ var elementVariableName = _code.Identifier(
+ parameters.TargetName + "ElementType", elementType, parameters.ScopeObjects, capitalize: false);
var elementParameters = parameters with { TargetName = elementVariableName };
mainBuilder
@@ -1447,7 +1448,7 @@ private void SetValueComparer(
{
var mainBuilder = parameters.MainBuilder;
var valueComparerType = valueComparer.GetType();
- if (valueComparer is IInfrastructure { Instance: ValueComparer underlyingValueComparer }
+ if (valueComparer is IInfrastructure { Instance: var underlyingValueComparer }
&& typeMappingComparer == underlyingValueComparer
&& valueComparerType.GetDeclaredConstructor([typeof(ValueComparer)]) != null)
{
@@ -1517,14 +1518,17 @@ private void
.AppendLines(
_code.Expression(
getClrValueUsingContainingEntityExpression, parameters.Namespaces, unsafeAccessors,
- (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements), skipFinalNewline: true)
+ (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements),
+ skipFinalNewline: true)
.AppendLine(",")
.AppendLines(
_code.Expression(
hasSentinelValueUsingContainingEntityExpression, parameters.Namespaces, unsafeAccessors,
- (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements), skipFinalNewline: true)
+ (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements),
+ skipFinalNewline: true)
.AppendLine(",");
}
+
mainBuilder
.AppendLines(
_code.Expression(
@@ -1549,9 +1553,11 @@ private void
.AppendLines(
_code.Expression(
setterUsingContainingEntityExpression, parameters.Namespaces, unsafeAccessors,
- (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements), skipFinalNewline: true)
+ (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements),
+ skipFinalNewline: true)
.AppendLine(",");
}
+
mainBuilder
.AppendLines(
_code.Expression(
@@ -1560,7 +1566,8 @@ private void
.AppendLine(");")
.DecrementIndent();
- ClrPropertyMaterializationSetterFactory.Instance.Create(property, out var materializationSetterUsingContainingEntityExpression, out var materializationSetterExpression);
+ ClrPropertyMaterializationSetterFactory.Instance.Create(
+ property, out var materializationSetterUsingContainingEntityExpression, out var materializationSetterExpression);
mainBuilder
.Append(variableName).AppendLine(".SetMaterializationSetter(")
@@ -1571,9 +1578,11 @@ private void
.AppendLines(
_code.Expression(
materializationSetterUsingContainingEntityExpression, parameters.Namespaces, unsafeAccessors,
- (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements), skipFinalNewline: true)
+ (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements),
+ skipFinalNewline: true)
.AppendLine(",");
}
+
mainBuilder
.AppendLines(
_code.Expression(
@@ -1596,22 +1605,26 @@ private void
.AppendLines(
_code.Expression(
get!, parameters.Namespaces, unsafeAccessors,
- (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements), skipFinalNewline: true)
+ (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements),
+ skipFinalNewline: true)
.AppendLine(",")
.AppendLines(
_code.Expression(
set!, parameters.Namespaces, unsafeAccessors,
- (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements), skipFinalNewline: true)
+ (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements),
+ skipFinalNewline: true)
.AppendLine(",")
.AppendLines(
_code.Expression(
setForMaterialization!, parameters.Namespaces, unsafeAccessors,
- (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements), skipFinalNewline: true)
+ (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements),
+ skipFinalNewline: true)
.AppendLine(",")
.AppendLines(
_code.Expression(
createCollection!, parameters.Namespaces, unsafeAccessors,
- (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements), skipFinalNewline: true)
+ (IReadOnlyDictionary)parameters.ScopeVariables, memberAccessReplacements),
+ skipFinalNewline: true)
.AppendLine(");")
.DecrementIndent();
}
@@ -3023,8 +3036,7 @@ private static void CreateAnnotations(
annotatable,
parameters with
{
- Annotations = annotatable.GetRuntimeAnnotations().ToDictionary(a => a.Name, a => a.Value),
- IsRuntime = true
+ Annotations = annotatable.GetRuntimeAnnotations().ToDictionary(a => a.Name, a => a.Value), IsRuntime = true
});
}
diff --git a/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs b/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs
index 4813ef420f6..4b78e52a29b 100644
--- a/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs
+++ b/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs
@@ -185,8 +185,7 @@ protected virtual ModelBuilder VisitDatabaseModel(ModelBuilder modelBuilder, Dat
VisitForeignKeys(modelBuilder, databaseModel.Tables.SelectMany(table => table.ForeignKeys).ToList());
modelBuilder.Model.AddAnnotations(
- databaseModel.GetAnnotations().Where(
- a => a.Name != ScaffoldingAnnotationNames.ConnectionString));
+ databaseModel.GetAnnotations().Where(a => a.Name != ScaffoldingAnnotationNames.ConnectionString));
return modelBuilder;
}
@@ -503,9 +502,8 @@ protected virtual EntityTypeBuilder VisitColumns(EntityTypeBuilder builder, ICol
property.Metadata.SetColumnOrder(column.Table.Columns.IndexOf(column));
property.Metadata.AddAnnotations(
- column.GetAnnotations().Where(
- a => a.Name != ScaffoldingAnnotationNames.ConcurrencyToken
- && a.Name != ScaffoldingAnnotationNames.ClrType));
+ column.GetAnnotations().Where(a => a.Name != ScaffoldingAnnotationNames.ConcurrencyToken
+ && a.Name != ScaffoldingAnnotationNames.ClrType));
return property;
}
@@ -814,8 +812,7 @@ protected virtual ModelBuilder VisitForeignKeys(
}
var principalPropertiesMap = foreignKey.PrincipalColumns
- .Select(
- fc => (property: principalEntityType.FindProperty(GetPropertyName(fc))!, column: fc)).ToList();
+ .Select(fc => (property: principalEntityType.FindProperty(GetPropertyName(fc))!, column: fc)).ToList();
var principalProperties = principalPropertiesMap
.Select(tuple => tuple.property)
.ToList();
diff --git a/src/EFCore.Design/Scaffolding/Internal/TextTemplatingEngineHost.cs b/src/EFCore.Design/Scaffolding/Internal/TextTemplatingEngineHost.cs
index 8a78e882446..db5732d36c0 100644
--- a/src/EFCore.Design/Scaffolding/Internal/TextTemplatingEngineHost.cs
+++ b/src/EFCore.Design/Scaffolding/Internal/TextTemplatingEngineHost.cs
@@ -55,10 +55,10 @@ public virtual ITextTemplatingSession Session
/// 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 IList StandardAssemblyReferences { get; } = new[]
- {
+ public virtual IList StandardAssemblyReferences { get; } =
+ [
typeof(ITextTemplatingEngineHost).Assembly.Location, typeof(CompilerErrorCollection).Assembly.Location
- };
+ ];
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -66,7 +66,7 @@ public virtual ITextTemplatingSession Session
/// 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 IList StandardImports { get; } = new[] { "System" };
+ public virtual IList StandardImports { get; } = ["System"];
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
diff --git a/src/EFCore.Design/build/net10.0/Microsoft.EntityFrameworkCore.Design.props b/src/EFCore.Design/build/net10.0/Microsoft.EntityFrameworkCore.Design.props
index affac16f65b..4969df90e3d 100644
--- a/src/EFCore.Design/build/net10.0/Microsoft.EntityFrameworkCore.Design.props
+++ b/src/EFCore.Design/build/net10.0/Microsoft.EntityFrameworkCore.Design.props
@@ -2,4 +2,4 @@
True
-
+
\ No newline at end of file
diff --git a/src/EFCore.InMemory/Extensions/InMemoryServiceCollectionExtensions.cs b/src/EFCore.InMemory/Extensions/InMemoryServiceCollectionExtensions.cs
index d3d50a93eb0..11d0208a0f5 100644
--- a/src/EFCore.InMemory/Extensions/InMemoryServiceCollectionExtensions.cs
+++ b/src/EFCore.InMemory/Extensions/InMemoryServiceCollectionExtensions.cs
@@ -49,13 +49,12 @@ public static IServiceCollection AddEntityFrameworkInMemoryDatabase(this IServic
.TryAdd()
.TryAdd()
.TryAdd(p => p.GetRequiredService())
- .TryAddProviderSpecificServices(
- b => b
- .TryAddSingleton()
- .TryAddScoped()
- .TryAddSingleton()
- .TryAddSingleton()
- .TryAddScoped());
+ .TryAddProviderSpecificServices(b => b
+ .TryAddSingleton()
+ .TryAddScoped()
+ .TryAddSingleton()
+ .TryAddSingleton()
+ .TryAddScoped());
builder.TryAddCoreServices();
diff --git a/src/EFCore.InMemory/Metadata/Conventions/InMemoryConventionSetBuilder.cs b/src/EFCore.InMemory/Metadata/Conventions/InMemoryConventionSetBuilder.cs
index 7bfad928af8..f53c7ebeec6 100644
--- a/src/EFCore.InMemory/Metadata/Conventions/InMemoryConventionSetBuilder.cs
+++ b/src/EFCore.InMemory/Metadata/Conventions/InMemoryConventionSetBuilder.cs
@@ -76,10 +76,9 @@ private static IServiceScope CreateServiceScope()
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
- .AddDbContext(
- (p, o) =>
- o.UseInMemoryDatabase(Guid.NewGuid().ToString())
- .UseInternalServiceProvider(p))
+ .AddDbContext((p, o) =>
+ o.UseInMemoryDatabase(Guid.NewGuid().ToString())
+ .UseInternalServiceProvider(p))
.BuildServiceProvider();
return serviceProvider.GetRequiredService().CreateScope();
diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs
index 9ccba1f9659..fdc860cdc25 100644
--- a/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs
+++ b/src/EFCore.InMemory/Query/Internal/InMemoryExpressionTranslatingExpressionVisitor.cs
@@ -3,6 +3,7 @@
using System.Collections;
using System.Diagnostics.CodeAnalysis;
+using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
@@ -369,8 +370,7 @@ private static bool TryUseComparer(
foreach (var candidate in comparer
.GetType()
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
- .Where(
- m => m.Name == "Equals" && m.GetParameters().Length == 2)
+ .Where(m => m.Name == "Equals" && m.GetParameters().Length == 2)
.ToList())
{
var parameters = candidate.GetParameters();
@@ -553,7 +553,7 @@ protected override Expression VisitMember(MemberExpression memberExpression)
return QueryCompilationContext.NotTranslatedExpression;
}
- if (TryBindMember(innerExpression, MemberIdentity.Create(memberExpression.Member), memberExpression.Type) is Expression result)
+ if (TryBindMember(innerExpression, MemberIdentity.Create(memberExpression.Member), memberExpression.Type) is { } result)
{
return result;
}
@@ -928,7 +928,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp
// Null-compensate any extension method where the 'this' argument is a reference type
// (in theory should do this for value types as well, but that's more complicated as the expression type needs to be changed etc.)
if (methodCallExpression is { Object: null, Method: { IsStatic: true } staticMethod }
- && staticMethod.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), inherit: false)
+ && staticMethod.IsDefined(typeof(ExtensionAttribute), inherit: false)
&& arguments is [{ Type.IsValueType: false } instance, ..])
{
return Expression.Condition(
@@ -1206,7 +1206,7 @@ private static Expression ProcessSingleResultScalar(
var valueBufferVariable = Expression.Variable(typeof(ValueBuffer));
var readExpression = valueBufferVariable.CreateValueBufferReadValueExpression(type, index: 0, property: null);
return Expression.Block(
- variables: new[] { valueBufferVariable },
+ variables: [valueBufferVariable],
Expression.Assign(valueBufferVariable, serverQuery),
Expression.Condition(
Expression.MakeMemberAccess(valueBufferVariable, ValueBufferIsEmpty),
@@ -1366,11 +1366,10 @@ private bool TryRewriteEntityEquality(
}
result = Visit(
- primaryKeyProperties1.Select(
- p =>
- Expression.MakeBinary(
- nodeType, CreatePropertyAccessExpression(nonNullEntityReference, p),
- Expression.Constant(null, p.ClrType.MakeNullable())))
+ primaryKeyProperties1.Select(p =>
+ Expression.MakeBinary(
+ nodeType, CreatePropertyAccessExpression(nonNullEntityReference, p),
+ Expression.Constant(null, p.ClrType.MakeNullable())))
.Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.OrElse(l, r) : Expression.AndAlso(l, r)));
return true;
@@ -1418,16 +1417,14 @@ private bool TryRewriteEntityEquality(
}
result = Visit(
- primaryKeyProperties.Select(
- p =>
- Expression.MakeBinary(
- nodeType,
- CreatePropertyAccessExpression(left, p),
- CreatePropertyAccessExpression(right, p)))
- .Aggregate(
- (l, r) => nodeType == ExpressionType.Equal
- ? Expression.AndAlso(l, r)
- : Expression.OrElse(l, r)));
+ primaryKeyProperties.Select(p =>
+ Expression.MakeBinary(
+ nodeType,
+ CreatePropertyAccessExpression(left, p),
+ CreatePropertyAccessExpression(right, p)))
+ .Aggregate((l, r) => nodeType == ExpressionType.Equal
+ ? Expression.AndAlso(l, r)
+ : Expression.OrElse(l, r)));
return true;
}
@@ -1459,8 +1456,8 @@ when methodCallExpression.Method.GetGenericMethodDefinition() == GetParameterVal
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.Type.IsNullableType()
? memberAssignment.Expression
: Expression.Convert(memberAssignment.Expression, property.ClrType.MakeNullable());
@@ -1519,8 +1516,8 @@ private static bool CanEvaluate(Expression expression)
case MemberInitExpression memberInitExpression:
return CanEvaluate(memberInitExpression.NewExpression)
- && memberInitExpression.Bindings.All(
- mb => mb is MemberAssignment memberAssignment && CanEvaluate(memberAssignment.Expression));
+ && memberInitExpression.Bindings.All(mb
+ => mb is MemberAssignment memberAssignment && CanEvaluate(memberAssignment.Expression));
default:
return false;
@@ -1719,7 +1716,7 @@ public Expression Convert(Type type)
}
return StructuralType is IEntityType entityType
- && entityType.GetDerivedTypes().FirstOrDefault(et => et.ClrType == type) is IEntityType derivedEntityType
+ && entityType.GetDerivedTypes().FirstOrDefault(et => et.ClrType == type) is { } derivedEntityType
? new StructuralTypeReferenceExpression(this, derivedEntityType)
: QueryCompilationContext.NotTranslatedExpression;
}
diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs b/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs
index ba7120441e1..7fb56232687 100644
--- a/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs
+++ b/src/EFCore.InMemory/Query/Internal/InMemoryQueryExpression.cs
@@ -76,10 +76,9 @@ public InMemoryQueryExpression(IEntityType entityType)
foreach (var derivedEntityType in entityType.GetDerivedTypes())
{
var entityCheck = derivedEntityType.GetConcreteDerivedTypesInclusive()
- .Select(
- e => keyValueComparer.ExtractEqualsBody(
- propertyExpressionsMap[discriminatorProperty],
- Constant(e.GetDiscriminatorValue(), discriminatorProperty.ClrType)))
+ .Select(e => keyValueComparer.ExtractEqualsBody(
+ propertyExpressionsMap[discriminatorProperty],
+ Constant(e.GetDiscriminatorValue(), discriminatorProperty.ClrType)))
.Aggregate((l, r) => OrElse(l, r));
foreach (var property in derivedEntityType.GetDeclaredProperties())
@@ -469,19 +468,20 @@ public virtual void ApplyDefaultIfEmpty()
ServerQueryExpression,
Constant(new ValueBuffer(Enumerable.Repeat((object?)null, _projectionMappingExpressions.Count).ToArray())));
- ReplaceProjection(_projectionMapping.ToDictionary(
- kv => kv.Key,
- kv => kv.Value switch
- {
- EntityProjectionExpression p => MakeEntityProjectionNullable(p),
+ ReplaceProjection(
+ _projectionMapping.ToDictionary(
+ kv => kv.Key,
+ kv => kv.Value switch
+ {
+ EntityProjectionExpression p => MakeEntityProjectionNullable(p),
- var p when !p.Type.IsNullableType()
- => Coalesce(
- MakeReadValueNullable(p),
- p.Type.GetDefaultValueConstant()),
+ var p when !p.Type.IsNullableType()
+ => Coalesce(
+ MakeReadValueNullable(p),
+ p.Type.GetDefaultValueConstant()),
- var p => p
- }));
+ var p => p
+ }));
}
///
@@ -667,8 +667,8 @@ public virtual StructuralTypeShaperExpression AddNavigationToWeakEntityType(
var outerParameter = Parameter(typeof(ValueBuffer), "outer");
var innerParameter = Parameter(typeof(ValueBuffer), "inner");
var replacingVisitor = new ReplacingExpressionVisitor(
- new Expression[] { CurrentParameter, innerQueryExpression.CurrentParameter },
- new Expression[] { outerParameter, innerParameter });
+ [CurrentParameter, innerQueryExpression.CurrentParameter],
+ [outerParameter, innerParameter]);
var selectorExpressions = _projectionMappingExpressions.Select(e => replacingVisitor.Visit(e)).ToList();
var outerIndex = selectorExpressions.Count;
@@ -912,8 +912,8 @@ private Expression AddJoin(
var outerParameter = Parameter(typeof(ValueBuffer), "outer");
var innerParameter = Parameter(typeof(ValueBuffer), "inner");
var replacingVisitor = new ReplacingExpressionVisitor(
- new Expression[] { CurrentParameter, innerQueryExpression.CurrentParameter },
- new Expression[] { outerParameter, innerParameter });
+ [CurrentParameter, innerQueryExpression.CurrentParameter],
+ [outerParameter, innerParameter]);
int outerIndex;
if (outerClientEval)
@@ -1030,23 +1030,22 @@ private Expression AddJoin(
New(
ValueBufferConstructor, NewArrayInit(
typeof(object),
- resultSelectorExpressions.Select(
- (e, i) =>
+ resultSelectorExpressions.Select((e, i) =>
+ {
+ var expression = replacingVisitor.Visit(e);
+ if (innerNullable
+ && i > outerIndex)
+ {
+ expression = MakeReadValueNullable(expression);
+ }
+
+ if (expression.Type.IsValueType)
{
- var expression = replacingVisitor.Visit(e);
- if (innerNullable
- && i > outerIndex)
- {
- expression = MakeReadValueNullable(expression);
- }
-
- if (expression.Type.IsValueType)
- {
- expression = Convert(expression, typeof(object));
- }
-
- return expression;
- }))),
+ expression = Convert(expression, typeof(object));
+ }
+
+ return expression;
+ }))),
outerParameter,
innerParameter);
@@ -1116,7 +1115,7 @@ private Expression AddJoin(
return New(
transparentIdentifierType.GetTypeInfo().DeclaredConstructors.Single(),
- new[] { outerShaperExpression, innerShaperExpression }, outerMemberInfo, innerMemberInfo);
+ [outerShaperExpression, innerShaperExpression], outerMemberInfo, innerMemberInfo);
static Expression MakeNullable(Expression expression, bool nullable)
=> nullable
diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs
index a64883aaf3f..8a5af0166fb 100644
--- a/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs
+++ b/src/EFCore.InMemory/Query/Internal/InMemoryQueryableMethodTranslatingExpressionVisitor.cs
@@ -383,8 +383,8 @@ private static ShapedQueryExpression CreateShapedQueryExpressionStatic(IEntityTy
var original2 = resultSelector.Parameters[1];
var newResultSelectorBody = new ReplacingExpressionVisitor(
- new Expression[] { original1, original2 },
- new[] { groupByShaper.KeySelector, groupByShaper }).Visit(resultSelector.Body);
+ [original1, original2],
+ [groupByShaper.KeySelector, groupByShaper]).Visit(resultSelector.Body);
newResultSelectorBody = ExpandSharedTypeEntities(inMemoryQueryExpression, newResultSelectorBody);
var newShaper = _projectionBindingExpressionVisitor.Translate(inMemoryQueryExpression, newResultSelectorBody);
@@ -1162,12 +1162,14 @@ protected override Expression VisitMember(MemberExpression memberExpression)
{
// Fold member access into conditional, i.e. transform
// (test ? expr1 : expr2).Member -> (test ? expr1.Member : expr2.Member)
- if (memberExpression.Expression is ConditionalExpression cond) {
- return Visit(Expression.Condition(
- cond.Test,
- Expression.MakeMemberAccess(cond.IfTrue, memberExpression.Member),
- Expression.MakeMemberAccess(cond.IfFalse, memberExpression.Member)
- ));
+ if (memberExpression.Expression is ConditionalExpression cond)
+ {
+ return Visit(
+ Expression.Condition(
+ cond.Test,
+ Expression.MakeMemberAccess(cond.IfTrue, memberExpression.Member),
+ Expression.MakeMemberAccess(cond.IfFalse, memberExpression.Member)
+ ));
}
var innerExpression = Visit(memberExpression.Expression);
@@ -1183,7 +1185,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp
source = Visit(source);
return TryExpand(source, MemberIdentity.Create(navigationName))
- ?? methodCallExpression.Update(null!, new[] { source, methodCallExpression.Arguments[1] });
+ ?? methodCallExpression.Update(null!, [source, methodCallExpression.Arguments[1]]);
}
return base.VisitMethodCall(methodCallExpression);
@@ -1264,13 +1266,12 @@ protected override Expression VisitExtension(Expression extensionExpression)
? Expression.AndAlso(
outerKey is NewArrayExpression newArrayExpression
? newArrayExpression.Expressions
- .Select(
- e =>
- {
- var left = (e as UnaryExpression)?.Operand ?? e;
+ .Select(e =>
+ {
+ var left = (e as UnaryExpression)?.Operand ?? e;
- return Expression.NotEqual(left, Expression.Constant(null, left.Type));
- })
+ return Expression.NotEqual(left, Expression.Constant(null, left.Type));
+ })
.Aggregate((l, r) => Expression.AndAlso(l, r))
: Expression.NotEqual(outerKey, Expression.Constant(null, outerKey.Type)),
keyComparison)
@@ -1341,7 +1342,7 @@ private ShapedQueryExpression TranslateTwoParameterSelector(ShapedQueryExpressio
var replacement2 = AccessField(transparentIdentifierType, transparentIdentifierParameter, "Inner");
var newResultSelector = Expression.Lambda(
new ReplacingExpressionVisitor(
- new[] { original1, original2 }, new[] { replacement1, replacement2 })
+ [original1, original2], [replacement1, replacement2])
.Visit(resultSelector.Body),
transparentIdentifierParameter);
diff --git a/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.ShaperExpressionProcessingExpressionVisitor.cs b/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.ShaperExpressionProcessingExpressionVisitor.cs
index 7f435655384..0a7c964f4f6 100644
--- a/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.ShaperExpressionProcessingExpressionVisitor.cs
+++ b/src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.ShaperExpressionProcessingExpressionVisitor.cs
@@ -215,7 +215,7 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression)
= queryExpression.GetProjection(projectionBindingExpression).GetConstantValue>();
var updatedExpression = newExpression.Update(
- new[] { Constant(ValueBuffer.Empty), newExpression.Arguments[1] });
+ [Constant(ValueBuffer.Empty), newExpression.Arguments[1]]);
return MakeBinary(ExpressionType.Assign, binaryExpression.Left, updatedExpression);
}
diff --git a/src/EFCore.InMemory/Storage/Internal/InMemoryStoreProvider.cs b/src/EFCore.InMemory/Storage/Internal/InMemoryStoreProvider.cs
index 0f8ea7b1ced..7ccaac07cad 100644
--- a/src/EFCore.InMemory/Storage/Internal/InMemoryStoreProvider.cs
+++ b/src/EFCore.InMemory/Storage/Internal/InMemoryStoreProvider.cs
@@ -24,7 +24,10 @@ public class InMemoryStoreProvider : IInMemoryStoreProvider
/// 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 InMemoryStoreProvider(IDbContextOptions options, IInMemoryDatabaseRootCache databaseRootCache, IInMemoryTableFactory tableFactory)
+ public InMemoryStoreProvider(
+ IDbContextOptions options,
+ IInMemoryDatabaseRootCache databaseRootCache,
+ IInMemoryTableFactory tableFactory)
{
_options = options;
_databaseRootCache = databaseRootCache;
diff --git a/src/EFCore.InMemory/Storage/Internal/InMemoryTable.cs b/src/EFCore.InMemory/Storage/Internal/InMemoryTable.cs
index fb3b097285f..c5a3d5a6750 100644
--- a/src/EFCore.InMemory/Storage/Internal/InMemoryTable.cs
+++ b/src/EFCore.InMemory/Storage/Internal/InMemoryTable.cs
@@ -385,7 +385,7 @@ private static bool IsNullable(IProperty property)
private static bool IsNullable(IComplexProperty property)
=> property.IsNullable
- ||( property.DeclaringType is IComplexType complexType
+ || (property.DeclaringType is IComplexType complexType
&& IsNullable(complexType.ComplexProperty));
private void ThrowNullabilityErrorException(
@@ -399,14 +399,14 @@ private void ThrowNullabilityErrorException(
nullabilityErrors.Format(),
entry.EntityType.DisplayName(),
entry.BuildCurrentValuesString(entry.EntityType.FindPrimaryKey()!.Properties)),
- new[] { entry });
+ [entry]);
}
throw new DbUpdateException(
InMemoryStrings.NullabilityErrorException(
nullabilityErrors.Format(),
entry.EntityType.DisplayName()),
- new[] { entry });
+ [entry]);
}
///
@@ -432,8 +432,7 @@ protected virtual void ThrowUpdateConcurrencyException(
"{"
+ string.Join(
", ",
- concurrencyConflicts.Select(
- c => c.Key.Name + ": " + Convert.ToString(c.Value, CultureInfo.InvariantCulture)))
+ concurrencyConflicts.Select(c => c.Key.Name + ": " + Convert.ToString(c.Value, CultureInfo.InvariantCulture)))
+ "}"),
entries)
: new DbUpdateConcurrencyException(
diff --git a/src/EFCore.Proxies/Proxies/Internal/IProxyLazyLoader.cs b/src/EFCore.Proxies/Proxies/Internal/IProxyLazyLoader.cs
index 442d9360b63..8c3295364e1 100644
--- a/src/EFCore.Proxies/Proxies/Internal/IProxyLazyLoader.cs
+++ b/src/EFCore.Proxies/Proxies/Internal/IProxyLazyLoader.cs
@@ -20,7 +20,6 @@ public interface IProxyLazyLoader
/// 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.
///
- [IgnoreDataMember]
- [JsonIgnore]
+ [IgnoreDataMember, JsonIgnore]
ILazyLoader? LazyLoader { get; set; }
}
diff --git a/src/EFCore.Proxies/ProxiesServiceCollectionExtensions.cs b/src/EFCore.Proxies/ProxiesServiceCollectionExtensions.cs
index 3b3a0707893..31b0a872098 100644
--- a/src/EFCore.Proxies/ProxiesServiceCollectionExtensions.cs
+++ b/src/EFCore.Proxies/ProxiesServiceCollectionExtensions.cs
@@ -31,8 +31,7 @@ public static IServiceCollection AddEntityFrameworkProxies(
new EntityFrameworkServicesBuilder(serviceCollection)
.TryAdd()
.TryAdd()
- .TryAddProviderSpecificServices(
- b => b.TryAddSingleton());
+ .TryAddProviderSpecificServices(b => b.TryAddSingleton());
return serviceCollection;
}
diff --git a/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs b/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs
index f69dae85b38..b3c1718ea06 100644
--- a/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs
+++ b/src/EFCore.Relational/Design/AnnotationCodeGenerator.cs
@@ -3,7 +3,6 @@
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
-using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
#pragma warning disable EF1001 // Accessing annotation names (internal)
@@ -55,9 +54,8 @@ public AnnotationCodeGenerator(AnnotationCodeGeneratorDependencies dependencies)
///
public virtual IEnumerable FilterIgnoredAnnotations(IEnumerable annotations)
- => annotations.Where(
- a => !(CoreAnnotationNames.AllNames.Contains(a.Name)
- || IgnoredRelationalAnnotations.Contains(a.Name)));
+ => annotations.Where(a => !(CoreAnnotationNames.AllNames.Contains(a.Name)
+ || IgnoredRelationalAnnotations.Contains(a.Name)));
///
public virtual void RemoveAnnotationsHandledByConventions(IModel model, IDictionary annotations)
@@ -376,7 +374,8 @@ public virtual IReadOnlyList GenerateFluentApiCalls(
GenerateSimpleFluentApiCall(
annotations,
- RelationalAnnotationNames.JsonPropertyName, nameof(RelationalPropertyBuilderExtensions.HasJsonPropertyName), methodCallCodeFragments);
+ RelationalAnnotationNames.JsonPropertyName, nameof(RelationalPropertyBuilderExtensions.HasJsonPropertyName),
+ methodCallCodeFragments);
GenerateSimpleFluentApiCall(
annotations,
@@ -400,7 +399,8 @@ public virtual IReadOnlyList GenerateFluentApiCalls(
GenerateSimpleFluentApiCall(
annotations,
- RelationalAnnotationNames.JsonPropertyName, nameof(RelationalComplexPropertyBuilderExtensions.HasJsonPropertyName), methodCallCodeFragments);
+ RelationalAnnotationNames.JsonPropertyName, nameof(RelationalComplexPropertyBuilderExtensions.HasJsonPropertyName),
+ methodCallCodeFragments);
methodCallCodeFragments.AddRange(GenerateFluentApiCallsHelper(complexProperty, annotations, GenerateFluentApi));
@@ -1051,7 +1051,7 @@ private static void GenerateSimpleFluentApiCall(
if (annotations.TryGetValue(annotationName, out var annotation))
{
annotations.Remove(annotationName);
- if (annotation.Value is object annotationValue)
+ if (annotation.Value is { } annotationValue)
{
methodCallCodeFragments.Add(
new MethodCallCodeFragment(method, annotationValue));
diff --git a/src/EFCore.Relational/Design/Internal/RelationalCSharpRuntimeAnnotationCodeGenerator.cs b/src/EFCore.Relational/Design/Internal/RelationalCSharpRuntimeAnnotationCodeGenerator.cs
index a521fa01210..ed97fd13171 100644
--- a/src/EFCore.Relational/Design/Internal/RelationalCSharpRuntimeAnnotationCodeGenerator.cs
+++ b/src/EFCore.Relational/Design/Internal/RelationalCSharpRuntimeAnnotationCodeGenerator.cs
@@ -66,7 +66,7 @@ public override void Generate(IModel model, CSharpRuntimeAnnotationCodeGenerator
if (annotations.TryGetAndRemove(
RelationalAnnotationNames.DbFunctions,
- out IReadOnlyDictionary functions))
+ out IReadOnlyDictionary? functions))
{
parameters.Namespaces.Add(typeof(Dictionary<,>).Namespace!);
parameters.Namespaces.Add(typeof(BindingFlags).Namespace!);
@@ -85,7 +85,7 @@ public override void Generate(IModel model, CSharpRuntimeAnnotationCodeGenerator
if (annotations.TryGetAndRemove(
RelationalAnnotationNames.Sequences,
- out IReadOnlyDictionary<(string, string?), ISequence> sequences))
+ out IReadOnlyDictionary<(string, string?), ISequence>? sequences))
{
parameters.Namespaces.Add(typeof(Dictionary<,>).Namespace!);
var sequencesVariable = Dependencies.CSharpHelper.Identifier(
@@ -1611,7 +1611,7 @@ private void Create(
AddNamespace(method.DeclaringType!, parameters.Namespaces);
mainBuilder.AppendLine(",")
.AppendLine($"methodInfo: {code.Literal(method.DeclaringType!)}.GetMethod(").IncrementIndent()
- .Append(code.Literal(method.Name!)).AppendLine(",")
+ .Append(code.Literal(method.Name)).AppendLine(",")
.Append(method.IsPublic ? "BindingFlags.Public" : "BindingFlags.NonPublic")
.Append(method.IsStatic ? " | BindingFlags.Static" : " | BindingFlags.Instance")
.AppendLine(" | BindingFlags.DeclaredOnly,")
@@ -1825,7 +1825,7 @@ public override void Generate(IEntityType entityType, CSharpRuntimeAnnotationCod
if (annotations.TryGetAndRemove(
RelationalAnnotationNames.MappingFragments,
- out IReadOnlyStoreObjectDictionary fragments))
+ out IReadOnlyStoreObjectDictionary? fragments))
{
AddNamespace(typeof(StoreObjectDictionary), parameters.Namespaces);
AddNamespace(typeof(StoreObjectIdentifier), parameters.Namespaces);
@@ -1845,7 +1845,7 @@ public override void Generate(IEntityType entityType, CSharpRuntimeAnnotationCod
if (annotations.TryGetAndRemove(
RelationalAnnotationNames.InsertStoredProcedure,
- out StoredProcedure insertStoredProcedure))
+ out StoredProcedure? insertStoredProcedure))
{
var sprocVariable = Dependencies.CSharpHelper.Identifier(
"insertSproc", insertStoredProcedure, parameters.ScopeObjects, capitalize: false);
@@ -1858,7 +1858,7 @@ public override void Generate(IEntityType entityType, CSharpRuntimeAnnotationCod
if (annotations.TryGetAndRemove(
RelationalAnnotationNames.DeleteStoredProcedure,
- out StoredProcedure deleteStoredProcedure))
+ out StoredProcedure? deleteStoredProcedure))
{
var sprocVariable = Dependencies.CSharpHelper.Identifier(
"deleteSproc", deleteStoredProcedure, parameters.ScopeObjects, capitalize: false);
@@ -1871,7 +1871,7 @@ public override void Generate(IEntityType entityType, CSharpRuntimeAnnotationCod
if (annotations.TryGetAndRemove(
RelationalAnnotationNames.UpdateStoredProcedure,
- out StoredProcedure updateStoredProcedure))
+ out StoredProcedure? updateStoredProcedure))
{
var sprocVariable = Dependencies.CSharpHelper.Identifier(
"updateSproc", updateStoredProcedure, parameters.ScopeObjects, capitalize: false);
@@ -2087,7 +2087,7 @@ public override void Generate(IProperty property, CSharpRuntimeAnnotationCodeGen
if (annotations.TryGetAndRemove(
RelationalAnnotationNames.RelationalOverrides,
- out IReadOnlyStoreObjectDictionary tableOverrides))
+ out IReadOnlyStoreObjectDictionary? tableOverrides))
{
AddNamespace(typeof(StoreObjectDictionary), parameters.Namespaces);
AddNamespace(typeof(StoreObjectIdentifier), parameters.Namespaces);
diff --git a/src/EFCore.Relational/Diagnostics/RelationalLoggerExtensions.cs b/src/EFCore.Relational/Diagnostics/RelationalLoggerExtensions.cs
index acecc79ca01..08913cc8397 100644
--- a/src/EFCore.Relational/Diagnostics/RelationalLoggerExtensions.cs
+++ b/src/EFCore.Relational/Diagnostics/RelationalLoggerExtensions.cs
@@ -3144,18 +3144,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()));
+ 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()));
}
///
@@ -3242,18 +3241,17 @@ private static string ForeignKeyPropertiesMappedToUnrelatedTables(EventDefinitio
{
var d = (FallbackEventDefinition)definition;
var p = (ForeignKeyEventData)payload;
- return d.GenerateMessage(
- l => l.Log(
- d.Level,
- d.EventId,
- d.MessageFormat,
- p.ForeignKey.Properties.Format(),
- p.ForeignKey.DeclaringEntityType.DisplayName(),
- p.ForeignKey.PrincipalEntityType.DisplayName(),
- p.ForeignKey.Properties.Format(),
- p.ForeignKey.DeclaringEntityType.GetSchemaQualifiedTableName(),
- p.ForeignKey.PrincipalKey.Properties.Format(),
- p.ForeignKey.PrincipalEntityType.GetSchemaQualifiedTableName()));
+ return d.GenerateMessage(l => l.Log(
+ d.Level,
+ d.EventId,
+ d.MessageFormat,
+ p.ForeignKey.Properties.Format(),
+ p.ForeignKey.DeclaringEntityType.DisplayName(),
+ p.ForeignKey.PrincipalEntityType.DisplayName(),
+ p.ForeignKey.Properties.Format(),
+ p.ForeignKey.DeclaringEntityType.GetSchemaQualifiedTableName(),
+ p.ForeignKey.PrincipalKey.Properties.Format(),
+ p.ForeignKey.PrincipalEntityType.GetSchemaQualifiedTableName()));
}
///
@@ -3299,18 +3297,17 @@ private static string ForeignKeyTPCPrincipal(EventDefinitionBase definition, Eve
{
var d = (FallbackEventDefinition)definition;
var p = (ForeignKeyEventData)payload;
- return d.GenerateMessage(
- l => l.Log(
- d.Level,
- d.EventId,
- d.MessageFormat,
- p.ForeignKey.Properties.Format(),
- p.ForeignKey.DeclaringEntityType.DisplayName(),
- p.ForeignKey.PrincipalEntityType.DisplayName(),
- p.ForeignKey.PrincipalEntityType.GetSchemaQualifiedTableName()!,
- p.ForeignKey.PrincipalEntityType.DisplayName(),
- p.ForeignKey.DeclaringEntityType.DisplayName(),
- p.ForeignKey.PrincipalEntityType.DisplayName()));
+ return d.GenerateMessage(l => l.Log(
+ d.Level,
+ d.EventId,
+ d.MessageFormat,
+ p.ForeignKey.Properties.Format(),
+ p.ForeignKey.DeclaringEntityType.DisplayName(),
+ p.ForeignKey.PrincipalEntityType.DisplayName(),
+ p.ForeignKey.PrincipalEntityType.GetSchemaQualifiedTableName()!,
+ p.ForeignKey.PrincipalEntityType.DisplayName(),
+ p.ForeignKey.DeclaringEntityType.DisplayName(),
+ p.ForeignKey.PrincipalEntityType.DisplayName()));
}
///
diff --git a/src/EFCore.Relational/EFExtensions.cs b/src/EFCore.Relational/EFExtensions.cs
index c790c6256f2..a7212acc073 100644
--- a/src/EFCore.Relational/EFExtensions.cs
+++ b/src/EFCore.Relational/EFExtensions.cs
@@ -30,7 +30,8 @@ public static class EFExtensions
/// The type of collection.
/// The collection to be integrated as parameters into the query.
/// The same value for further use in the query.
- public static TSource MultipleParameters(TSource argument) where TSource : IEnumerable
+ public static TSource MultipleParameters(TSource argument)
+ where TSource : IEnumerable
=> throw new InvalidOperationException(RelationalStrings.EFMultipleParametersInvoked);
}
}
diff --git a/src/EFCore.Relational/Extensions/RelationalComplexCollectionTypePropertyBuilderExtensions.cs b/src/EFCore.Relational/Extensions/RelationalComplexCollectionTypePropertyBuilderExtensions.cs
index 136edb2463e..b67da37c280 100644
--- a/src/EFCore.Relational/Extensions/RelationalComplexCollectionTypePropertyBuilderExtensions.cs
+++ b/src/EFCore.Relational/Extensions/RelationalComplexCollectionTypePropertyBuilderExtensions.cs
@@ -41,5 +41,6 @@ public static ComplexCollectionTypePropertyBuilder HasJsonPropertyName(
public static ComplexCollectionTypePropertyBuilder HasJsonPropertyName(
this ComplexCollectionTypePropertyBuilder propertyBuilder,
string? name)
- => (ComplexCollectionTypePropertyBuilder)HasJsonPropertyName((ComplexCollectionTypePropertyBuilder)propertyBuilder, name);
+ => (ComplexCollectionTypePropertyBuilder)HasJsonPropertyName(
+ (ComplexCollectionTypePropertyBuilder)propertyBuilder, name);
}
diff --git a/src/EFCore.Relational/Extensions/RelationalDatabaseFacadeExtensions.cs b/src/EFCore.Relational/Extensions/RelationalDatabaseFacadeExtensions.cs
index 561186f724c..fa35a3764d1 100644
--- a/src/EFCore.Relational/Extensions/RelationalDatabaseFacadeExtensions.cs
+++ b/src/EFCore.Relational/Extensions/RelationalDatabaseFacadeExtensions.cs
@@ -561,7 +561,7 @@ public static Task ExecuteSqlRawAsync(
this DatabaseFacade databaseFacade,
string sql,
CancellationToken cancellationToken = default)
- => ExecuteSqlRawAsync(databaseFacade, sql, Enumerable.Empty(), cancellationToken);
+ => ExecuteSqlRawAsync(databaseFacade, sql, [], cancellationToken);
///
/// Executes the given SQL against the database and returns the number of rows affected.
diff --git a/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs b/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs
index 86da4f7ffe2..0f0833b02bc 100644
--- a/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs
+++ b/src/EFCore.Relational/Extensions/RelationalEntityTypeExtensions.cs
@@ -1021,7 +1021,7 @@ public static void SetComment(this IMutableEntityType entityType, string? commen
/// The entity type.
/// The configured entity type mapping fragments.
public static IEnumerable GetMappingFragments(this IReadOnlyEntityType entityType)
- => EntityTypeMappingFragment.Get(entityType) ?? Enumerable.Empty();
+ => EntityTypeMappingFragment.Get(entityType) ?? [];
///
///
@@ -1036,7 +1036,7 @@ public static IEnumerable GetMappingFragment
/// The configured entity type mapping fragments.
public static IEnumerable GetMappingFragments(this IMutableEntityType entityType)
=> EntityTypeMappingFragment.Get(entityType)?.Cast()
- ?? Enumerable.Empty();
+ ?? [];
///
///
@@ -1051,7 +1051,7 @@ public static IEnumerable GetMappingFragments
/// The configured entity type mapping fragments.
public static IEnumerable GetMappingFragments(this IConventionEntityType entityType)
=> EntityTypeMappingFragment.Get(entityType)?.Cast()
- ?? Enumerable.Empty();
+ ?? [];
///
///
@@ -1066,7 +1066,7 @@ public static IEnumerable GetMappingFragme
/// The configured entity type mapping fragments.
public static IEnumerable GetMappingFragments(this IEntityType entityType)
=> EntityTypeMappingFragment.Get(entityType)?.Cast()
- ?? Enumerable.Empty();
+ ?? [];
///
///
@@ -1086,7 +1086,7 @@ public static IEnumerable GetMappingFragment
{
var fragments = EntityTypeMappingFragment.Get(entityType);
return fragments == null
- ? Enumerable.Empty()
+ ? []
: fragments.Where(f => f.StoreObject.StoreObjectType == storeObjectType);
}
@@ -1640,10 +1640,10 @@ public static void SetContainerColumnTypeMapping(this IMutableEntityType entityT
{
var propertyName = entityType.FindAnnotation(RelationalAnnotationNames.JsonPropertyName);
return propertyName == null
- ? (entityType.IsMappedToJson()
- ? entityType.FindOwnership()!.GetNavigation(pointsToPrincipal: false)!.Name
- : null)
- : (string?)propertyName.Value;
+ ? (entityType.IsMappedToJson()
+ ? entityType.FindOwnership()!.GetNavigation(pointsToPrincipal: false)!.Name
+ : null)
+ : (string?)propertyName.Value;
}
///
diff --git a/src/EFCore.Relational/Extensions/RelationalForeignKeyExtensions.cs b/src/EFCore.Relational/Extensions/RelationalForeignKeyExtensions.cs
index 2e53d147e76..985ac838e1f 100644
--- a/src/EFCore.Relational/Extensions/RelationalForeignKeyExtensions.cs
+++ b/src/EFCore.Relational/Extensions/RelationalForeignKeyExtensions.cs
@@ -139,7 +139,7 @@ public static IEnumerable GetMappedConstraints(this IFore
foreignKey.DeclaringEntityType.Model.EnsureRelationalModel();
return (IEnumerable?)foreignKey.FindRuntimeAnnotationValue(
RelationalAnnotationNames.ForeignKeyMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
diff --git a/src/EFCore.Relational/Extensions/RelationalIndexExtensions.cs b/src/EFCore.Relational/Extensions/RelationalIndexExtensions.cs
index 7df34a087a3..2f27af24c08 100644
--- a/src/EFCore.Relational/Extensions/RelationalIndexExtensions.cs
+++ b/src/EFCore.Relational/Extensions/RelationalIndexExtensions.cs
@@ -170,7 +170,7 @@ public static IEnumerable GetMappedTableIndexes(this IIndex index)
index.DeclaringEntityType.Model.EnsureRelationalModel();
return (IEnumerable?)index.FindRuntimeAnnotationValue(
RelationalAnnotationNames.TableIndexMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
diff --git a/src/EFCore.Relational/Extensions/RelationalKeyExtensions.cs b/src/EFCore.Relational/Extensions/RelationalKeyExtensions.cs
index 2db451d52bb..e6848e8e732 100644
--- a/src/EFCore.Relational/Extensions/RelationalKeyExtensions.cs
+++ b/src/EFCore.Relational/Extensions/RelationalKeyExtensions.cs
@@ -111,7 +111,7 @@ public static IEnumerable GetMappedConstraints(this IKey key)
key.DeclaringEntityType.Model.EnsureRelationalModel();
return (IEnumerable?)key.FindRuntimeAnnotationValue(
RelationalAnnotationNames.UniqueConstraintMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
diff --git a/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs b/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs
index 11c4ec363a5..eb1c6ca33f8 100644
--- a/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs
+++ b/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs
@@ -253,7 +253,10 @@ public static string GetDefaultColumnName(this IReadOnlyProperty property)
return Uniquifier.Truncate(baseName, property.DeclaringType.Model.GetMaxIdentifierLength());
[return: NotNullIfNotNull("builder")]
- static StringBuilder? CreateOwnershipPrefix(IReadOnlyEntityType entityType, in StoreObjectIdentifier storeObject, StringBuilder? builder)
+ static StringBuilder? CreateOwnershipPrefix(
+ IReadOnlyEntityType entityType,
+ in StoreObjectIdentifier storeObject,
+ StringBuilder? builder)
{
while (true)
{
@@ -289,7 +292,10 @@ public static string GetDefaultColumnName(this IReadOnlyProperty property)
}
}
- static StringBuilder CreateComplexPrefix(IReadOnlyComplexType complexType, in StoreObjectIdentifier storeObject, StringBuilder? builder)
+ static StringBuilder CreateComplexPrefix(
+ IReadOnlyComplexType complexType,
+ in StoreObjectIdentifier storeObject,
+ StringBuilder? builder)
{
builder ??= new StringBuilder();
while (true)
@@ -552,7 +558,7 @@ public static IEnumerable GetDefaultColumnMappings(this IPro
property.DeclaringType.Model.EnsureRelationalModel();
return (IEnumerable?)property.FindRuntimeAnnotationValue(
RelationalAnnotationNames.DefaultColumnMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
@@ -565,7 +571,7 @@ public static IEnumerable GetTableColumnMappings(this IProperty
property.DeclaringType.Model.EnsureRelationalModel();
return (IEnumerable?)property.FindRuntimeAnnotationValue(
RelationalAnnotationNames.TableColumnMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
@@ -578,7 +584,7 @@ public static IEnumerable GetViewColumnMappings(this IProper
property.DeclaringType.Model.EnsureRelationalModel();
return (IEnumerable?)property.FindRuntimeAnnotationValue(
RelationalAnnotationNames.ViewColumnMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
@@ -591,7 +597,7 @@ public static IEnumerable GetSqlQueryColumnMappings(this
property.DeclaringType.Model.EnsureRelationalModel();
return (IEnumerable?)property.FindRuntimeAnnotationValue(
RelationalAnnotationNames.SqlQueryColumnMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
@@ -604,7 +610,7 @@ public static IEnumerable GetFunctionColumnMappings(this
property.DeclaringType.Model.EnsureRelationalModel();
return (IEnumerable?)property.FindRuntimeAnnotationValue(
RelationalAnnotationNames.FunctionColumnMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
@@ -617,7 +623,7 @@ public static IEnumerable GetInsertStoredPr
property.DeclaringType.Model.EnsureRelationalModel();
return (IEnumerable?)property.FindRuntimeAnnotationValue(
RelationalAnnotationNames.InsertStoredProcedureResultColumnMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
@@ -630,7 +636,7 @@ public static IEnumerable GetInsertStoredProce
property.DeclaringType.Model.EnsureRelationalModel();
return (IEnumerable?)property.FindRuntimeAnnotationValue(
RelationalAnnotationNames.InsertStoredProcedureParameterMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
@@ -643,7 +649,7 @@ public static IEnumerable GetDeleteStoredProce
property.DeclaringType.Model.EnsureRelationalModel();
return (IEnumerable?)property.FindRuntimeAnnotationValue(
RelationalAnnotationNames.DeleteStoredProcedureParameterMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
@@ -656,7 +662,7 @@ public static IEnumerable GetUpdateStoredPr
property.DeclaringType.Model.EnsureRelationalModel();
return (IEnumerable?)property.FindRuntimeAnnotationValue(
RelationalAnnotationNames.UpdateStoredProcedureResultColumnMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
@@ -669,7 +675,7 @@ public static IEnumerable GetUpdateStoredProce
property.DeclaringType.Model.EnsureRelationalModel();
return (IEnumerable?)property.FindRuntimeAnnotationValue(
RelationalAnnotationNames.UpdateStoredProcedureParameterMappings)
- ?? Enumerable.Empty();
+ ?? [];
}
///
@@ -1218,7 +1224,7 @@ public static void SetIsFixedLength(this IMutableProperty property, bool? fixedL
/// if the mapped column is nullable; otherwise.
public static bool IsColumnNullable(this IReadOnlyProperty property)
=> property.IsNullable
- || (property.DeclaringType.ContainingEntityType is IReadOnlyEntityType entityType
+ || (property.DeclaringType.ContainingEntityType is { } entityType
&& entityType.BaseType != null
&& entityType.GetMappingStrategy() == RelationalAnnotationNames.TphMappingStrategy)
|| (property.DeclaringType is IReadOnlyComplexType complexType
@@ -1226,8 +1232,8 @@ public static bool IsColumnNullable(this IReadOnlyProperty property)
private static bool IsNullable(IReadOnlyComplexProperty complexProperty)
=> complexProperty.IsNullable
- || (complexProperty.DeclaringType is IReadOnlyComplexType complexType
- && IsNullable(complexType.ComplexProperty));
+ || (complexProperty.DeclaringType is IReadOnlyComplexType complexType
+ && IsNullable(complexType.ComplexProperty));
///
/// Checks whether the column mapped to the given property will be nullable
@@ -1255,7 +1261,7 @@ public static bool IsColumnNullable(this IReadOnlyProperty property, in StoreObj
}
return property.IsNullable
- || (property.DeclaringType.ContainingEntityType is IReadOnlyEntityType entityType
+ || (property.DeclaringType.ContainingEntityType is { } entityType
&& ((entityType.BaseType != null
&& entityType.GetMappingStrategy() == RelationalAnnotationNames.TphMappingStrategy)
|| IsOptionalSharingDependent(entityType, storeObject, 0)))
@@ -1643,7 +1649,7 @@ public static IEnumerable GetOverrides(thi
/// The property facet overrides.
public static IEnumerable GetOverrides(this IMutableProperty property)
=> RelationalPropertyOverrides.Get(property)?.Cast()
- ?? Enumerable.Empty();
+ ?? [];
///
///
@@ -1658,7 +1664,7 @@ public static IEnumerable GetOverrides(this
/// The property facet overrides.
public static IEnumerable GetOverrides(this IConventionProperty property)
=> RelationalPropertyOverrides.Get(property)?.Cast()
- ?? Enumerable.Empty();
+ ?? [];
///