diff --git a/EFCore.sln.DotSettings b/EFCore.sln.DotSettings index b4ee3f703c7..4cf51e07431 100644 --- a/EFCore.sln.DotSettings +++ b/EFCore.sln.DotSettings @@ -62,13 +62,14 @@ NEXT_LINE 1 1 - False + True True NEVER False False NEVER NEVER + False False True LINE_BREAK @@ -79,10 +80,11 @@ False True True + CHOP_IF_LONG True True 140 - False + True CHOP_ALWAYS True @@ -120,13 +122,53 @@ Licensed under the Apache License, Version 2.0. See License.txt in the project r <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /> <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Public" Description="Test Methods"><ElementKinds><Kind Name="TEST_MEMBER" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="Aa_bb" /></Policy> EF + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="I" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="T" Suffix="" Style="AaBb" /> $object$_On$event$ + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> True ..\EFCore.sln.DotSettings True 1 + DO_NOTHING True True True @@ -140,4 +182,5 @@ Licensed under the Apache License, Version 2.0. See License.txt in the project r True True True - True \ No newline at end of file + True + True \ No newline at end of file diff --git a/src/EFCore.Cosmos/CosmosPropertyBuilderExtensions.cs b/src/EFCore.Cosmos/CosmosPropertyBuilderExtensions.cs index 41729c86c14..ebb8f1c093e 100644 --- a/src/EFCore.Cosmos/CosmosPropertyBuilderExtensions.cs +++ b/src/EFCore.Cosmos/CosmosPropertyBuilderExtensions.cs @@ -2,10 +2,10 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using JetBrains.Annotations; +using Microsoft.EntityFrameworkCore.Cosmos.Metadata.Internal; +using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Internal; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Cosmos.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.Cosmos { diff --git a/src/EFCore.Cosmos/Extensions/CosmosServiceCollectionExtensions.cs b/src/EFCore.Cosmos/Extensions/CosmosServiceCollectionExtensions.cs index 7d5f1b63604..4ad986db629 100644 --- a/src/EFCore.Cosmos/Extensions/CosmosServiceCollectionExtensions.cs +++ b/src/EFCore.Cosmos/Extensions/CosmosServiceCollectionExtensions.cs @@ -41,7 +41,6 @@ public static IServiceCollection AddEntityFrameworkCosmos([NotNull] this IServic .TryAddProviderSpecificServices( b => b .TryAddScoped() - ); builder.TryAddCoreServices(); diff --git a/src/EFCore.Cosmos/Infrastructure/Internal/CosmosDbOptionExtension.cs b/src/EFCore.Cosmos/Infrastructure/Internal/CosmosDbOptionExtension.cs index f0c49ea5141..20640621fcd 100644 --- a/src/EFCore.Cosmos/Infrastructure/Internal/CosmosDbOptionExtension.cs +++ b/src/EFCore.Cosmos/Infrastructure/Internal/CosmosDbOptionExtension.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Text; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; diff --git a/src/EFCore.Cosmos/Metadata/Conventions/Internal/StoreKeyConvention.cs b/src/EFCore.Cosmos/Metadata/Conventions/Internal/StoreKeyConvention.cs index 511d9fd3013..658ebc23e89 100644 --- a/src/EFCore.Cosmos/Metadata/Conventions/Internal/StoreKeyConvention.cs +++ b/src/EFCore.Cosmos/Metadata/Conventions/Internal/StoreKeyConvention.cs @@ -64,7 +64,7 @@ public InternalRelationshipBuilder Apply(InternalRelationshipBuilder relationshi public Annotation Apply(InternalEntityTypeBuilder entityTypeBuilder, string name, Annotation annotation, Annotation oldAnnotation) { - if(name == CosmosAnnotationNames.ContainerName) + if (name == CosmosAnnotationNames.ContainerName) { Apply(entityTypeBuilder); } diff --git a/src/EFCore.Cosmos/Metadata/CosmosEntityTypeAnnotations.cs b/src/EFCore.Cosmos/Metadata/CosmosEntityTypeAnnotations.cs index a65581911ad..0acf740878a 100644 --- a/src/EFCore.Cosmos/Metadata/CosmosEntityTypeAnnotations.cs +++ b/src/EFCore.Cosmos/Metadata/CosmosEntityTypeAnnotations.cs @@ -35,14 +35,13 @@ public virtual string ContainerName get => EntityType.BaseType != null ? GetAnnotations(EntityType.RootType()).ContainerName : ((string)Annotations.Metadata[CosmosAnnotationNames.ContainerName]) - ?? GetDefaultContainerName(); + ?? GetDefaultContainerName(); - [param: CanBeNull] - set => SetContainerName(value); + [param: CanBeNull] set => SetContainerName(value); } private string GetDefaultContainerName() => GetAnnotations(EntityType.Model).DefaultContainerName - ?? EntityType.ShortName(); + ?? EntityType.ShortName(); protected virtual bool SetContainerName([CanBeNull] string value) => Annotations.SetAnnotation( @@ -62,8 +61,7 @@ public virtual IProperty DiscriminatorProperty return propertyName == null ? null : EntityType.FindProperty(propertyName); } - [param: CanBeNull] - set => SetDiscriminatorProperty(value); + [param: CanBeNull] set => SetDiscriminatorProperty(value); } protected virtual bool SetDiscriminatorProperty([CanBeNull] IProperty value) @@ -106,8 +104,7 @@ protected virtual bool RemoveDiscriminatorValue() public virtual object DiscriminatorValue { get => Annotations.Metadata[CosmosAnnotationNames.DiscriminatorValue]; - [param: CanBeNull] - set => SetDiscriminatorValue(value); + [param: CanBeNull] set => SetDiscriminatorValue(value); } protected virtual bool SetDiscriminatorValue([CanBeNull] object value) diff --git a/src/EFCore.Cosmos/Metadata/CosmosModelAnnotations.cs b/src/EFCore.Cosmos/Metadata/CosmosModelAnnotations.cs index 27bd1736413..f3e8f98e5d3 100644 --- a/src/EFCore.Cosmos/Metadata/CosmosModelAnnotations.cs +++ b/src/EFCore.Cosmos/Metadata/CosmosModelAnnotations.cs @@ -25,8 +25,7 @@ public virtual string DefaultContainerName { get => (string)Annotations.Metadata[CosmosAnnotationNames.ContainerName]; - [param: CanBeNull] - set => SetDefaultContainerName(value); + [param: CanBeNull] set => SetDefaultContainerName(value); } protected virtual bool SetDefaultContainerName([CanBeNull] string value) diff --git a/src/EFCore.Cosmos/Metadata/CosmosPropertyAnnotations.cs b/src/EFCore.Cosmos/Metadata/CosmosPropertyAnnotations.cs index 666523585df..84354595e15 100644 --- a/src/EFCore.Cosmos/Metadata/CosmosPropertyAnnotations.cs +++ b/src/EFCore.Cosmos/Metadata/CosmosPropertyAnnotations.cs @@ -23,10 +23,9 @@ public CosmosPropertyAnnotations(IProperty property) public virtual string PropertyName { get => ((string)Annotations.Metadata[CosmosAnnotationNames.PropertyName]) - ?? Property.Name; + ?? Property.Name; - [param: CanBeNull] - set => SetPropertyName(value); + [param: CanBeNull] set => SetPropertyName(value); } protected virtual bool SetPropertyName([CanBeNull] string value) diff --git a/src/EFCore.Cosmos/Metadata/Internal/CosmosModelBuilderAnnotations.cs b/src/EFCore.Cosmos/Metadata/Internal/CosmosModelBuilderAnnotations.cs index 5c573f132ae..216295ecb44 100644 --- a/src/EFCore.Cosmos/Metadata/Internal/CosmosModelBuilderAnnotations.cs +++ b/src/EFCore.Cosmos/Metadata/Internal/CosmosModelBuilderAnnotations.cs @@ -3,7 +3,6 @@ using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata.Internal; -using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Cosmos.Metadata.Internal { diff --git a/src/EFCore.Cosmos/Metadata/Internal/CosmosPropertyBuilderAnnotations.cs b/src/EFCore.Cosmos/Metadata/Internal/CosmosPropertyBuilderAnnotations.cs index 192196356a5..7e8650b21b3 100644 --- a/src/EFCore.Cosmos/Metadata/Internal/CosmosPropertyBuilderAnnotations.cs +++ b/src/EFCore.Cosmos/Metadata/Internal/CosmosPropertyBuilderAnnotations.cs @@ -3,7 +3,6 @@ using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata.Internal; -using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Cosmos.Metadata.Internal { diff --git a/src/EFCore.Cosmos/Metadata/Internal/EntityTypeExtensions.cs b/src/EFCore.Cosmos/Metadata/Internal/EntityTypeExtensions.cs index 940adbf316c..1bbaeefb750 100644 --- a/src/EFCore.Cosmos/Metadata/Internal/EntityTypeExtensions.cs +++ b/src/EFCore.Cosmos/Metadata/Internal/EntityTypeExtensions.cs @@ -9,8 +9,8 @@ public static class EntityTypeExtensions { public static bool IsDocumentRoot(this IEntityType entityType) => entityType.BaseType == null - ? !entityType.IsOwned() - || entityType[CosmosAnnotationNames.ContainerName] != null - : entityType.BaseType.IsDocumentRoot(); + ? !entityType.IsOwned() + || entityType[CosmosAnnotationNames.ContainerName] != null + : entityType.BaseType.IsDocumentRoot(); } } diff --git a/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosEntityQueryableExpressionVisitor.cs b/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosEntityQueryableExpressionVisitor.cs index a6630742087..792f01bda62 100644 --- a/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosEntityQueryableExpressionVisitor.cs +++ b/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosEntityQueryableExpressionVisitor.cs @@ -50,11 +50,12 @@ protected override Expression VisitEntityQueryable([NotNull] Type elementType) QueryModelVisitor.QueryCompilationContext.IsAsyncQuery, entityType.Cosmos().ContainerName, new SelectExpression(entityType, _querySource)), - new EntityShaper(entityType, + new EntityShaper( + entityType, trackingQuery: QueryModelVisitor.QueryCompilationContext.IsTrackingQuery - && !entityType.IsQueryType, + && !entityType.IsQueryType, useQueryBuffer: QueryModelVisitor.QueryCompilationContext.IsQueryBufferRequired - && !entityType.IsQueryType, + && !entityType.IsQueryType, _entityMaterializerSource)); } } diff --git a/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosEntityQueryableExpressionVisitorFactory.cs b/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosEntityQueryableExpressionVisitorFactory.cs index 527f3c7615e..7348c972f81 100644 --- a/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosEntityQueryableExpressionVisitorFactory.cs +++ b/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosEntityQueryableExpressionVisitorFactory.cs @@ -3,7 +3,6 @@ using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Cosmos.Query.Internal; -using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Query; diff --git a/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosSqlGenerator.cs b/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosSqlGenerator.cs index 3e32b1a7fae..b514ec960c9 100644 --- a/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosSqlGenerator.cs +++ b/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/CosmosSqlGenerator.cs @@ -8,7 +8,6 @@ using System.Text; using Microsoft.EntityFrameworkCore.Cosmos.Query.Expressions.Internal; using Microsoft.EntityFrameworkCore.Cosmos.Storage; -using Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -54,7 +53,7 @@ public class CosmosSqlGenerator : ExpressionVisitor { ExpressionType.Not, "~" }, // Others - { ExpressionType.Coalesce, " ?? " }, + { ExpressionType.Coalesce, " ?? " } }; public CosmosSqlQuery GenerateSqlQuerySpec( @@ -116,7 +115,9 @@ protected override Expression VisitConstant(ConstantExpression constantExpressio { _sqlBuilder.Append("null"); } - else if (value.GetType().IsNumeric() || value is DateTime || value is DateTimeOffset) + else if (value.GetType().IsNumeric() + || value is DateTime + || value is DateTimeOffset) { var jsonValue = JToken.FromObject(value); _sqlBuilder.Append(jsonValue.ToString(Formatting.None)); diff --git a/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/SqlTranslatingExpressionVisitor.cs b/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/SqlTranslatingExpressionVisitor.cs index f543fdf2d87..7afed66e4ab 100644 --- a/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/SqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.Cosmos/Query/ExpressionVisitors/Internal/SqlTranslatingExpressionVisitor.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Cosmos.Query.Expressions.Internal; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.Expressions.Internal; @@ -21,7 +20,8 @@ public class SqlTranslatingExpressionVisitor : ExpressionVisitorBase private readonly SelectExpression _selectExpression; private readonly QueryCompilationContext _queryCompilationContext; - public SqlTranslatingExpressionVisitor(SelectExpression selectExpression, + public SqlTranslatingExpressionVisitor( + SelectExpression selectExpression, QueryCompilationContext queryCompilationContext) { _selectExpression = selectExpression; @@ -32,7 +32,8 @@ public class SqlTranslatingExpressionVisitor : ExpressionVisitorBase protected override Expression VisitMember(MemberExpression memberExpression) { - var properties = MemberAccessBindingExpressionVisitor.GetPropertyPath(memberExpression, + var properties = MemberAccessBindingExpressionVisitor.GetPropertyPath( + memberExpression, _queryCompilationContext, out var qsre); var newExpression = _selectExpression.BindPropertyPath(qsre, properties); @@ -47,7 +48,8 @@ protected override Expression VisitMember(MemberExpression memberExpression) protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { - var properties = MemberAccessBindingExpressionVisitor.GetPropertyPath(methodCallExpression, + var properties = MemberAccessBindingExpressionVisitor.GetPropertyPath( + methodCallExpression, _queryCompilationContext, out var qsre); var newExpression = _selectExpression.BindPropertyPath(qsre, properties); diff --git a/src/EFCore.Cosmos/Query/Expressions/Internal/SelectExpression.cs b/src/EFCore.Cosmos/Query/Expressions/Internal/SelectExpression.cs index acdd671b348..f9905a968e7 100644 --- a/src/EFCore.Cosmos/Query/Expressions/Internal/SelectExpression.cs +++ b/src/EFCore.Cosmos/Query/Expressions/Internal/SelectExpression.cs @@ -7,7 +7,6 @@ using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Cosmos.Query.ExpressionVisitors.Internal; using Microsoft.EntityFrameworkCore.Cosmos.Storage; -using Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Newtonsoft.Json.Linq; @@ -47,16 +46,17 @@ var concreteEntityTypes var discriminatorProperty = entityType.Cosmos().DiscriminatorProperty; var discriminatorPredicate = Equal( - new KeyAccessExpression(discriminatorProperty, FromExpression), - Constant(concreteEntityTypes[0].Cosmos().DiscriminatorValue, discriminatorProperty.ClrType)); + new KeyAccessExpression(discriminatorProperty, FromExpression), + Constant(concreteEntityTypes[0].Cosmos().DiscriminatorValue, discriminatorProperty.ClrType)); if (concreteEntityTypes.Count > 1) { discriminatorPredicate = concreteEntityTypes .Skip(1) - .Select(concreteEntityType - => Constant(concreteEntityType.Cosmos().DiscriminatorValue, discriminatorProperty.ClrType)) + .Select( + concreteEntityType + => Constant(concreteEntityType.Cosmos().DiscriminatorValue, discriminatorProperty.ClrType)) .Aggregate( discriminatorPredicate, (current, discriminatorValue) => OrElse( diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosQueryContextFactory.cs b/src/EFCore.Cosmos/Query/Internal/CosmosQueryContextFactory.cs index 64cf5ed2a6d..2d9e625dd99 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosQueryContextFactory.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosQueryContextFactory.cs @@ -14,7 +14,7 @@ public class CosmosQueryContextFactory : QueryContextFactory public CosmosQueryContextFactory( [NotNull] QueryContextDependencies dependencies, [NotNull] CosmosClientWrapper cosmosClient) - : base(dependencies) + : base(dependencies) { _cosmosClient = cosmosClient; } diff --git a/src/EFCore.Cosmos/Query/Internal/CosmosQueryModelVisitor.cs b/src/EFCore.Cosmos/Query/Internal/CosmosQueryModelVisitor.cs index 86bfcda141c..5ab258bdfd0 100644 --- a/src/EFCore.Cosmos/Query/Internal/CosmosQueryModelVisitor.cs +++ b/src/EFCore.Cosmos/Query/Internal/CosmosQueryModelVisitor.cs @@ -14,7 +14,8 @@ namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal { public class CosmosQueryModelVisitor : EntityQueryModelVisitor { - public CosmosQueryModelVisitor(EntityQueryModelVisitorDependencies dependencies, + public CosmosQueryModelVisitor( + EntityQueryModelVisitorDependencies dependencies, QueryCompilationContext queryCompilationContext) : base(dependencies, queryCompilationContext) { @@ -55,15 +56,17 @@ public override void VisitWhereClause(WhereClause whereClause, QueryModel queryM { Expression = new QueryShaperExpression( QueryCompilationContext.IsAsyncQuery, - Expression.Call(LinqOperatorProvider.Where.MakeGenericMethod(CurrentParameter.Type), - queryShaperExpression.QueryExpression, - Expression.Lambda(predicate, CurrentParameter)), + Expression.Call( + LinqOperatorProvider.Where.MakeGenericMethod(CurrentParameter.Type), + queryShaperExpression.QueryExpression, + Expression.Lambda(predicate, CurrentParameter)), queryShaperExpression.Shaper); if (CurrentParameter.Type == typeof(JObject)) { UpdateCurrentParameter(fromClause, previousParameterType); } + return; } diff --git a/src/EFCore.Cosmos/Query/Internal/EntityShaper.cs b/src/EFCore.Cosmos/Query/Internal/EntityShaper.cs index f899d83c120..7f3040f9e79 100644 --- a/src/EFCore.Cosmos/Query/Internal/EntityShaper.cs +++ b/src/EFCore.Cosmos/Query/Internal/EntityShaper.cs @@ -80,17 +80,18 @@ private NewExpression CreateEntityInfoExpression(IEntityType entityType, INaviga var nestedEntitiesExpression = nestedEntities.Count == 0 ? (Expression)Expression.Constant(null, typeof(IList)) - : Expression.ListInit(Expression.New(typeof(List)), + : Expression.ListInit( + Expression.New(typeof(List)), nestedEntities.Select(n => Expression.ElementInit(_listAddMethodInfo, n))); return Expression.New( - EntityInfo.ConstructorInfo, - Expression.Constant(navigation, typeof(INavigation)), - Expression.Constant(entityType.FindPrimaryKey(), typeof(IKey)), - valueBufferFactory, - materializer, - Expression.Constant(indexMap, typeof(Dictionary)), - nestedEntitiesExpression); + EntityInfo.ConstructorInfo, + Expression.Constant(navigation, typeof(INavigation)), + Expression.Constant(entityType.FindPrimaryKey(), typeof(IKey)), + valueBufferFactory, + materializer, + Expression.Constant(indexMap, typeof(Dictionary)), + nestedEntitiesExpression); } private LambdaExpression CreateMaterializerExpression( @@ -101,7 +102,7 @@ private NewExpression CreateEntityInfoExpression(IEntityType entityType, INaviga typeIndexMap = null; var materializationContextParameter - = Expression.Parameter(typeof(MaterializationContext), "materializationContext"); + = Expression.Parameter(typeof(MaterializationContext), "materializationContext"); var concreteEntityTypes = entityType.GetConcreteTypesInHierarchy().ToList(); var firstEntityType = concreteEntityTypes[0]; @@ -172,6 +173,7 @@ var blockExpressions usedProperties.Add(property); propertyIndex = usedProperties.Count - 1; } + indexMap[property.GetIndex()] = propertyIndex; shadowPropertyExists = shadowPropertyExists || property.IsShadowProperty; @@ -244,32 +246,32 @@ var discriminatorValue var entity = entityInfo.Materializer(new MaterializationContext(valueBuffer, queryContext.Context)); return ShapeNestedEntities( - jObject, - queryContext, - trackingQuery, - bufferedQuery, - entityInfo, - entity); + jObject, + queryContext, + trackingQuery, + bufferedQuery, + entityInfo, + entity); } else { var entity = queryContext.QueryBuffer - .GetEntity( - entityInfo.Key, - new EntityLoadInfo( - new MaterializationContext(valueBuffer, queryContext.Context), - entityInfo.Materializer, - entityInfo.TypeIndexMap), - queryStateManager: trackingQuery, - throwOnNullKey: true); + .GetEntity( + entityInfo.Key, + new EntityLoadInfo( + new MaterializationContext(valueBuffer, queryContext.Context), + entityInfo.Materializer, + entityInfo.TypeIndexMap), + queryStateManager: trackingQuery, + throwOnNullKey: true); return ShapeNestedEntities( - jObject, - queryContext, - trackingQuery, - bufferedQuery, - entityInfo, - entity); + jObject, + queryContext, + trackingQuery, + bufferedQuery, + entityInfo, + entity); } } @@ -312,12 +314,13 @@ var discriminatorValue { foreach (JObject nestedJObject in jArray) { - nestedEntities.Add(Shape( - nestedJObject, - queryContext, - trackingQuery, - bufferedQuery, - nestedEntityInfo)); + nestedEntities.Add( + Shape( + nestedJObject, + queryContext, + trackingQuery, + bufferedQuery, + nestedEntityInfo)); } } diff --git a/src/EFCore.Cosmos/Query/Internal/ValueBufferFactoryFactory.cs b/src/EFCore.Cosmos/Query/Internal/ValueBufferFactoryFactory.cs index d520c090190..123980cb3a7 100644 --- a/src/EFCore.Cosmos/Query/Internal/ValueBufferFactoryFactory.cs +++ b/src/EFCore.Cosmos/Query/Internal/ValueBufferFactoryFactory.cs @@ -27,11 +27,12 @@ public static class ValueBufferFactoryFactory Expression.NewArrayInit( typeof(object), usedProperties - .Select(p => + .Select( + p => CreateGetValueExpression( _jObjectParameter, p))), - _jObjectParameter); + _jObjectParameter); private static Expression CreateGetValueExpression( Expression jObjectExpression, @@ -46,8 +47,8 @@ public static class ValueBufferFactoryFactory if (storeName.Length == 0) { var type = property.FindMapping()?.ClrType - ?? property.GetValueConverter()?.ProviderClrType - ?? property.ClrType; + ?? property.GetValueConverter()?.ProviderClrType + ?? property.ClrType; return Expression.Default(type); } diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs index 65df39cd75f..c2b677fe651 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosClientWrapper.cs @@ -4,12 +4,8 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; using System.Net; using System.Runtime.CompilerServices; -using System.Text; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; @@ -51,10 +47,11 @@ public class CosmosClientWrapper : IDisposable private CosmosClient Client => _client - ?? (_client = new CosmosClient(new CosmosConfiguration(_endPoint, _authKey) - { - UserAgentSuffix = _userAgent - })); + ?? (_client = new CosmosClient( + new CosmosConfiguration(_endPoint, _authKey) + { + UserAgentSuffix = _userAgent + })); public bool CreateDatabaseIfNotExists() => _executionStrategyFactory.Create().Execute( @@ -143,7 +140,7 @@ public bool DeleteDatabase() var pk = new PartitionKeyDefinition(); pk.Paths.Add("/" + parameters.PartitionKey); - var settings = new CosmosContainerSettings() + var settings = new CosmosContainerSettings { Id = parameters.ContainerId, PartitionKey = pk @@ -283,6 +280,7 @@ private async Task GetItemsAsync(string containerId, CancellationTo { queryDefinition.UseParameter(parameter.Name, parameter.Value); } + return items.CreateItemQuery(queryDefinition, maxConcurrency: 16); } diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseCreator.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseCreator.cs index c90db596a69..e93869f668c 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseCreator.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseCreator.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; @@ -86,6 +85,5 @@ public virtual bool CanConnect() public virtual Task CanConnectAsync(CancellationToken cancellationToken = default) => throw new NotImplementedException(); - } } diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseWrapper.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseWrapper.cs index a552f63b786..b1c2fc665b2 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseWrapper.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosDatabaseWrapper.cs @@ -25,6 +25,7 @@ public class CosmosDatabaseWrapper : Database { private readonly Dictionary _documentCollections = new Dictionary(); + private readonly CosmosClientWrapper _cosmosClient; private readonly bool _sensitiveLoggingEnabled; @@ -65,6 +66,7 @@ public override int SaveChanges(IReadOnlyList entries) { ((InternalEntityEntry)root).SetEntityState(EntityState.Modified); } + continue; } @@ -75,7 +77,7 @@ public override int SaveChanges(IReadOnlyList entries) } } - foreach(var rootEntry in rootEntriesToSave) + foreach (var rootEntry in rootEntriesToSave) { if (!entriesSaved.Contains(rootEntry) && Save(rootEntry)) @@ -110,6 +112,7 @@ public override int SaveChanges(IReadOnlyList entries) { ((InternalEntityEntry)root).SetEntityState(EntityState.Modified); } + continue; } diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMapping.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMapping.cs index 8cc7caff989..ec1d20a4bf9 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMapping.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMapping.cs @@ -24,13 +24,14 @@ public class CosmosTypeMapping : CoreTypeMapping [CanBeNull] ValueComparer comparer = null, [CanBeNull] ValueComparer keyComparer = null, [CanBeNull] ValueComparer structuralComparer = null) - : base(new CoreTypeMappingParameters( - clrType, - converter: null, - comparer, - keyComparer, - structuralComparer, - valueGeneratorFactory: null)) + : base( + new CoreTypeMappingParameters( + clrType, + converter: null, + comparer, + keyComparer, + structuralComparer, + valueGeneratorFactory: null)) { } @@ -46,4 +47,4 @@ private CosmosTypeMapping(CoreTypeMappingParameters parameters) public override CoreTypeMapping Clone(ValueConverter converter) => new CosmosTypeMapping(Parameters.WithComposedConverter(converter)); } -} \ No newline at end of file +} diff --git a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs index 8e527fcb2c1..2523ad20e83 100644 --- a/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs +++ b/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs @@ -46,4 +46,4 @@ protected override CoreTypeMapping FindMapping(in TypeMappingInfo mappingInfo) return base.FindMapping(mappingInfo); } } -} \ No newline at end of file +} diff --git a/src/EFCore.Cosmos/Storage/SqlParameter.cs b/src/EFCore.Cosmos/Storage/SqlParameter.cs index 20a81908b04..f1981b93f93 100644 --- a/src/EFCore.Cosmos/Storage/SqlParameter.cs +++ b/src/EFCore.Cosmos/Storage/SqlParameter.cs @@ -1,8 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using Newtonsoft.Json; - namespace Microsoft.EntityFrameworkCore.Cosmos.Storage { public class SqlParameter diff --git a/src/EFCore.InMemory/Extensions/InMemoryServiceCollectionExtensions.cs b/src/EFCore.InMemory/Extensions/InMemoryServiceCollectionExtensions.cs index c5719192663..55e69410a31 100644 --- a/src/EFCore.InMemory/Extensions/InMemoryServiceCollectionExtensions.cs +++ b/src/EFCore.InMemory/Extensions/InMemoryServiceCollectionExtensions.cs @@ -12,11 +12,9 @@ using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors; -using Microsoft.EntityFrameworkCore.Query.Internal; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Utilities; using Microsoft.EntityFrameworkCore.ValueGeneration; -using Remotion.Linq.Parsing.ExpressionVisitors.TreeEvaluation; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection diff --git a/src/EFCore.InMemory/Storage/Internal/InMemoryStoreCache.cs b/src/EFCore.InMemory/Storage/Internal/InMemoryStoreCache.cs index 25ee63bc466..ff3634995e7 100644 --- a/src/EFCore.InMemory/Storage/Internal/InMemoryStoreCache.cs +++ b/src/EFCore.InMemory/Storage/Internal/InMemoryStoreCache.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Collections.Concurrent; using System.Threading; using JetBrains.Annotations; diff --git a/src/EFCore.InMemory/Storage/Internal/InMemoryTypeMapping.cs b/src/EFCore.InMemory/Storage/Internal/InMemoryTypeMapping.cs index 52752599f9a..86ac416b7de 100644 --- a/src/EFCore.InMemory/Storage/Internal/InMemoryTypeMapping.cs +++ b/src/EFCore.InMemory/Storage/Internal/InMemoryTypeMapping.cs @@ -24,13 +24,14 @@ public class InMemoryTypeMapping : CoreTypeMapping [CanBeNull] ValueComparer comparer = null, [CanBeNull] ValueComparer keyComparer = null, [CanBeNull] ValueComparer structuralComparer = null) - : base(new CoreTypeMappingParameters( - clrType, - converter: null, - comparer, - keyComparer, - structuralComparer, - valueGeneratorFactory: null)) + : base( + new CoreTypeMappingParameters( + clrType, + converter: null, + comparer, + keyComparer, + structuralComparer, + valueGeneratorFactory: null)) { } diff --git a/src/EFCore.Proxies/Proxies/Internal/ProxiesOptionsExtension.cs b/src/EFCore.Proxies/Proxies/Internal/ProxiesOptionsExtension.cs index 7d59d5606fc..316d40dbf81 100644 --- a/src/EFCore.Proxies/Proxies/Internal/ProxiesOptionsExtension.cs +++ b/src/EFCore.Proxies/Proxies/Internal/ProxiesOptionsExtension.cs @@ -121,8 +121,8 @@ public virtual bool ApplyServices(IServiceCollection services) /// public virtual string LogFragment => _logFragment - ?? (_logFragment = _useLazyLoadingProxies - ? "using lazy-loading proxies " - : ""); + ?? (_logFragment = _useLazyLoadingProxies + ? "using lazy-loading proxies " + : ""); } } diff --git a/src/EFCore.Relational/Extensions/RelationalTaskExtensions.cs b/src/EFCore.Relational/Extensions/RelationalTaskExtensions.cs index ebb0299fc15..d68c819f7b6 100644 --- a/src/EFCore.Relational/Extensions/RelationalTaskExtensions.cs +++ b/src/EFCore.Relational/Extensions/RelationalTaskExtensions.cs @@ -51,7 +51,7 @@ internal static class RelationalTaskExtensions } else { - taskCompletionSource.TrySetResult((T?)t.Result); + taskCompletionSource.TrySetResult(t.Result); } }, TaskContinuationOptions.ExecuteSynchronously); diff --git a/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs b/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs index 5f2bdfa1621..51cd68b4bb3 100644 --- a/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs +++ b/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs @@ -8,7 +8,6 @@ using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; -using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Infrastructure diff --git a/src/EFCore.Relational/Infrastructure/RelationalModelValidatorDependencies.cs b/src/EFCore.Relational/Infrastructure/RelationalModelValidatorDependencies.cs index 414cfbd2f64..526f783752b 100644 --- a/src/EFCore.Relational/Infrastructure/RelationalModelValidatorDependencies.cs +++ b/src/EFCore.Relational/Infrastructure/RelationalModelValidatorDependencies.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Utilities; diff --git a/src/EFCore.Relational/Metadata/Builders/DiscriminatorBuilder.cs b/src/EFCore.Relational/Metadata/Builders/DiscriminatorBuilder.cs index bc361c952ed..da13579f171 100644 --- a/src/EFCore.Relational/Metadata/Builders/DiscriminatorBuilder.cs +++ b/src/EFCore.Relational/Metadata/Builders/DiscriminatorBuilder.cs @@ -67,10 +67,10 @@ public virtual DiscriminatorBuilder HasValue([NotNull] Type entityType, [CanBeNu { var entityTypeBuilder = EntityTypeBuilder.Metadata.IsQueryType - ? EntityTypeBuilder.ModelBuilder.Query( - entityType, AnnotationsBuilder.ConfigurationSource) - : EntityTypeBuilder.ModelBuilder.Entity( - entityType, AnnotationsBuilder.ConfigurationSource, allowOwned: true); + ? EntityTypeBuilder.ModelBuilder.Query( + entityType, AnnotationsBuilder.ConfigurationSource) + : EntityTypeBuilder.ModelBuilder.Entity( + entityType, AnnotationsBuilder.ConfigurationSource, allowOwned: true); return HasValue(entityTypeBuilder, value); } @@ -85,10 +85,10 @@ public virtual DiscriminatorBuilder HasValue([NotNull] string entityTypeName, [C { var entityTypeBuilder = EntityTypeBuilder.Metadata.IsQueryType - ? EntityTypeBuilder.ModelBuilder.Query( - entityTypeName, AnnotationsBuilder.ConfigurationSource) - : EntityTypeBuilder.ModelBuilder.Entity( - entityTypeName, AnnotationsBuilder.ConfigurationSource, allowOwned: true); + ? EntityTypeBuilder.ModelBuilder.Query( + entityTypeName, AnnotationsBuilder.ConfigurationSource) + : EntityTypeBuilder.ModelBuilder.Entity( + entityTypeName, AnnotationsBuilder.ConfigurationSource, allowOwned: true); return HasValue(entityTypeBuilder, value); } diff --git a/src/EFCore.Relational/Metadata/Conventions/Internal/RelationalConventionSetBuilderDependencies.cs b/src/EFCore.Relational/Metadata/Conventions/Internal/RelationalConventionSetBuilderDependencies.cs index 3909165dd7f..1137426e214 100644 --- a/src/EFCore.Relational/Metadata/Conventions/Internal/RelationalConventionSetBuilderDependencies.cs +++ b/src/EFCore.Relational/Metadata/Conventions/Internal/RelationalConventionSetBuilderDependencies.cs @@ -1,15 +1,11 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Diagnostics; -using System.Linq; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Storage; -using Microsoft.EntityFrameworkCore.Storage.Internal; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Utilities; using Microsoft.Extensions.Logging; diff --git a/src/EFCore.Relational/Metadata/Internal/RelationalEntityTypeBuilderAnnotations.cs b/src/EFCore.Relational/Metadata/Internal/RelationalEntityTypeBuilderAnnotations.cs index 8973961eb87..64a00e56fd1 100644 --- a/src/EFCore.Relational/Metadata/Internal/RelationalEntityTypeBuilderAnnotations.cs +++ b/src/EFCore.Relational/Metadata/Internal/RelationalEntityTypeBuilderAnnotations.cs @@ -126,9 +126,9 @@ public virtual DiscriminatorBuilder HasDiscriminator([CanBeNull] Type discrimina return discriminatorType == null ? RemoveDiscriminator() : DiscriminatorProperty != null - && DiscriminatorProperty.ClrType == discriminatorType - ? DiscriminatorBuilder(null, null) - : DiscriminatorBuilder(null, discriminatorType); + && DiscriminatorProperty.ClrType == discriminatorType + ? DiscriminatorBuilder(null, null) + : DiscriminatorBuilder(null, discriminatorType); } /// @@ -151,10 +151,10 @@ public virtual DiscriminatorBuilder HasDiscriminator([CanBeNull] PropertyInfo pr return propertyInfo == null ? RemoveDiscriminator() : DiscriminatorProperty != null - && DiscriminatorProperty.Name == propertyInfo.GetSimpleMemberName() - && DiscriminatorProperty.ClrType == propertyInfo.PropertyType - ? DiscriminatorBuilder(null, null) - : DiscriminatorBuilder(b => b.Property(propertyInfo, Annotations.ConfigurationSource), null); + && DiscriminatorProperty.Name == propertyInfo.GetSimpleMemberName() + && DiscriminatorProperty.ClrType == propertyInfo.PropertyType + ? DiscriminatorBuilder(null, null) + : DiscriminatorBuilder(b => b.Property(propertyInfo, Annotations.ConfigurationSource), null); } private DiscriminatorBuilder RemoveDiscriminator() diff --git a/src/EFCore.Relational/Metadata/Internal/Sequence.cs b/src/EFCore.Relational/Metadata/Internal/Sequence.cs index fbbc7e7af81..1abf0744362 100644 --- a/src/EFCore.Relational/Metadata/Internal/Sequence.cs +++ b/src/EFCore.Relational/Metadata/Internal/Sequence.cs @@ -191,14 +191,7 @@ public virtual int IncrementBy /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - public static IReadOnlyCollection SupportedTypes { get; } = new[] - { - typeof(byte), - typeof(long), - typeof(int), - typeof(short), - typeof(decimal) - }; + public static IReadOnlyCollection SupportedTypes { get; } = new[] { typeof(byte), typeof(long), typeof(int), typeof(short), typeof(decimal) }; /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore.Relational/Migrations/Internal/MigrationsIdGenerator.cs b/src/EFCore.Relational/Migrations/Internal/MigrationsIdGenerator.cs index 8a6956ab1b3..9944b03e8f2 100644 --- a/src/EFCore.Relational/Migrations/Internal/MigrationsIdGenerator.cs +++ b/src/EFCore.Relational/Migrations/Internal/MigrationsIdGenerator.cs @@ -16,7 +16,7 @@ public class MigrationsIdGenerator : IMigrationsIdGenerator private const string Format = "yyyyMMddHHmmss"; private DateTime _lastTimestamp = DateTime.MinValue; - private object _lock = new object(); + private readonly object _lock = new object(); /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs b/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs index 35bc7083b3c..ad8f73308e6 100644 --- a/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs +++ b/src/EFCore.Relational/Migrations/Internal/MigrationsModelDiffer.cs @@ -28,39 +28,15 @@ namespace Microsoft.EntityFrameworkCore.Migrations.Internal /// public class MigrationsModelDiffer : IMigrationsModelDiffer { - private static readonly Type[] _dropOperationTypes = - { - typeof(DropIndexOperation), - typeof(DropPrimaryKeyOperation), - typeof(DropSequenceOperation), - typeof(DropUniqueConstraintOperation) - }; + private static readonly Type[] _dropOperationTypes = { typeof(DropIndexOperation), typeof(DropPrimaryKeyOperation), typeof(DropSequenceOperation), typeof(DropUniqueConstraintOperation) }; - private static readonly Type[] _alterOperationTypes = - { - typeof(AddPrimaryKeyOperation), - typeof(AddUniqueConstraintOperation), - typeof(AlterSequenceOperation) - }; + private static readonly Type[] _alterOperationTypes = { typeof(AddPrimaryKeyOperation), typeof(AddUniqueConstraintOperation), typeof(AlterSequenceOperation) }; - private static readonly Type[] _renameOperationTypes = - { - typeof(RenameColumnOperation), - typeof(RenameIndexOperation), - typeof(RenameSequenceOperation) - }; + private static readonly Type[] _renameOperationTypes = { typeof(RenameColumnOperation), typeof(RenameIndexOperation), typeof(RenameSequenceOperation) }; - private static readonly Type[] _columnOperationTypes = - { - typeof(AddColumnOperation), - typeof(AlterColumnOperation) - }; + private static readonly Type[] _columnOperationTypes = { typeof(AddColumnOperation), typeof(AlterColumnOperation) }; - private static readonly Type[] _constraintOperationTypes = - { - typeof(AddForeignKeyOperation), - typeof(CreateIndexOperation) - }; + private static readonly Type[] _constraintOperationTypes = { typeof(AddForeignKeyOperation), typeof(CreateIndexOperation) }; private IStateManager _sourceStateManager; private IStateManager _targetStateManager; @@ -829,9 +805,9 @@ private static bool EntityTypePathEquals(IEntityType source, IEntityType target, var nextSource = source.DefiningEntityType ?? source.BaseType; var nextTarget = target.DefiningEntityType ?? target.BaseType; return nextSource == null - || !sourceTable.EntityTypes.Contains(nextSource) - || nextTarget == null - || !targetTable.EntityTypes.Contains(nextTarget) + || !sourceTable.EntityTypes.Contains(nextSource) + || nextTarget == null + || !targetTable.EntityTypes.Contains(nextTarget) ? true : EntityTypePathEquals(nextSource, nextTarget, diffContext); } diff --git a/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs b/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs index 5c31e92e711..9de2779c1bf 100644 --- a/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs +++ b/src/EFCore.Relational/Migrations/MigrationsSqlGenerator.cs @@ -1582,8 +1582,8 @@ protected virtual IUpdateSqlGenerator SqlGenerator [CanBeNull] string schema, [NotNull] string tableName, [NotNull] string columnName - // Any property that maps to the column will work because model validator has - // checked that all properties result in the same column definition. + // Any property that maps to the column will work because model validator has + // checked that all properties result in the same column definition. ) => FindEntityTypes(model, schema, tableName)?.SelectMany(e => e.GetDeclaredProperties()) .FirstOrDefault(p => p.Relational().ColumnName == columnName); diff --git a/src/EFCore.Relational/Query/ExpressionTranslators/Internal/ComparisonTranslator.cs b/src/EFCore.Relational/Query/ExpressionTranslators/Internal/ComparisonTranslator.cs index 51d682d159a..92a0f23bdb0 100644 --- a/src/EFCore.Relational/Query/ExpressionTranslators/Internal/ComparisonTranslator.cs +++ b/src/EFCore.Relational/Query/ExpressionTranslators/Internal/ComparisonTranslator.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Linq.Expressions; -using System.Reflection; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Query.Expressions; using Microsoft.EntityFrameworkCore.Query.Expressions.Internal; @@ -26,7 +25,7 @@ public class ComparisonTranslator : IExpressionFragmentTranslator { ExpressionType.Equal, ExpressionType.Equal }, { ExpressionType.NotEqual, ExpressionType.NotEqual } }; - + /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. @@ -60,8 +59,8 @@ public virtual Expression Translate(Expression expression) private static Expression RemoveNullConditional(Expression expression) => expression.RemoveConvert() is NullConditionalExpression nullConditionalExpression - ? RemoveNullConditional(nullConditionalExpression.AccessOperation) - : expression; + ? RemoveNullConditional(nullConditionalExpression.AccessOperation) + : expression; private static Expression TranslateInternal( Func opFunc, @@ -85,9 +84,9 @@ private static Expression RemoveNullConditional(Expression expression) right = methodCall.Arguments[1]; } else if (methodCall.Method.Name == "CompareTo" - && methodCall.Arguments.Count == 1 - && methodCall.Object != null - && methodCall.Object.Type == methodCall.Arguments[0].Type) + && methodCall.Arguments.Count == 1 + && methodCall.Object != null + && methodCall.Object.Type == methodCall.Arguments[0].Type) { left = methodCall.Object; right = methodCall.Arguments[0]; diff --git a/src/EFCore.Relational/Query/ExpressionTranslators/Internal/EqualsTranslator.cs b/src/EFCore.Relational/Query/ExpressionTranslators/Internal/EqualsTranslator.cs index 54e7a111832..622c01e2107 100644 --- a/src/EFCore.Relational/Query/ExpressionTranslators/Internal/EqualsTranslator.cs +++ b/src/EFCore.Relational/Query/ExpressionTranslators/Internal/EqualsTranslator.cs @@ -44,7 +44,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) var argument = methodCallExpression.Arguments[0]; return methodCallExpression.Method.GetParameters()[0].ParameterType == typeof(object) - && methodCallExpression.Object.Type != argument.Type + && methodCallExpression.Object.Type != argument.Type ? TranslateEquals(methodCallExpression.Object, argument.RemoveConvert(), methodCallExpression) : Expression.Equal(methodCallExpression.Object, argument); } @@ -56,7 +56,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) var left = methodCallExpression.Arguments[0].RemoveConvert(); var right = methodCallExpression.Arguments[1].RemoveConvert(); return methodCallExpression.Method.GetParameters()[0].ParameterType == typeof(object) - && left.Type != right.Type + && left.Type != right.Type ? TranslateEquals(left, right, methodCallExpression) : Expression.Equal(left, right); } diff --git a/src/EFCore.Relational/Query/ExpressionTranslators/Internal/GetValueOrDefaultTranslator.cs b/src/EFCore.Relational/Query/ExpressionTranslators/Internal/GetValueOrDefaultTranslator.cs index e93090a63d6..0846061cac1 100644 --- a/src/EFCore.Relational/Query/ExpressionTranslators/Internal/GetValueOrDefaultTranslator.cs +++ b/src/EFCore.Relational/Query/ExpressionTranslators/Internal/GetValueOrDefaultTranslator.cs @@ -28,7 +28,8 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) methodCallExpression.Object, methodCallExpression.Type.GenerateDefaultValueConstantExpression()); } - else if (methodCallExpression.Arguments.Count == 1) + + if (methodCallExpression.Arguments.Count == 1) { return Expression.Coalesce( methodCallExpression.Object, diff --git a/src/EFCore.Relational/Query/ExpressionTranslators/Internal/LikeTranslator.cs b/src/EFCore.Relational/Query/ExpressionTranslators/Internal/LikeTranslator.cs index 7b321bb9f6a..ea3a86a96f5 100644 --- a/src/EFCore.Relational/Query/ExpressionTranslators/Internal/LikeTranslator.cs +++ b/src/EFCore.Relational/Query/ExpressionTranslators/Internal/LikeTranslator.cs @@ -35,8 +35,8 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) return Equals(methodCallExpression.Method, _methodInfo) ? new LikeExpression(methodCallExpression.Arguments[1], methodCallExpression.Arguments[2]) : Equals(methodCallExpression.Method, _methodInfoWithEscape) - ? new LikeExpression(methodCallExpression.Arguments[1], methodCallExpression.Arguments[2], methodCallExpression.Arguments[3]) - : null; + ? new LikeExpression(methodCallExpression.Arguments[1], methodCallExpression.Arguments[2], methodCallExpression.Arguments[3]) + : null; } } } diff --git a/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMemberTranslator.cs b/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMemberTranslator.cs index 098c775e8db..844a78fc515 100644 --- a/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMemberTranslator.cs +++ b/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMemberTranslator.cs @@ -37,7 +37,7 @@ protected RelationalCompositeMemberTranslator([NotNull] RelationalCompositeMembe /// A SQL expression representing the translated MemberExpression. /// public virtual Expression Translate(MemberExpression memberExpression) - => Enumerable.Concat(_plugins, _translators) + => _plugins.Concat(_translators) .Select(translator => translator.Translate(memberExpression)) .FirstOrDefault(translatedMember => translatedMember != null); diff --git a/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMemberTranslatorDependencies.cs b/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMemberTranslatorDependencies.cs index a547f0f52e1..d1143aada36 100644 --- a/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMemberTranslatorDependencies.cs +++ b/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMemberTranslatorDependencies.cs @@ -58,7 +58,7 @@ public RelationalCompositeMemberTranslatorDependencies([NotNull] IEnumerable A replacement for the current dependency of this type. /// A new parameter object with the given service replaced. public RelationalCompositeMemberTranslatorDependencies With( - [NotNull] IEnumerable plugins) + [NotNull] IEnumerable plugins) => new RelationalCompositeMemberTranslatorDependencies(plugins); } } diff --git a/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMethodCallTranslator.cs b/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMethodCallTranslator.cs index ebf71dbbe5e..581c48f6364 100644 --- a/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMethodCallTranslator.cs +++ b/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMethodCallTranslator.cs @@ -40,7 +40,7 @@ public abstract class RelationalCompositeMethodCallTranslator : ICompositeMethod new EqualsTranslator(dependencies.Logger), new GetValueOrDefaultTranslator(), new IsNullOrEmptyTranslator(), - new LikeTranslator(), + new LikeTranslator() }; } @@ -59,7 +59,7 @@ public abstract class RelationalCompositeMethodCallTranslator : ICompositeMethod /// public virtual Expression Translate(MethodCallExpression methodCallExpression, IModel model) => ((IMethodCallTranslator)model.Relational().FindDbFunction(methodCallExpression.Method))?.Translate(methodCallExpression) - ?? Enumerable.Concat(_plugins, _methodCallTranslators) + ?? _plugins.Concat(_methodCallTranslators) .Select(translator => translator.Translate(methodCallExpression)) .FirstOrDefault(translatedMethodCall => translatedMethodCall != null); diff --git a/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMethodCallTranslatorDependencies.cs b/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMethodCallTranslatorDependencies.cs index 430936be70f..d3819e4c867 100644 --- a/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMethodCallTranslatorDependencies.cs +++ b/src/EFCore.Relational/Query/ExpressionTranslators/RelationalCompositeMethodCallTranslatorDependencies.cs @@ -77,7 +77,7 @@ public RelationalCompositeMethodCallTranslatorDependencies With([NotNull] IDiagn /// A replacement for the current dependency of this type. /// A new parameter object with the given service replaced. public RelationalCompositeMethodCallTranslatorDependencies With( - [NotNull] IEnumerable plugins) + [NotNull] IEnumerable plugins) => new RelationalCompositeMethodCallTranslatorDependencies(Logger, plugins); } } diff --git a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/BufferedEntityShaper`.cs b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/BufferedEntityShaper`.cs index f2a7c39da8b..3869b4a81e1 100644 --- a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/BufferedEntityShaper`.cs +++ b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/BufferedEntityShaper`.cs @@ -50,14 +50,14 @@ public virtual TEntity Shape(QueryContext queryContext, in ValueBuffer valueBuff Debug.Assert(queryContext != null); return (TEntity)queryContext.QueryBuffer - .GetEntity( - Key, - new EntityLoadInfo( - new MaterializationContext(valueBuffer, queryContext.Context), - Materializer, - _typeIndexMap), - queryStateManager: IsTrackingQuery, - throwOnNullKey: !AllowNullResult); + .GetEntity( + Key, + new EntityLoadInfo( + new MaterializationContext(valueBuffer, queryContext.Context), + Materializer, + _typeIndexMap), + queryStateManager: IsTrackingQuery, + throwOnNullKey: !AllowNullResult); } /// diff --git a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/CompositePredicateExpressionVisitor.cs b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/CompositePredicateExpressionVisitor.cs index f5c78209bef..5b6392d1c8c 100644 --- a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/CompositePredicateExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/CompositePredicateExpressionVisitor.cs @@ -68,9 +68,9 @@ private class DiscriminatorPredicateOptimizingVisitor : RelinqExpressionVisitor protected override Expression VisitBinary(BinaryExpression binaryExpression) { return binaryExpression.NodeType == ExpressionType.Equal - && binaryExpression.Left.RemoveConvert() is ConditionalExpression conditionalExpression - && conditionalExpression.Test is DiscriminatorPredicateExpression discriminatorPredicateExpression - && conditionalExpression.IfFalse.IsNullConstantExpression() + && binaryExpression.Left.RemoveConvert() is ConditionalExpression conditionalExpression + && conditionalExpression.Test is DiscriminatorPredicateExpression discriminatorPredicateExpression + && conditionalExpression.IfFalse.IsNullConstantExpression() ? Expression.AndAlso( discriminatorPredicateExpression.Reduce(), Expression.Equal( diff --git a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/CompositeShaper.cs b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/CompositeShaper.cs index 821f4ed8635..f5686757d6a 100644 --- a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/CompositeShaper.cs +++ b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/CompositeShaper.cs @@ -34,22 +34,15 @@ public static class CompositeShaper Check.NotNull(materializer, nameof(materializer)); return (Shaper)_createCompositeShaperMethodInfo - .MakeGenericMethod( - outerShaper.GetType(), - outerShaper.Type, - innerShaper.GetType(), - innerShaper.Type, - materializer.ReturnType) - .Invoke( - null, - new object[] - { - querySource, - outerShaper, - innerShaper, - materializer.Compile(), - storeMaterializerExpression ? materializer : null - }); + .MakeGenericMethod( + outerShaper.GetType(), + outerShaper.Type, + innerShaper.GetType(), + innerShaper.Type, + materializer.ReturnType) + .Invoke( + null, + new object[] { querySource, outerShaper, innerShaper, materializer.Compile(), storeMaterializerExpression ? materializer : null }); } private static readonly MethodInfo _createCompositeShaperMethodInfo @@ -135,8 +128,8 @@ public override Shaper AddOffset(int offset) public override Shaper Unwrap(IQuerySource querySource) => _outerShaper.Unwrap(querySource) - ?? _innerShaper.Unwrap(querySource) - ?? base.Unwrap(querySource); + ?? _innerShaper.Unwrap(querySource) + ?? base.Unwrap(querySource); } } } diff --git a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/IsNullExpressionBuildingVisitor.cs b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/IsNullExpressionBuildingVisitor.cs index 6d1c5b29eb4..146f254d6a2 100644 --- a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/IsNullExpressionBuildingVisitor.cs +++ b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/IsNullExpressionBuildingVisitor.cs @@ -182,7 +182,7 @@ protected override Expression VisitConditional(ConditionalExpression conditional } return left != null - && right != null + && right != null ? Expression.MakeBinary(expressionType, left, right) : left ?? right; } diff --git a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/PredicateReductionExpressionOptimizer.cs b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/PredicateReductionExpressionOptimizer.cs index 74d8bfb1ca1..b3a28db2d13 100644 --- a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/PredicateReductionExpressionOptimizer.cs +++ b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/PredicateReductionExpressionOptimizer.cs @@ -93,7 +93,7 @@ protected override Expression VisitBinary(BinaryExpression node) } return newRight is ConstantExpression rightConstant - && (bool?)rightConstant.Value == true + && (bool?)rightConstant.Value == true ? newLeft.Type == typeof(bool) ? newLeft : Expression.Convert(newLeft, typeof(bool)) : node.Update(newLeft, node.Conversion, newRight); } diff --git a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/ProjectionShaper.cs b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/ProjectionShaper.cs index d91522d38d5..55dbac99fd5 100644 --- a/src/EFCore.Relational/Query/ExpressionVisitors/Internal/ProjectionShaper.cs +++ b/src/EFCore.Relational/Query/ExpressionVisitors/Internal/ProjectionShaper.cs @@ -43,12 +43,7 @@ var shaper materializer.ReturnType) .Invoke( null, - new object[] - { - originalShaper, - materializer.Compile(), - storeMaterializerExpression ? materializer : null - }); + new object[] { originalShaper, materializer.Compile(), storeMaterializerExpression ? materializer : null }); return shaper; } diff --git a/src/EFCore.Relational/Query/ExpressionVisitors/RelationalEntityQueryableExpressionVisitor.cs b/src/EFCore.Relational/Query/ExpressionVisitors/RelationalEntityQueryableExpressionVisitor.cs index 71345f0f58c..b0b3e377613 100644 --- a/src/EFCore.Relational/Query/ExpressionVisitors/RelationalEntityQueryableExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/ExpressionVisitors/RelationalEntityQueryableExpressionVisitor.cs @@ -263,15 +263,10 @@ var materializerExpression obj: null, parameters: new object[] { - _querySource, - QueryModelVisitor.QueryCompilationContext.IsTrackingQuery - && !entityType.IsQueryType, - entityType.FindPrimaryKey(), - materializer, - materializerExpression, - typeIndexMap, - QueryModelVisitor.QueryCompilationContext.IsQueryBufferRequired - && !entityType.IsQueryType + _querySource, QueryModelVisitor.QueryCompilationContext.IsTrackingQuery + && !entityType.IsQueryType, + entityType.FindPrimaryKey(), materializer, materializerExpression, typeIndexMap, QueryModelVisitor.QueryCompilationContext.IsQueryBufferRequired + && !entityType.IsQueryType }); } else diff --git a/src/EFCore.Relational/Query/ExpressionVisitors/SqlTranslatingExpressionVisitor.cs b/src/EFCore.Relational/Query/ExpressionVisitors/SqlTranslatingExpressionVisitor.cs index b1dc366b98c..27e679a7021 100644 --- a/src/EFCore.Relational/Query/ExpressionVisitors/SqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/ExpressionVisitors/SqlTranslatingExpressionVisitor.cs @@ -615,10 +615,10 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp // (this supports joining on an indexed property) var operand = methodCallExpression.Method.IsEFIndexer() - ? null - : _queryModelVisitor.QueryCompilationContext.Model.Relational().FindDbFunction(methodCallExpression.Method) != null - ? methodCallExpression.Object - : Visit(methodCallExpression.Object); + ? null + : _queryModelVisitor.QueryCompilationContext.Model.Relational().FindDbFunction(methodCallExpression.Method) != null + ? methodCallExpression.Object + : Visit(methodCallExpression.Object); if (operand != null || methodCallExpression.Object == null) @@ -759,7 +759,7 @@ private Expression TryBindQuerySourcePropertyExpression(MemberExpression memberE ?.GetProjectionForMemberInfo(memberExpression.Member); return _topLevelPredicate != null - && sql is AliasExpression aliasExpression + && sql is AliasExpression aliasExpression ? aliasExpression.Expression : sql; } diff --git a/src/EFCore.Relational/Query/ExpressionVisitors/SqlTranslatingExpressionVisitorDependencies.cs b/src/EFCore.Relational/Query/ExpressionVisitors/SqlTranslatingExpressionVisitorDependencies.cs index 4c131270486..98897664436 100644 --- a/src/EFCore.Relational/Query/ExpressionVisitors/SqlTranslatingExpressionVisitorDependencies.cs +++ b/src/EFCore.Relational/Query/ExpressionVisitors/SqlTranslatingExpressionVisitorDependencies.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Query.ExpressionTranslators; using Microsoft.EntityFrameworkCore.Storage; diff --git a/src/EFCore.Relational/Query/Expressions/AliasExpression.cs b/src/EFCore.Relational/Query/Expressions/AliasExpression.cs index fdbae1c0339..be926606831 100644 --- a/src/EFCore.Relational/Query/Expressions/AliasExpression.cs +++ b/src/EFCore.Relational/Query/Expressions/AliasExpression.cs @@ -108,7 +108,7 @@ public override bool Equals(object obj) return ReferenceEquals(this, obj) ? true : obj.GetType() == GetType() - && Equals((AliasExpression)obj); + && Equals((AliasExpression)obj); } private bool Equals(AliasExpression other) diff --git a/src/EFCore.Relational/Query/Expressions/CaseExpression.cs b/src/EFCore.Relational/Query/Expressions/CaseExpression.cs index a1a1f34c879..5d13154f37c 100644 --- a/src/EFCore.Relational/Query/Expressions/CaseExpression.cs +++ b/src/EFCore.Relational/Query/Expressions/CaseExpression.cs @@ -20,7 +20,7 @@ namespace Microsoft.EntityFrameworkCore.Query.Expressions public class CaseExpression : Expression, IPrintable { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The list of when clauses. public CaseExpression([NotNull] params CaseWhenClause[] whenClauses) @@ -29,7 +29,7 @@ public CaseExpression([NotNull] params CaseWhenClause[] whenClauses) } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The case operand expression. /// The list of when clauses. @@ -39,7 +39,7 @@ public CaseExpression([CanBeNull] Expression operand, [NotNull] params CaseWhenC } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The list of when clauses. /// The else result expression. @@ -49,7 +49,7 @@ public CaseExpression([NotNull] IReadOnlyList whenClauses, [CanB } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The case operand expression. /// The list of when clauses. @@ -66,7 +66,8 @@ public CaseExpression([NotNull] IReadOnlyList whenClauses, [CanB foreach (var whenClause in whenClauses) { - if (operand != null && whenClause.Test.Type != expectedWhenOperandType) + if (operand != null + && whenClause.Test.Type != expectedWhenOperandType) { throw new ArgumentException( RelationalStrings.CaseWhenClauseTestTypeUnexpected( @@ -74,6 +75,7 @@ public CaseExpression([NotNull] IReadOnlyList whenClauses, [CanB expectedWhenOperandType), nameof(whenClauses)); } + if (whenClause.Result.Type != resultType) { throw new ArgumentException( @@ -82,7 +84,8 @@ public CaseExpression([NotNull] IReadOnlyList whenClauses, [CanB } } - if (elseResult != null && elseResult.Type != resultType) + if (elseResult != null + && elseResult.Type != resultType) { throw new ArgumentException( RelationalStrings.CaseElseResultTypeUnexpected(elseResult.Type, resultType), @@ -111,16 +114,16 @@ public CaseExpression([NotNull] IReadOnlyList whenClauses, [CanB public virtual Expression ElseResult { get; } /// - /// Gets the node type of this . + /// Gets the node type of this . /// - /// One of the values. + /// One of the values. public override ExpressionType NodeType => ExpressionType.Extension; /// - /// Gets the static type of the expression that this represents. + /// Gets the static type of the expression that this represents. /// - /// The that represents the static type of the expression. + /// The that represents the static type of the expression. public override Type Type { get; } /// @@ -187,12 +190,12 @@ public override bool Equals(object obj) private bool Equals(CaseExpression other) => (Operand == null - ? other.Operand == null - : Operand.Equals(other.Operand)) - && Enumerable.SequenceEqual(WhenClauses, other.WhenClauses, EqualityComparer.Default) - && (ElseResult == null - ? other.ElseResult == null - : ElseResult.Equals(other.ElseResult)); + ? other.Operand == null + : Operand.Equals(other.Operand)) + && WhenClauses.SequenceEqual(other.WhenClauses, EqualityComparer.Default) + && (ElseResult == null + ? other.ElseResult == null + : ElseResult.Equals(other.ElseResult)); /// /// Gets a hash code for the current object. diff --git a/src/EFCore.Relational/Query/Expressions/CaseWhenClause.cs b/src/EFCore.Relational/Query/Expressions/CaseWhenClause.cs index 8091c69f36c..a6608b4c9d6 100644 --- a/src/EFCore.Relational/Query/Expressions/CaseWhenClause.cs +++ b/src/EFCore.Relational/Query/Expressions/CaseWhenClause.cs @@ -8,12 +8,12 @@ namespace Microsoft.EntityFrameworkCore.Query.Expressions { /// - /// Represents one when clause of a . + /// Represents one when clause of a . /// public class CaseWhenClause { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The when operand expression. /// The result expression. @@ -55,11 +55,11 @@ public override bool Equals(object obj) private bool Equals(CaseWhenClause other) => (Test == null - ? other.Test == null - : Test.Equals(other.Test)) - && (Result == null - ? other.Result == null - : Result.Equals(other.Result)); + ? other.Test == null + : Test.Equals(other.Test)) + && (Result == null + ? other.Result == null + : Result.Equals(other.Result)); /// /// Gets a hash code for the current object. diff --git a/src/EFCore.Relational/Query/Expressions/ColumnExpression.cs b/src/EFCore.Relational/Query/Expressions/ColumnExpression.cs index d5df8f6a5d8..a61fce9f943 100644 --- a/src/EFCore.Relational/Query/Expressions/ColumnExpression.cs +++ b/src/EFCore.Relational/Query/Expressions/ColumnExpression.cs @@ -124,7 +124,7 @@ public override bool Equals(object obj) return ReferenceEquals(this, obj) ? true : obj.GetType() == GetType() - && Equals((ColumnExpression)obj); + && Equals((ColumnExpression)obj); } private bool Equals([NotNull] ColumnExpression other) diff --git a/src/EFCore.Relational/Query/Expressions/InExpression.cs b/src/EFCore.Relational/Query/Expressions/InExpression.cs index 75637f0a35c..4c71fb4859b 100644 --- a/src/EFCore.Relational/Query/Expressions/InExpression.cs +++ b/src/EFCore.Relational/Query/Expressions/InExpression.cs @@ -171,7 +171,7 @@ private bool Equals(InExpression other) => Operand.Equals(other.Operand) && (Values == null ? other.Values == null - : ExpressionEqualityComparer.Instance.SequenceEquals(Values, other.Values)) + : ExpressionEqualityComparer.Instance.SequenceEquals(Values, other.Values)) && (SubQuery == null ? other.SubQuery == null : SubQuery.Equals(other.SubQuery)); diff --git a/src/EFCore.Relational/Query/Expressions/LikeExpression.cs b/src/EFCore.Relational/Query/Expressions/LikeExpression.cs index 9199e773376..82910261d70 100644 --- a/src/EFCore.Relational/Query/Expressions/LikeExpression.cs +++ b/src/EFCore.Relational/Query/Expressions/LikeExpression.cs @@ -136,6 +136,7 @@ public override bool Equals(object obj) return ReferenceEquals(this, obj) ? true : obj.GetType() == GetType() && Equals((LikeExpression)obj); } + private bool Equals(LikeExpression other) => ExpressionEqualityComparer.Instance.Equals(Match, other.Match) && ExpressionEqualityComparer.Instance.Equals(Pattern, other.Pattern) diff --git a/src/EFCore.Relational/Query/Expressions/SelectExpression.cs b/src/EFCore.Relational/Query/Expressions/SelectExpression.cs index 3087b941da9..f2c59165b0c 100644 --- a/src/EFCore.Relational/Query/Expressions/SelectExpression.cs +++ b/src/EFCore.Relational/Query/Expressions/SelectExpression.cs @@ -125,8 +125,7 @@ internal void DetachContext() public virtual TableExpressionBase ProjectStarTable { get => _projectStarTable ?? (_tables.Count == 1 ? _tables.Single() : null); - [param: CanBeNull] - set => _projectStarTable = value; + [param: CanBeNull] set => _projectStarTable = value; } /// @@ -775,7 +774,7 @@ private RelationalTypeMapping FindResultTypeMapping(Expression e) case ConditionalExpression conditionalExpression: return FindResultTypeMapping(conditionalExpression.IfTrue) - ?? FindResultTypeMapping(conditionalExpression.IfFalse); + ?? FindResultTypeMapping(conditionalExpression.IfFalse); case SqlFunctionExpression sqlFunctionExpression: return sqlFunctionExpression.ResultTypeMapping; @@ -872,8 +871,8 @@ private Expression CreateUniqueProjection(Expression expression, string newAlias } var currentOrderingIndex = _orderBy.FindIndex( - e => e.Expression.Equals(expression) - || e.Expression.Equals(removedProjection)); + e => e.Expression.Equals(expression) + || e.Expression.Equals(removedProjection)); if (currentOrderingIndex != -1) { var oldOrdering = _orderBy[currentOrderingIndex]; diff --git a/src/EFCore.Relational/Query/Expressions/SqlFunctionExpression.cs b/src/EFCore.Relational/Query/Expressions/SqlFunctionExpression.cs index 708a5c4d508..72aa5b4be94 100644 --- a/src/EFCore.Relational/Query/Expressions/SqlFunctionExpression.cs +++ b/src/EFCore.Relational/Query/Expressions/SqlFunctionExpression.cs @@ -263,6 +263,7 @@ public class SqlFunctionExpression : Expression RelationalStrings.SqlFunctionArgumentsAndMappingsMismatch, nameof(argumentTypeMappings)); } + if (ArgumentTypeMappings.Any(m => m == null)) { throw new ArgumentException( diff --git a/src/EFCore.Relational/Query/Internal/AsyncQueryingEnumerable.cs b/src/EFCore.Relational/Query/Internal/AsyncQueryingEnumerable.cs index bd559fa5de1..f12902e547a 100644 --- a/src/EFCore.Relational/Query/Internal/AsyncQueryingEnumerable.cs +++ b/src/EFCore.Relational/Query/Internal/AsyncQueryingEnumerable.cs @@ -222,6 +222,7 @@ public void Dispose() _relationalQueryContext.Connection?.Close(); } + _relationalQueryContext.Connection?.UnregisterBufferable(this); _disposed = true; diff --git a/src/EFCore.Relational/Query/Internal/QueryingEnumerable.cs b/src/EFCore.Relational/Query/Internal/QueryingEnumerable.cs index 87a8c99cb1c..490898bd57e 100644 --- a/src/EFCore.Relational/Query/Internal/QueryingEnumerable.cs +++ b/src/EFCore.Relational/Query/Internal/QueryingEnumerable.cs @@ -209,6 +209,7 @@ public void Dispose() _relationalQueryContext.Connection?.Close(); } + _relationalQueryContext.Connection?.UnregisterBufferable(this); _disposed = true; diff --git a/src/EFCore.Relational/Query/Internal/RelationalEvaluatableExpressionFilter.cs b/src/EFCore.Relational/Query/Internal/RelationalEvaluatableExpressionFilter.cs index 5ca96668bd4..b29ca89e021 100644 --- a/src/EFCore.Relational/Query/Internal/RelationalEvaluatableExpressionFilter.cs +++ b/src/EFCore.Relational/Query/Internal/RelationalEvaluatableExpressionFilter.cs @@ -8,7 +8,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Internal { - public class RelationalEvaluatableExpressionFilter : EvaluatableExpressionFilter { private readonly IModel _model; diff --git a/src/EFCore.Relational/Query/Internal/RelationalResultOperatorHandler.cs b/src/EFCore.Relational/Query/Internal/RelationalResultOperatorHandler.cs index e6b554f18ac..3bb52e46fa1 100644 --- a/src/EFCore.Relational/Query/Internal/RelationalResultOperatorHandler.cs +++ b/src/EFCore.Relational/Query/Internal/RelationalResultOperatorHandler.cs @@ -149,14 +149,14 @@ var handlerContext selectExpression); return relationalQueryModelVisitor.RequiresClientEval - || relationalQueryModelVisitor.RequiresClientSelectMany - || relationalQueryModelVisitor.RequiresClientJoin - || relationalQueryModelVisitor.RequiresClientFilter - || relationalQueryModelVisitor.RequiresClientOrderBy - || relationalQueryModelVisitor.RequiresClientResultOperator - || relationalQueryModelVisitor.RequiresStreamingGroupResultOperator - || !_resultHandlers.TryGetValue(resultOperator.GetType(), out var resultHandler) - || selectExpression == null + || relationalQueryModelVisitor.RequiresClientSelectMany + || relationalQueryModelVisitor.RequiresClientJoin + || relationalQueryModelVisitor.RequiresClientFilter + || relationalQueryModelVisitor.RequiresClientOrderBy + || relationalQueryModelVisitor.RequiresClientResultOperator + || relationalQueryModelVisitor.RequiresStreamingGroupResultOperator + || !_resultHandlers.TryGetValue(resultOperator.GetType(), out var resultHandler) + || selectExpression == null ? handlerContext.EvalOnClient() : resultHandler(handlerContext); } @@ -492,16 +492,16 @@ var sqlExpression break; case MethodCallExpression methodCallExpression - when methodCallExpression.IsEFProperty() - || methodCallExpression.Method.IsEFIndexer(): + when methodCallExpression.IsEFProperty() + || methodCallExpression.Method.IsEFIndexer(): sql = sqlTranslatingExpressionVisitor.Visit(methodCallExpression); memberInfoMappings[groupByKeyMemberInfo] = sql; key = new[] { sql }; break; case UnaryExpression unaryExpression - when unaryExpression.RemoveConvert() is MethodCallExpression methodCallExpression - && methodCallExpression.Method.IsEFIndexer(): + when unaryExpression.RemoveConvert() is MethodCallExpression methodCallExpression + && methodCallExpression.Method.IsEFIndexer(): sql = sqlTranslatingExpressionVisitor.Visit(methodCallExpression); memberInfoMappings[groupByKeyMemberInfo] = sql; key = new[] { sql }; @@ -1003,12 +1003,10 @@ var clientExpression clientExpression) : clientExpression; } - else - { - return sumExpression.Type.IsNullableType() - ? Expression.Convert(clientExpression, sumExpression.Type) - : clientExpression; - } + + return sumExpression.Type.IsNullableType() + ? Expression.Convert(clientExpression, sumExpression.Type) + : clientExpression; } } @@ -1066,7 +1064,7 @@ protected static void PrepareSelectExpressionForAggregate(SelectExpression selec private static bool IsGroupByAggregate(QueryModel queryModel) => queryModel.MainFromClause.FromExpression is QuerySourceReferenceExpression mainFromClauseQsre - && mainFromClauseQsre.ReferencedQuerySource.ItemType.IsGrouping(); + && mainFromClauseQsre.ReferencedQuerySource.ItemType.IsGrouping(); private static readonly MethodInfo _transformClientExpressionMethodInfo = typeof(RelationalResultOperatorHandler).GetTypeInfo() @@ -1082,6 +1080,7 @@ private static bool IsGroupByAggregate(QueryModel queryModel) private sealed class ContainsSelectExpressionVisitor : ExpressionVisitor { public bool ContainsExpressionType { get; private set; } + public override Expression Visit(Expression node) { if (node is SelectExpression) @@ -1089,9 +1088,11 @@ public override Expression Visit(Expression node) ContainsExpressionType = true; return node; } + return base.Visit(node); } } + private static bool ContainsSelect(Expression expression) { var visitor = new ContainsSelectExpressionVisitor(); diff --git a/src/EFCore.Relational/Query/RelationalQueryModelVisitor.cs b/src/EFCore.Relational/Query/RelationalQueryModelVisitor.cs index 094f6e57c6c..048cc4581fd 100644 --- a/src/EFCore.Relational/Query/RelationalQueryModelVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalQueryModelVisitor.cs @@ -199,7 +199,7 @@ protected override Expression VisitMethodCall(MethodCallExpression node) public override bool ShouldApplyDefiningQuery(IEntityType entityType, IQuerySource querySource) { return (!(entityType.FindAnnotation(RelationalAnnotationNames.TableName) is ConventionalAnnotation tableNameAnnotation) - || tableNameAnnotation?.GetConfigurationSource() == ConfigurationSource.Convention) + || tableNameAnnotation?.GetConfigurationSource() == ConfigurationSource.Convention) && QueryCompilationContext.QueryAnnotations .OfType() .All(a => a.QuerySource != querySource); @@ -695,8 +695,7 @@ var previousMapping = new Dictionary { { - queryModel.MainFromClause, - QueryCompilationContext.QuerySourceMapping + queryModel.MainFromClause, QueryCompilationContext.QuerySourceMapping .GetExpression(queryModel.MainFromClause) } }; @@ -889,11 +888,11 @@ var subQueryModelVisitor AddQuery(querySource, subSelectExpression); return new QuerySourceUpdater( - querySource, - QueryCompilationContext, - LinqOperatorProvider, - subSelectExpression) - .Visit(subQueryModelVisitor.Expression); + querySource, + QueryCompilationContext, + LinqOperatorProvider, + subSelectExpression) + .Visit(subQueryModelVisitor.Expression); } } @@ -1446,7 +1445,7 @@ internal bool IsShapedQueryExpression(Expression expression) var queryMethods = QueryCompilationContext.QueryMethodProvider; return methodCallExpression.Method.MethodIsClosedFormOf(queryMethods.ShapedQueryMethod) - || methodCallExpression.Method.MethodIsClosedFormOf(queryMethods.DefaultIfEmptyShapedQueryMethod) + || methodCallExpression.Method.MethodIsClosedFormOf(queryMethods.DefaultIfEmptyShapedQueryMethod) ? true : false; } @@ -1454,7 +1453,7 @@ internal bool IsShapedQueryExpression(Expression expression) private MethodCallExpression UnwrapShapedQueryExpression(MethodCallExpression expression) { return expression.Method.MethodIsClosedFormOf(LinqOperatorProvider.DefaultIfEmpty) - || expression.Method.MethodIsClosedFormOf(LinqOperatorProvider.DefaultIfEmptyArg) + || expression.Method.MethodIsClosedFormOf(LinqOperatorProvider.DefaultIfEmptyArg) ? (MethodCallExpression)expression.Arguments[0] : expression; } @@ -1855,10 +1854,10 @@ var referencedQuerySource = subQueryModel?.MainFromClause.FromExpression.TryGetReferencedQuerySource(); return referencedQuerySource != groupJoinClause - || queryModel.CountQuerySourceReferences(groupJoinClause) != 1 - || subQueryModel.BodyClauses.Count != 0 - || subQueryModel.ResultOperators.Count != 1 - || !(subQueryModel.ResultOperators[0] is DefaultIfEmptyResultOperator) + || queryModel.CountQuerySourceReferences(groupJoinClause) != 1 + || subQueryModel.BodyClauses.Count != 0 + || subQueryModel.ResultOperators.Count != 1 + || !(subQueryModel.ResultOperators[0] is DefaultIfEmptyResultOperator) ? false : true; } diff --git a/src/EFCore.Relational/Query/ResultOperators/Internal/FromSqlExpressionNode.cs b/src/EFCore.Relational/Query/ResultOperators/Internal/FromSqlExpressionNode.cs index 028b6a1e207..8dc5428e30d 100644 --- a/src/EFCore.Relational/Query/ResultOperators/Internal/FromSqlExpressionNode.cs +++ b/src/EFCore.Relational/Query/ResultOperators/Internal/FromSqlExpressionNode.cs @@ -20,8 +20,7 @@ public class FromSqlExpressionNode : ResultOperatorExpressionNodeBase /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - public static readonly IReadOnlyCollection SupportedMethods = new[] - { RelationalQueryableExtensions.FromSqlMethodInfo }; + public static readonly IReadOnlyCollection SupportedMethods = new[] { RelationalQueryableExtensions.FromSqlMethodInfo }; private readonly string _sql; private readonly Expression _arguments; diff --git a/src/EFCore.Relational/Query/Sql/DefaultQuerySqlGenerator.cs b/src/EFCore.Relational/Query/Sql/DefaultQuerySqlGenerator.cs index 4b91c7a3b59..430e583b1b6 100644 --- a/src/EFCore.Relational/Query/Sql/DefaultQuerySqlGenerator.cs +++ b/src/EFCore.Relational/Query/Sql/DefaultQuerySqlGenerator.cs @@ -159,7 +159,6 @@ protected virtual void GenerateTagsHeaderComment() string line; while ((line = reader.ReadLine()) != null) { - _relationalCommandBuilder.Append(SingleLineCommentToken).Append(" ").AppendLine(line); } } @@ -315,7 +314,8 @@ public virtual Expression VisitSelect(SelectExpression selectExpression) var orderByList = new List(selectExpression.OrderBy); // Filter out constant and parameter expressions (SELECT 1) if there is no skip or take #10410 - if (selectExpression.Limit == null && selectExpression.Offset == null) + if (selectExpression.Limit == null + && selectExpression.Offset == null) { orderByList.RemoveAll(o => IsOrderByExpressionConstant(ApplyOptimizations(o.Expression, searchCondition: false))); } @@ -588,11 +588,11 @@ protected virtual void GeneratePredicate([NotNull] Expression predicate) var rightBooleanConstant = GetBooleanConstantValue(binaryExpression.Right); if ((binaryExpression.NodeType == ExpressionType.Equal - && leftBooleanConstant == true - && rightBooleanConstant == true) + && leftBooleanConstant == true + && rightBooleanConstant == true) || (binaryExpression.NodeType == ExpressionType.NotEqual - && leftBooleanConstant == false - && rightBooleanConstant == false)) + && leftBooleanConstant == false + && rightBooleanConstant == false)) { return; } @@ -627,7 +627,7 @@ protected virtual void GenerateHaving([NotNull] Expression predicate) private bool IsOrderByExpressionConstant([NotNull] Expression processedExpression) { return processedExpression.RemoveConvert() is ConstantExpression - || processedExpression.RemoveConvert() is ParameterExpression; + || processedExpression.RemoveConvert() is ParameterExpression; } /// @@ -870,7 +870,7 @@ public virtual Expression VisitFromSql(FromSqlExpression fromSqlExpression) break; case NewArrayExpression newArrayExpression - when newArrayExpression.NodeType == ExpressionType.NewArrayInit: + when newArrayExpression.NodeType == ExpressionType.NewArrayInit: substitutions = new string[newArrayExpression.Expressions.Count]; for (var i = 0; i < newArrayExpression.Expressions.Count; i++) @@ -1991,7 +1991,7 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) // Convert nodes are transparent to SQL hence no conversion needed return unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked + || unaryExpression.NodeType == ExpressionType.ConvertChecked ? unaryExpression : ApplyConversion(unaryExpression); } @@ -2034,8 +2034,8 @@ protected override Expression VisitExtension(Expression extensionExpression) var newElseResult = Visit(caseExpression.ElseResult); newExpression = newOperand != caseExpression.Operand - || whenThenListChanged - || newElseResult != caseExpression.ElseResult + || whenThenListChanged + || newElseResult != caseExpression.ElseResult ? new CaseExpression(newOperand, newWhenThenList, newElseResult) : caseExpression; break; @@ -2065,17 +2065,17 @@ private static bool IsSearchCondition(Expression expression) expression = expression.RemoveConvert(); return !(expression is BinaryExpression) - && expression.NodeType != ExpressionType.Not - && expression.NodeType != ExpressionType.Extension + && expression.NodeType != ExpressionType.Not + && expression.NodeType != ExpressionType.Extension ? false : expression.IsComparisonOperation() - || expression.IsLogicalOperation() - || expression.NodeType == ExpressionType.Not - || expression is ExistsExpression - || expression is InExpression - || expression is IsNullExpression - || expression is LikeExpression - || expression is ComparisonExpression; + || expression.IsLogicalOperation() + || expression.NodeType == ExpressionType.Not + || expression is ExistsExpression + || expression is InExpression + || expression is IsNullExpression + || expression is LikeExpression + || expression is ComparisonExpression; } private static Expression BuildCompareToExpression(Expression expression, bool compareTo) diff --git a/src/EFCore.Relational/Query/Sql/ISqlExpressionVisitor.cs b/src/EFCore.Relational/Query/Sql/ISqlExpressionVisitor.cs index 1b2cb6fc30c..a072003cb4c 100644 --- a/src/EFCore.Relational/Query/Sql/ISqlExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/Sql/ISqlExpressionVisitor.cs @@ -184,7 +184,7 @@ public interface ISqlExpressionVisitor Expression VisitColumnReference([NotNull] ColumnReferenceExpression columnReferenceExpression); /// - /// Visits a case expression. + /// Visits a case expression. /// /// The case expression. /// An expression. diff --git a/src/EFCore.Relational/Scaffolding/Metadata/Internal/ScaffoldingAnnotationNames.cs b/src/EFCore.Relational/Scaffolding/Metadata/Internal/ScaffoldingAnnotationNames.cs index c50fe19fa12..e9fa6e1f40f 100644 --- a/src/EFCore.Relational/Scaffolding/Metadata/Internal/ScaffoldingAnnotationNames.cs +++ b/src/EFCore.Relational/Scaffolding/Metadata/Internal/ScaffoldingAnnotationNames.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - namespace Microsoft.EntityFrameworkCore.Scaffolding.Metadata.Internal { /// diff --git a/src/EFCore.Relational/Storage/DoubleTypeMapping.cs b/src/EFCore.Relational/Storage/DoubleTypeMapping.cs index 78a36b59fbe..9e292364325 100644 --- a/src/EFCore.Relational/Storage/DoubleTypeMapping.cs +++ b/src/EFCore.Relational/Storage/DoubleTypeMapping.cs @@ -60,10 +60,10 @@ protected override string GenerateNonNullSqlLiteral(object value) var literal = doubleValue.ToString("G17", CultureInfo.InvariantCulture); return !literal.Contains("E") - && !literal.Contains("e") - && !literal.Contains(".") - && !double.IsNaN(doubleValue) - && !double.IsInfinity(doubleValue) + && !literal.Contains("e") + && !literal.Contains(".") + && !double.IsNaN(doubleValue) + && !double.IsInfinity(doubleValue) ? literal + ".0" : literal; } diff --git a/src/EFCore.Relational/Storage/ISqlGenerationHelper.cs b/src/EFCore.Relational/Storage/ISqlGenerationHelper.cs index 29c2c799472..c4d85bde3f7 100644 --- a/src/EFCore.Relational/Storage/ISqlGenerationHelper.cs +++ b/src/EFCore.Relational/Storage/ISqlGenerationHelper.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Text; using JetBrains.Annotations; diff --git a/src/EFCore.Relational/Storage/RelationalConnection.cs b/src/EFCore.Relational/Storage/RelationalConnection.cs index 238e4914026..cc039c7b314 100644 --- a/src/EFCore.Relational/Storage/RelationalConnection.cs +++ b/src/EFCore.Relational/Storage/RelationalConnection.cs @@ -176,7 +176,7 @@ public virtual void EnlistTransaction(Transaction transaction) /// The newly created transaction. [NotNull] // ReSharper disable once RedundantNameQualifier - public virtual IDbContextTransaction BeginTransaction() => BeginTransaction(System.Data.IsolationLevel.Unspecified); + public virtual IDbContextTransaction BeginTransaction() => BeginTransaction(IsolationLevel.Unspecified); /// /// Asynchronously begins a new transaction. @@ -188,7 +188,7 @@ public virtual void EnlistTransaction(Transaction transaction) [NotNull] public virtual async Task BeginTransactionAsync(CancellationToken cancellationToken = default) // ReSharper disable once RedundantNameQualifier - => await BeginTransactionAsync(System.Data.IsolationLevel.Unspecified, cancellationToken); + => await BeginTransactionAsync(IsolationLevel.Unspecified, cancellationToken); /// /// Begins a new transaction. diff --git a/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs b/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs index 68e2feb53f1..58a71b2374c 100644 --- a/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs +++ b/src/EFCore.Relational/Storage/RelationalSqlGenerationHelper.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Text; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Utilities; @@ -72,7 +71,7 @@ public virtual string GenerateParameterNamePlaceholder(string name) /// The to write generated string to. /// The candidate name for the parameter placeholder. public virtual void GenerateParameterNamePlaceholder(StringBuilder builder, string name) - => GenerateParameterName(builder,name); + => GenerateParameterName(builder, name); /// /// Generates the escaped SQL representation of an identifier (column name, table name, etc.). diff --git a/src/EFCore.Relational/Storage/RelationalTypeMapping.cs b/src/EFCore.Relational/Storage/RelationalTypeMapping.cs index 83c25305c9a..b5f30664b40 100644 --- a/src/EFCore.Relational/Storage/RelationalTypeMapping.cs +++ b/src/EFCore.Relational/Storage/RelationalTypeMapping.cs @@ -344,8 +344,9 @@ private static string GetBaseName(string storeType) DbType? dbType = null, bool unicode = false, int? size = null) - : this(new RelationalTypeMappingParameters( - new CoreTypeMappingParameters(clrType), storeType, StoreTypePostfix.None, dbType, unicode, size)) + : this( + new RelationalTypeMappingParameters( + new CoreTypeMappingParameters(clrType), storeType, StoreTypePostfix.None, dbType, unicode, size)) { } @@ -410,7 +411,7 @@ public virtual RelationalTypeMapping Clone(in RelationalTypeMappingInfo mappingI if (!oldBehavior) { var storeTypeChanged = mappingInfo.StoreTypeNameBase != null - && !string.Equals(mappingInfo.StoreTypeNameBase, StoreTypeNameBase, StringComparison.OrdinalIgnoreCase); + && !string.Equals(mappingInfo.StoreTypeNameBase, StoreTypeNameBase, StringComparison.OrdinalIgnoreCase); clone = storeTypeChanged ? Clone(Parameters.WithTypeMappingInfo(mappingInfo)) diff --git a/src/EFCore.Relational/Storage/RelationalTypeMappingSourceDependencies.cs b/src/EFCore.Relational/Storage/RelationalTypeMappingSourceDependencies.cs index 1bf964e5c25..15102268963 100644 --- a/src/EFCore.Relational/Storage/RelationalTypeMappingSourceDependencies.cs +++ b/src/EFCore.Relational/Storage/RelationalTypeMappingSourceDependencies.cs @@ -59,7 +59,7 @@ public sealed class RelationalTypeMappingSourceDependencies /// A replacement for the current dependency of this type. /// A new parameter object with the given service replaced. public RelationalTypeMappingSourceDependencies With( - [NotNull] IEnumerable plugins) + [NotNull] IEnumerable plugins) => new RelationalTypeMappingSourceDependencies(plugins); } } diff --git a/src/EFCore.Relational/Update/Internal/ModificationCommandComparer.cs b/src/EFCore.Relational/Update/Internal/ModificationCommandComparer.cs index 8d13f7bd28a..b98dc6ec85b 100644 --- a/src/EFCore.Relational/Update/Internal/ModificationCommandComparer.cs +++ b/src/EFCore.Relational/Update/Internal/ModificationCommandComparer.cs @@ -121,7 +121,7 @@ public virtual int Compare(ModificationCommand x, ModificationCommand y) (typeof(IStructuralComparable).IsAssignableFrom(type) ? _structuralCompareMethod : _compareMethod) - .MakeGenericMethod(t), + .MakeGenericMethod(t), Expression.Convert(xParameter, t), Expression.Convert(yParameter, t)), xParameter, diff --git a/src/EFCore.SqlServer.NTS/Extensions/SqlServerNetTopologySuiteDbContextOptionsBuilderExtensions.cs b/src/EFCore.SqlServer.NTS/Extensions/SqlServerNetTopologySuiteDbContextOptionsBuilderExtensions.cs index fe2281034fd..516b453bebe 100644 --- a/src/EFCore.SqlServer.NTS/Extensions/SqlServerNetTopologySuiteDbContextOptionsBuilderExtensions.cs +++ b/src/EFCore.SqlServer.NTS/Extensions/SqlServerNetTopologySuiteDbContextOptionsBuilderExtensions.cs @@ -9,7 +9,7 @@ namespace Microsoft.EntityFrameworkCore { /// - /// NetTopologySuite specific extension methods for . + /// NetTopologySuite specific extension methods for . /// public static class SqlServerNetTopologySuiteDbContextOptionsBuilderExtensions { @@ -26,7 +26,7 @@ public static class SqlServerNetTopologySuiteDbContextOptionsBuilderExtensions var coreOptionsBuilder = ((IRelationalDbContextOptionsBuilderInfrastructure)optionsBuilder).OptionsBuilder; var extension = coreOptionsBuilder.Options.FindExtension() - ?? new SqlServerNetTopologySuiteOptionsExtension(); + ?? new SqlServerNetTopologySuiteOptionsExtension(); ((IDbContextOptionsBuilderInfrastructure)coreOptionsBuilder).AddOrUpdateExtension(extension); diff --git a/src/EFCore.SqlServer.NTS/Infrastructure/Internal/SqlServerNetTopologySuiteOptionsExtension.cs b/src/EFCore.SqlServer.NTS/Infrastructure/Internal/SqlServerNetTopologySuiteOptionsExtension.cs index 77c3467140c..37127064cd3 100644 --- a/src/EFCore.SqlServer.NTS/Infrastructure/Internal/SqlServerNetTopologySuiteOptionsExtension.cs +++ b/src/EFCore.SqlServer.NTS/Infrastructure/Internal/SqlServerNetTopologySuiteOptionsExtension.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.SqlServer.Internal; diff --git a/src/EFCore.SqlServer.NTS/Internal/SqlServerNetTopologySuiteExpressionExtensions.cs b/src/EFCore.SqlServer.NTS/Internal/SqlServerNetTopologySuiteExpressionExtensions.cs index eb0245aed09..ed887901136 100644 --- a/src/EFCore.SqlServer.NTS/Internal/SqlServerNetTopologySuiteExpressionExtensions.cs +++ b/src/EFCore.SqlServer.NTS/Internal/SqlServerNetTopologySuiteExpressionExtensions.cs @@ -44,34 +44,37 @@ private static IEnumerable FindProperties([NotNull] this Expression e { yield return property; } + break; case SqlFunctionExpression functionExpression: + { + IEnumerable arguments = functionExpression.Arguments; + if (functionExpression.Instance != null) { - IEnumerable arguments = functionExpression.Arguments; - if (functionExpression.Instance != null) - { - arguments = arguments.Concat(new[] { functionExpression.Instance }); - } - foreach (var property in arguments.SelectMany(FindProperties)) - { - yield return property; - } + arguments = arguments.Concat(new[] { functionExpression.Instance }); + } + + foreach (var property in arguments.SelectMany(FindProperties)) + { + yield return property; } + } break; case MethodCallExpression methodCallExpression: + { + IEnumerable arguments = methodCallExpression.Arguments; + if (methodCallExpression.Object != null) { - IEnumerable arguments = methodCallExpression.Arguments; - if (methodCallExpression.Object != null) - { - arguments = arguments.Concat(new[] { methodCallExpression.Object }); - } - foreach (var property in arguments.SelectMany(FindProperties)) - { - yield return property; - } + arguments = arguments.Concat(new[] { methodCallExpression.Object }); } + + foreach (var property in arguments.SelectMany(FindProperties)) + { + yield return property; + } + } break; case MemberExpression memberExpression: @@ -79,6 +82,7 @@ private static IEnumerable FindProperties([NotNull] this Expression e { yield return property; } + break; } } diff --git a/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerCurveMemberTranslator.cs b/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerCurveMemberTranslator.cs index 0f39e9774b3..c8a9647669a 100644 --- a/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerCurveMemberTranslator.cs +++ b/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerCurveMemberTranslator.cs @@ -24,7 +24,7 @@ public class SqlServerCurveMemberTranslator : IMemberTranslator { { typeof(ICurve).GetRuntimeProperty(nameof(ICurve.EndPoint)), "STEndPoint" }, { typeof(ICurve).GetRuntimeProperty(nameof(ICurve.IsClosed)), "STIsClosed" }, - { typeof(ICurve).GetRuntimeProperty(nameof(ICurve.StartPoint)), "STStartPoint" }, + { typeof(ICurve).GetRuntimeProperty(nameof(ICurve.StartPoint)), "STStartPoint" } }; private static readonly MemberInfo _isRing = typeof(ICurve).GetRuntimeProperty(nameof(ICurve.IsRing)); @@ -68,7 +68,9 @@ public virtual Expression Translate(MemberExpression memberExpression) Enumerable.Empty(), resultTypeMapping); } - else if (!isGeography && Equals(member, _isRing)) + + if (!isGeography + && Equals(member, _isRing)) { return new SqlFunctionExpression( memberExpression.Expression, diff --git a/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerGeometryMemberTranslator.cs b/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerGeometryMemberTranslator.cs index b7ef99c7c78..e116f4a6ef1 100644 --- a/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerGeometryMemberTranslator.cs +++ b/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerGeometryMemberTranslator.cs @@ -85,9 +85,10 @@ public virtual Expression Translate(MemberExpression memberExpression) Enumerable.Empty(), resultTypeMapping); } + if (Equals(member, _ogcGeometryType)) { - var whenThenList = new List() + var whenThenList = new List { new CaseWhenClause(Expression.Constant("Point"), Expression.Constant(OgcGeometryType.Point)), new CaseWhenClause(Expression.Constant("LineString"), Expression.Constant(OgcGeometryType.LineString)), @@ -113,6 +114,7 @@ public virtual Expression Translate(MemberExpression memberExpression) Enumerable.Empty()), whenThenList.ToArray()); } + if (Equals(member, _srid)) { return new SqlFunctionExpression( diff --git a/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerGeometryMethodTranslator.cs b/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerGeometryMethodTranslator.cs index 273d9e7808f..6975a4f626c 100644 --- a/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerGeometryMethodTranslator.cs +++ b/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerGeometryMethodTranslator.cs @@ -93,6 +93,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) argumentTypeMappings[i] = _typeMappingSource.FindMapping(type); } } + if (!anyGeometryArguments) { argumentTypeMappings = null; @@ -113,6 +114,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) _typeMappingSource.FindMapping(methodCallExpression.Object.Type, storeType), argumentTypeMappings); } + if (Equals(method, _getGeometryN)) { return new SqlFunctionExpression( @@ -122,6 +124,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) new[] { Expression.Add(methodCallExpression.Arguments[0], Expression.Constant(1)) }, _typeMappingSource.FindMapping(typeof(IGeometry), storeType)); } + if (Equals(method, _isWithinDistance)) { return Expression.LessThanOrEqual( diff --git a/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerNetTopologySuiteMemberTranslatorPlugin.cs b/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerNetTopologySuiteMemberTranslatorPlugin.cs index a2e114249e5..e9a3c3d6eb8 100644 --- a/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerNetTopologySuiteMemberTranslatorPlugin.cs +++ b/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerNetTopologySuiteMemberTranslatorPlugin.cs @@ -19,16 +19,7 @@ public class SqlServerNetTopologySuiteMemberTranslatorPlugin : IMemberTranslator /// public SqlServerNetTopologySuiteMemberTranslatorPlugin(IRelationalTypeMappingSource typeMappingSource) { - Translators = new IMemberTranslator[] - { - new SqlServerCurveMemberTranslator(typeMappingSource), - new SqlServerGeometryMemberTranslator(typeMappingSource), - new SqlServerGeometryCollectionMemberTranslator(), - new SqlServerLineStringMemberTranslator(), - new SqlServerMultiCurveMemberTranslator(), - new SqlServerPointMemberTranslator(), - new SqlServerPolygonMemberTranslator(typeMappingSource) - }; + Translators = new IMemberTranslator[] { new SqlServerCurveMemberTranslator(typeMappingSource), new SqlServerGeometryMemberTranslator(typeMappingSource), new SqlServerGeometryCollectionMemberTranslator(), new SqlServerLineStringMemberTranslator(), new SqlServerMultiCurveMemberTranslator(), new SqlServerPointMemberTranslator(), new SqlServerPolygonMemberTranslator(typeMappingSource) }; } /// diff --git a/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerPolygonMemberTranslator.cs b/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerPolygonMemberTranslator.cs index a6bc5ba9d1d..9fc737ae37a 100644 --- a/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerPolygonMemberTranslator.cs +++ b/src/EFCore.SqlServer.NTS/Query/ExpressionTranslators/Internal/SqlServerPolygonMemberTranslator.cs @@ -64,7 +64,8 @@ public virtual Expression Translate(MemberExpression memberExpression) new[] { Expression.Constant(1) }, _typeMappingSource.FindMapping(typeof(ILineString), storeType)); } - else if (Equals(_numInteriorRings, member)) + + if (Equals(_numInteriorRings, member)) { return Expression.Subtract( new SqlFunctionExpression( diff --git a/src/EFCore.SqlServer.NTS/Storage/Internal/SqlServerGeometryTypeMapping.cs b/src/EFCore.SqlServer.NTS/Storage/Internal/SqlServerGeometryTypeMapping.cs index ace3a309ade..a9e83ffbc72 100644 --- a/src/EFCore.SqlServer.NTS/Storage/Internal/SqlServerGeometryTypeMapping.cs +++ b/src/EFCore.SqlServer.NTS/Storage/Internal/SqlServerGeometryTypeMapping.cs @@ -36,10 +36,10 @@ public class SqlServerGeometryTypeMapping : RelationalGeometryTypeMap [UsedImplicitly] public SqlServerGeometryTypeMapping(IGeometryServices geometryServices, string storeType) : base( - new GeometryValueConverter( - CreateReader(geometryServices, IsGeography(storeType)), - CreateWriter(IsGeography(storeType))), - storeType) + new GeometryValueConverter( + CreateReader(geometryServices, IsGeography(storeType)), + CreateWriter(IsGeography(storeType))), + storeType) => _isGeography = IsGeography(storeType); /// @@ -132,10 +132,16 @@ protected override void ConfigureParameter(DbParameter parameter) } private static SqlServerBytesReader CreateReader(IGeometryServices services, bool isGeography) - => new SqlServerBytesReader(services) { IsGeography = isGeography }; + => new SqlServerBytesReader(services) + { + IsGeography = isGeography + }; private static SqlServerBytesWriter CreateWriter(bool isGeography) - => new SqlServerBytesWriter { IsGeography = isGeography }; + => new SqlServerBytesWriter + { + IsGeography = isGeography + }; private static bool IsGeography(string storeType) => string.Equals(storeType, "geography", StringComparison.OrdinalIgnoreCase); diff --git a/src/EFCore.SqlServer.NTS/Storage/ValueConversion/Internal/GeometryValueConverter.cs b/src/EFCore.SqlServer.NTS/Storage/ValueConversion/Internal/GeometryValueConverter.cs index ac760e98b10..100bab57ed2 100644 --- a/src/EFCore.SqlServer.NTS/Storage/ValueConversion/Internal/GeometryValueConverter.cs +++ b/src/EFCore.SqlServer.NTS/Storage/ValueConversion/Internal/GeometryValueConverter.cs @@ -13,7 +13,7 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.Storage.ValueConversion.Intern /// directly from your code. This API may change or be removed in future releases. /// public class GeometryValueConverter : ValueConverter - where TGeometry : IGeometry + where TGeometry : IGeometry { /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore.SqlServer/Diagnostics/SqlServerEventId.cs b/src/EFCore.SqlServer/Diagnostics/SqlServerEventId.cs index 7e8c788423c..8d6b343fb84 100644 --- a/src/EFCore.SqlServer/Diagnostics/SqlServerEventId.cs +++ b/src/EFCore.SqlServer/Diagnostics/SqlServerEventId.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Diagnostics; using Microsoft.Extensions.Logging; diff --git a/src/EFCore.SqlServer/Extensions/SqlServerDbContextOptionsBuilderExtensions.cs b/src/EFCore.SqlServer/Extensions/SqlServerDbContextOptionsBuilderExtensions.cs index 98ef5767608..de8a3f97798 100644 --- a/src/EFCore.SqlServer/Extensions/SqlServerDbContextOptionsBuilderExtensions.cs +++ b/src/EFCore.SqlServer/Extensions/SqlServerDbContextOptionsBuilderExtensions.cs @@ -90,11 +90,14 @@ public static class SqlServerDbContextOptionsExtensions (DbContextOptionsBuilder)optionsBuilder, connectionString, sqlServerOptionsAction); /// - /// Configures the context to connect to a Microsoft SQL Server database. + /// Configures the context to connect to a Microsoft SQL Server database. /// /// The type of context to be configured. /// The builder being used to configure the context. - /// An action to configure the database connection string by using . + /// + /// An action to configure the database connection string by using + /// . + /// /// An optional action to allow additional SQL Server specific configuration. /// The options builder so that further configuration can be chained. public static DbContextOptionsBuilder UseSqlServer( @@ -106,10 +109,13 @@ public static class SqlServerDbContextOptionsExtensions (DbContextOptionsBuilder)optionsBuilder, connectionStringBuilderAction, sqlServerOptionsAction); /// - /// Configures the context to connect to a Microsoft SQL Server database. + /// Configures the context to connect to a Microsoft SQL Server database. /// /// The builder being used to configure the context. - /// An action to configure the database connection string by using . + /// + /// An action to configure the database connection string by using + /// . + /// /// An optional action to allow additional SQL Server specific configuration. /// The options builder so that further configuration can be chained. public static DbContextOptionsBuilder UseSqlServer( @@ -119,7 +125,7 @@ public static class SqlServerDbContextOptionsExtensions { Check.NotNull(connectionStringBuilderAction, nameof(connectionStringBuilderAction)); - var connectionStringBuilder = new SqlConnectionStringBuilder() + var connectionStringBuilder = new SqlConnectionStringBuilder { ConnectRetryCount = 0 }; @@ -127,6 +133,7 @@ public static class SqlServerDbContextOptionsExtensions { connectionStringBuilder.InitialCatalog = optionsBuilder.Options.ContextType.Name; } + connectionStringBuilderAction(connectionStringBuilder); return UseSqlServer(optionsBuilder, connectionStringBuilder.ConnectionString, sqlServerOptionsAction); diff --git a/src/EFCore.SqlServer/Infrastructure/SqlServerDbContextOptionsBuilder.cs b/src/EFCore.SqlServer/Infrastructure/SqlServerDbContextOptionsBuilder.cs index 8ccc0720820..e4e3b17db90 100644 --- a/src/EFCore.SqlServer/Infrastructure/SqlServerDbContextOptionsBuilder.cs +++ b/src/EFCore.SqlServer/Infrastructure/SqlServerDbContextOptionsBuilder.cs @@ -16,7 +16,7 @@ namespace Microsoft.EntityFrameworkCore.Infrastructure /// /// Instances of this class are returned from a call to /// + /// cref="SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder,string,System.Action{Microsoft.EntityFrameworkCore.Infrastructure.SqlServerDbContextOptionsBuilder}(Microsoft.EntityFrameworkCore.Infrastructure.SqlServerDbContextOptionsBuilder))" /> /// and it is not designed to be directly constructed in your application code. /// /// diff --git a/src/EFCore.SqlServer/Internal/SqlServerModelValidator.cs b/src/EFCore.SqlServer/Internal/SqlServerModelValidator.cs index a48a23c0604..5b813069e28 100644 --- a/src/EFCore.SqlServer/Internal/SqlServerModelValidator.cs +++ b/src/EFCore.SqlServer/Internal/SqlServerModelValidator.cs @@ -253,7 +253,7 @@ protected override void ValidateSharedColumnsCompatibility(IReadOnlyList The command builder to use to add the SQL fragment. protected override void IndexOptions(CreateIndexOperation operation, IModel model, MigrationCommandListBuilder builder) { - if (operation[SqlServerAnnotationNames.Include] is IReadOnlyList includeProperties && includeProperties.Count > 0) + if (operation[SqlServerAnnotationNames.Include] is IReadOnlyList includeProperties + && includeProperties.Count > 0) { builder.Append(" INCLUDE ("); for (var i = 0; i < includeProperties.Count; i++) @@ -1523,6 +1524,7 @@ protected override void IndexOptions(CreateIndexOperation operation, IModel mode builder.Append(", "); } } + builder.Append(")"); } diff --git a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerCompositeMethodCallTranslator.cs b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerCompositeMethodCallTranslator.cs index 2163ef3d488..51805e0a4a4 100644 --- a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerCompositeMethodCallTranslator.cs +++ b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerCompositeMethodCallTranslator.cs @@ -12,29 +12,7 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.Query.ExpressionTranslators.In /// public class SqlServerCompositeMethodCallTranslator : RelationalCompositeMethodCallTranslator { - private static readonly IMethodCallTranslator[] _methodCallTranslators = - { - new SqlServerContainsOptimizedTranslator(), - new SqlServerConvertTranslator(), - new SqlServerDateAddTranslator(), - new SqlServerDateDiffTranslator(), - new SqlServerEndsWithOptimizedTranslator(), - new SqlServerFullTextSearchMethodCallTranslator(), - new SqlServerMathTranslator(), - new SqlServerNewGuidTranslator(), - new SqlServerObjectToStringTranslator(), - new SqlServerStartsWithOptimizedTranslator(), - new SqlServerStringIsNullOrWhiteSpaceTranslator(), - new SqlServerStringReplaceTranslator(), - new SqlServerStringSubstringTranslator(), - new SqlServerStringToLowerTranslator(), - new SqlServerStringToUpperTranslator(), - new SqlServerStringTrimEndTranslator(), - new SqlServerStringTrimStartTranslator(), - new SqlServerStringTrimTranslator(), - new SqlServerStringIndexOfTranslator(), - new SqlServerStringConcatMethodCallTranslator() - }; + private static readonly IMethodCallTranslator[] _methodCallTranslators = { new SqlServerContainsOptimizedTranslator(), new SqlServerConvertTranslator(), new SqlServerDateAddTranslator(), new SqlServerDateDiffTranslator(), new SqlServerEndsWithOptimizedTranslator(), new SqlServerFullTextSearchMethodCallTranslator(), new SqlServerMathTranslator(), new SqlServerNewGuidTranslator(), new SqlServerObjectToStringTranslator(), new SqlServerStartsWithOptimizedTranslator(), new SqlServerStringIsNullOrWhiteSpaceTranslator(), new SqlServerStringReplaceTranslator(), new SqlServerStringSubstringTranslator(), new SqlServerStringToLowerTranslator(), new SqlServerStringToUpperTranslator(), new SqlServerStringTrimEndTranslator(), new SqlServerStringTrimStartTranslator(), new SqlServerStringTrimTranslator(), new SqlServerStringIndexOfTranslator(), new SqlServerStringConcatMethodCallTranslator() }; /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateAddTranslator.cs b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateAddTranslator.cs index 821d099a68a..679dfa5f689 100644 --- a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateAddTranslator.cs +++ b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateAddTranslator.cs @@ -49,20 +49,15 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) var amountToAdd = methodCallExpression.Arguments.First(); return !datePart.Equals("year") - && !datePart.Equals("month") - && amountToAdd is ConstantExpression constantExpression - && ((double)constantExpression.Value >= int.MaxValue - || (double)constantExpression.Value <= int.MinValue) + && !datePart.Equals("month") + && amountToAdd is ConstantExpression constantExpression + && ((double)constantExpression.Value >= int.MaxValue + || (double)constantExpression.Value <= int.MinValue) ? null : new SqlFunctionExpression( - functionName: "DATEADD", - returnType: methodCallExpression.Type, - arguments: new[] - { - new SqlFragmentExpression(datePart), - amountToAdd, - methodCallExpression.Object - }); + functionName: "DATEADD", + returnType: methodCallExpression.Type, + arguments: new[] { new SqlFragmentExpression(datePart), amountToAdd, methodCallExpression.Object }); } return null; diff --git a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateDiffTranslator.cs b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateDiffTranslator.cs index e1f147734b8..54627a9acdd 100644 --- a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateDiffTranslator.cs +++ b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateDiffTranslator.cs @@ -250,12 +250,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) ? new SqlFunctionExpression( functionName: "DATEDIFF", returnType: methodCallExpression.Type, - arguments: new[] - { - new SqlFragmentExpression(datePart), - methodCallExpression.Arguments[1], - methodCallExpression.Arguments[2] - }) + arguments: new[] { new SqlFragmentExpression(datePart), methodCallExpression.Arguments[1], methodCallExpression.Arguments[2] }) : null; } } diff --git a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateTimeMemberTranslator.cs b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateTimeMemberTranslator.cs index 8328681266f..428cfb6b282 100644 --- a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateTimeMemberTranslator.cs +++ b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerDateTimeMemberTranslator.cs @@ -72,11 +72,7 @@ public virtual Expression Translate(MemberExpression memberExpression) return new SqlFunctionExpression( "CONVERT", memberExpression.Type, - new Expression[] - { - new SqlFragmentExpression("date"), - new SqlFunctionExpression("GETDATE", memberExpression.Type) - }); + new Expression[] { new SqlFragmentExpression("date"), new SqlFunctionExpression("GETDATE", memberExpression.Type) }); case nameof(DateTime.TimeOfDay): return new ExplicitCastExpression( diff --git a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerEndsWithOptimizedTranslator.cs b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerEndsWithOptimizedTranslator.cs index 27ed4e3d26d..46970eb7b3d 100644 --- a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerEndsWithOptimizedTranslator.cs +++ b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerEndsWithOptimizedTranslator.cs @@ -33,11 +33,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) "RIGHT", // ReSharper disable once PossibleNullReferenceException methodCallExpression.Object.Type, - new[] - { - methodCallExpression.Object, - new SqlFunctionExpression("LEN", typeof(int), new[] { patternExpression }) - }), + new[] { methodCallExpression.Object, new SqlFunctionExpression("LEN", typeof(int), new[] { patternExpression }) }), patternExpression)); return patternExpression is ConstantExpression patternConstantExpression diff --git a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerFullTextSearchMethodCallTranslator.cs b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerFullTextSearchMethodCallTranslator.cs index 880c106ea16..cafa5fe6354 100644 --- a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerFullTextSearchMethodCallTranslator.cs +++ b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerFullTextSearchMethodCallTranslator.cs @@ -56,11 +56,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) return new SqlFunctionExpression( FreeTextFunctionName, typeof(bool), - new[] - { - methodCallExpression.Arguments[1], - methodCallExpression.Arguments[2] - }); + new[] { methodCallExpression.Arguments[1], methodCallExpression.Arguments[2] }); } if (Equals(methodCallExpression.Method, _freeTextMethodInfoWithLanguage)) @@ -72,9 +68,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) typeof(bool), new[] { - methodCallExpression.Arguments[1], - methodCallExpression.Arguments[2], - new SqlFragmentExpression( + methodCallExpression.Arguments[1], methodCallExpression.Arguments[2], new SqlFragmentExpression( $"LANGUAGE {((ConstantExpression)methodCallExpression.Arguments[3]).Value}") }); } @@ -86,11 +80,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) return new SqlFunctionExpression( ContainsFunctionName, typeof(bool), - new[] - { - methodCallExpression.Arguments[1], - methodCallExpression.Arguments[2] - }); + new[] { methodCallExpression.Arguments[1], methodCallExpression.Arguments[2] }); } if (Equals(methodCallExpression.Method, _containsMethodInfoWithLanguage)) @@ -102,9 +92,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) typeof(bool), new[] { - methodCallExpression.Arguments[1], - methodCallExpression.Arguments[2], - new SqlFragmentExpression( + methodCallExpression.Arguments[1], methodCallExpression.Arguments[2], new SqlFragmentExpression( $"LANGUAGE {((ConstantExpression)methodCallExpression.Arguments[3]).Value}") }); } diff --git a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerMathTranslator.cs b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerMathTranslator.cs index 24912c197e6..c09b5433e20 100644 --- a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerMathTranslator.cs +++ b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerMathTranslator.cs @@ -53,19 +53,9 @@ public class SqlServerMathTranslator : IMethodCallTranslator { typeof(Math).GetRuntimeMethod(nameof(Math.Sign), new[] { typeof(short) }), "SIGN" } }; - private static readonly IEnumerable _truncateMethodInfos = new[] - { - typeof(Math).GetRuntimeMethod(nameof(Math.Truncate), new[] { typeof(decimal) }), - typeof(Math).GetRuntimeMethod(nameof(Math.Truncate), new[] { typeof(double) }) - }; + private static readonly IEnumerable _truncateMethodInfos = new[] { typeof(Math).GetRuntimeMethod(nameof(Math.Truncate), new[] { typeof(decimal) }), typeof(Math).GetRuntimeMethod(nameof(Math.Truncate), new[] { typeof(double) }) }; - private static readonly IEnumerable _roundMethodInfos = new[] - { - typeof(Math).GetRuntimeMethod(nameof(Math.Round), new[] { typeof(decimal) }), - typeof(Math).GetRuntimeMethod(nameof(Math.Round), new[] { typeof(double) }), - typeof(Math).GetRuntimeMethod(nameof(Math.Round), new[] { typeof(decimal), typeof(int) }), - typeof(Math).GetRuntimeMethod(nameof(Math.Round), new[] { typeof(double), typeof(int) }) - }; + private static readonly IEnumerable _roundMethodInfos = new[] { typeof(Math).GetRuntimeMethod(nameof(Math.Round), new[] { typeof(decimal) }), typeof(Math).GetRuntimeMethod(nameof(Math.Round), new[] { typeof(double) }), typeof(Math).GetRuntimeMethod(nameof(Math.Round), new[] { typeof(decimal), typeof(int) }), typeof(Math).GetRuntimeMethod(nameof(Math.Round), new[] { typeof(double), typeof(int) }) }; /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerObjectToStringTranslator.cs b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerObjectToStringTranslator.cs index 3b1621d5d91..c7e1912f0ce 100644 --- a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerObjectToStringTranslator.cs +++ b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerObjectToStringTranslator.cs @@ -47,20 +47,16 @@ public class SqlServerObjectToStringTranslator : IMethodCallTranslator public virtual Expression Translate(MethodCallExpression methodCallExpression) { return methodCallExpression.Method.Name == nameof(ToString) - && methodCallExpression.Arguments.Count == 0 - && methodCallExpression.Object != null - && _typeMapping.TryGetValue( - methodCallExpression.Object.Type - .UnwrapNullableType(), - out var storeType) + && methodCallExpression.Arguments.Count == 0 + && methodCallExpression.Object != null + && _typeMapping.TryGetValue( + methodCallExpression.Object.Type + .UnwrapNullableType(), + out var storeType) ? new SqlFunctionExpression( functionName: "CONVERT", returnType: methodCallExpression.Type, - arguments: new[] - { - new SqlFragmentExpression(storeType), - methodCallExpression.Object - }) + arguments: new[] { new SqlFragmentExpression(storeType), methodCallExpression.Object }) : null; } } diff --git a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerStartsWithOptimizedTranslator.cs b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerStartsWithOptimizedTranslator.cs index 8c4960c24fc..4aed149ac65 100644 --- a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerStartsWithOptimizedTranslator.cs +++ b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerStartsWithOptimizedTranslator.cs @@ -44,11 +44,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) "LEFT", // ReSharper disable once PossibleNullReferenceException methodCallExpression.Object.Type, - new[] - { - methodCallExpression.Object, - new SqlFunctionExpression("LEN", typeof(int), new[] { patternExpression }) - }), + new[] { methodCallExpression.Object, new SqlFunctionExpression("LEN", typeof(int), new[] { patternExpression }) }), patternExpression))); return patternExpression is ConstantExpression patternConstantExpression diff --git a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerStringConcatMethodCallTranslator.cs b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerStringConcatMethodCallTranslator.cs index 242e747f49f..7e5784652f5 100644 --- a/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerStringConcatMethodCallTranslator.cs +++ b/src/EFCore.SqlServer/Query/ExpressionTranslators/Internal/SqlServerStringConcatMethodCallTranslator.cs @@ -24,7 +24,7 @@ public class SqlServerStringConcatMethodCallTranslator : IMethodCallTranslator /// public virtual Expression Translate(MethodCallExpression methodCallExpression) => _stringConcatMethodInfo.Equals(methodCallExpression.Method) - ? Expression.Add(methodCallExpression.Arguments[0], methodCallExpression.Arguments[1], _stringConcatMethodInfo) - : null; + ? Expression.Add(methodCallExpression.Arguments[0], methodCallExpression.Arguments[1], _stringConcatMethodInfo) + : null; } } diff --git a/src/EFCore.SqlServer/Query/Sql/Internal/SqlServerQuerySqlGenerator.cs b/src/EFCore.SqlServer/Query/Sql/Internal/SqlServerQuerySqlGenerator.cs index 5fad0fde97f..cd170b08e6b 100644 --- a/src/EFCore.SqlServer/Query/Sql/Internal/SqlServerQuerySqlGenerator.cs +++ b/src/EFCore.SqlServer/Query/Sql/Internal/SqlServerQuerySqlGenerator.cs @@ -159,8 +159,8 @@ public override Expression Visit(Expression expression) return expression is ExistsExpression existsExpression ? VisitExistExpression(existsExpression) : expression is SelectExpression selectExpression - ? VisitSelectExpression(selectExpression) - : base.Visit(expression); + ? VisitSelectExpression(selectExpression) + : base.Visit(expression); } private static bool RequiresRowNumberPaging(SelectExpression selectExpression) diff --git a/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerCodeGenerator.cs b/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerCodeGenerator.cs index 89d7f1995f6..36942144cb5 100644 --- a/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerCodeGenerator.cs +++ b/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerCodeGenerator.cs @@ -32,7 +32,7 @@ public SqlServerCodeGenerator([NotNull] ProviderCodeGeneratorDependencies depend => new MethodCallCodeFragment( nameof(SqlServerDbContextOptionsExtensions.UseSqlServer), providerOptions == null - ? new object[] { connectionString } - : new object[] { connectionString, new NestedClosureCodeFragment("x", providerOptions) }); + ? new object[] { connectionString } + : new object[] { connectionString, new NestedClosureCodeFragment("x", providerOptions) }); } } diff --git a/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs b/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs index 1d4e5d87458..472b998de6c 100644 --- a/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs +++ b/src/EFCore.SqlServer/Scaffolding/Internal/SqlServerDatabaseModelFactory.cs @@ -230,7 +230,7 @@ private static (string Schema, string Table) Parse(string table) Func schemaFilter) { return schemaFilter != null - || tables.Count > 0 + || tables.Count > 0 ? ((s, t) => { var tableFilterBuilder = new StringBuilder(); diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerDecimalTypeMapping.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerDecimalTypeMapping.cs index 66ddfcb89ec..c2150beb1af 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerDecimalTypeMapping.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerDecimalTypeMapping.cs @@ -26,11 +26,11 @@ public class SqlServerDecimalTypeMapping : DecimalTypeMapping StoreTypePostfix storeTypePostfix = StoreTypePostfix.None) : base( new RelationalTypeMappingParameters( - new CoreTypeMappingParameters(typeof(decimal)), - storeType, - storeTypePostfix, - dbType) - .WithPrecisionAndScale(precision, scale)) + new CoreTypeMappingParameters(typeof(decimal)), + storeType, + storeTypePostfix, + dbType) + .WithPrecisionAndScale(precision, scale)) { } diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerDoubleTypeMapping.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerDoubleTypeMapping.cs index 072e3c2b44f..68ccec4c440 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerDoubleTypeMapping.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerDoubleTypeMapping.cs @@ -52,9 +52,9 @@ protected override string GenerateNonNullSqlLiteral(object value) var doubleValue = (double)value; return !literal.Contains("E") - && !literal.Contains("e") - && !double.IsNaN(doubleValue) - && !double.IsInfinity(doubleValue) + && !literal.Contains("e") + && !double.IsNaN(doubleValue) + && !double.IsInfinity(doubleValue) ? literal + "E0" : literal; } diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerTypeMappingSource.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerTypeMappingSource.cs index eb347856d33..6cb09fe9cea 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerTypeMappingSource.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerTypeMappingSource.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Data; using System.Linq; -using System.Linq.Expressions; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata; @@ -136,18 +135,9 @@ public class SqlServerTypeMappingSource : RelationalTypeMappingSource private readonly IReadOnlyDictionary> _namedClrMappings = new Dictionary>(StringComparer.Ordinal) { - { - "Microsoft.SqlServer.Types.SqlHierarchyId", - t => SqlServerUdtTypeMapping.CreateSqlHierarchyIdMapping(t) - }, - { - "Microsoft.SqlServer.Types.SqlGeography", - t => SqlServerUdtTypeMapping.CreateSqlSpatialMapping(t, "geography") - }, - { - "Microsoft.SqlServer.Types.SqlGeometry", - t => SqlServerUdtTypeMapping.CreateSqlSpatialMapping(t, "geometry") - } + { "Microsoft.SqlServer.Types.SqlHierarchyId", t => SqlServerUdtTypeMapping.CreateSqlHierarchyIdMapping(t) }, + { "Microsoft.SqlServer.Types.SqlGeography", t => SqlServerUdtTypeMapping.CreateSqlSpatialMapping(t, "geography") }, + { "Microsoft.SqlServer.Types.SqlGeometry", t => SqlServerUdtTypeMapping.CreateSqlSpatialMapping(t, "geometry") } }; /// @@ -250,7 +240,7 @@ protected override void ValidateMapping(CoreTypeMapping mapping, IProperty prope /// protected override RelationalTypeMapping FindMapping(in RelationalTypeMappingInfo mappingInfo) => FindRawMapping(mappingInfo)?.Clone(mappingInfo) - ?? base.FindMapping(mappingInfo); + ?? base.FindMapping(mappingInfo); private RelationalTypeMapping FindRawMapping(RelationalTypeMappingInfo mappingInfo) { diff --git a/src/EFCore.SqlServer/Storage/Internal/SqlServerUdtTypeMapping.cs b/src/EFCore.SqlServer/Storage/Internal/SqlServerUdtTypeMapping.cs index 85f0016cedd..ff5409307e9 100644 --- a/src/EFCore.SqlServer/Storage/Internal/SqlServerUdtTypeMapping.cs +++ b/src/EFCore.SqlServer/Storage/Internal/SqlServerUdtTypeMapping.cs @@ -5,9 +5,7 @@ using System.Data; using System.Data.Common; using System.Data.SqlTypes; -using System.Linq; using System.Linq.Expressions; -using System.Reflection; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Internal; diff --git a/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs b/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs index 6d91f3d587a..2fb4c3dafed 100644 --- a/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs +++ b/src/EFCore.SqlServer/Update/Internal/SqlServerUpdateSqlGenerator.cs @@ -354,9 +354,9 @@ private string GetTypeNameForCopy(IProperty property) } return property.ClrType == typeof(byte[]) - && typeName != null - && (typeName.Equals("rowversion", StringComparison.OrdinalIgnoreCase) - || typeName.Equals("timestamp", StringComparison.OrdinalIgnoreCase)) + && typeName != null + && (typeName.Equals("rowversion", StringComparison.OrdinalIgnoreCase) + || typeName.Equals("timestamp", StringComparison.OrdinalIgnoreCase)) ? property.IsNullable ? "varbinary(8)" : "binary(8)" : typeName; } diff --git a/src/EFCore.SqlServer/ValueGeneration/Internal/SqlServerValueGeneratorCache.cs b/src/EFCore.SqlServer/ValueGeneration/Internal/SqlServerValueGeneratorCache.cs index 2375fdf1421..23a358d7b07 100644 --- a/src/EFCore.SqlServer/ValueGeneration/Internal/SqlServerValueGeneratorCache.cs +++ b/src/EFCore.SqlServer/ValueGeneration/Internal/SqlServerValueGeneratorCache.cs @@ -6,7 +6,6 @@ using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage; -using Microsoft.EntityFrameworkCore.Utilities; using Microsoft.EntityFrameworkCore.ValueGeneration; namespace Microsoft.EntityFrameworkCore.SqlServer.ValueGeneration.Internal diff --git a/src/EFCore.Sqlite.Core/Infrastructure/SpatialiteLoader.cs b/src/EFCore.Sqlite.Core/Infrastructure/SpatialiteLoader.cs index 1d096afe4d2..b0b6c6bb4db 100644 --- a/src/EFCore.Sqlite.Core/Infrastructure/SpatialiteLoader.cs +++ b/src/EFCore.Sqlite.Core/Infrastructure/SpatialiteLoader.cs @@ -147,6 +147,7 @@ private static void FindExtension() assetFullPath = candidateFullPath; } } + Debug.Assert(assetFullPath != null); var assetDirectory = Path.GetDirectoryName(assetFullPath); diff --git a/src/EFCore.Sqlite.Core/Metadata/Internal/SqlitePropertyBuilderAnnotations.cs b/src/EFCore.Sqlite.Core/Metadata/Internal/SqlitePropertyBuilderAnnotations.cs index bf87ad19c03..7d3ea65f983 100644 --- a/src/EFCore.Sqlite.Core/Metadata/Internal/SqlitePropertyBuilderAnnotations.cs +++ b/src/EFCore.Sqlite.Core/Metadata/Internal/SqlitePropertyBuilderAnnotations.cs @@ -86,7 +86,7 @@ public virtual bool HasDefaultValue([CanBeNull] object value) /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - public new virtual bool IsFixedLength(bool fixedLength) + public virtual bool IsFixedLength(bool fixedLength) => SetFixedLength(fixedLength); /// diff --git a/src/EFCore.Sqlite.Core/Migrations/SqliteMigrationsSqlGenerator.cs b/src/EFCore.Sqlite.Core/Migrations/SqliteMigrationsSqlGenerator.cs index d252fd12473..ccc69e0abc3 100644 --- a/src/EFCore.Sqlite.Core/Migrations/SqliteMigrationsSqlGenerator.cs +++ b/src/EFCore.Sqlite.Core/Migrations/SqliteMigrationsSqlGenerator.cs @@ -50,16 +50,16 @@ public override IReadOnlyList Generate(IReadOnlyList SqliteTypeMappingSource.IsSpatialiteType( operation.ColumnType - ?? GetColumnType( - operation.Schema, - operation.Table, - operation.Name, - operation.ClrType, - operation.IsUnicode, - operation.MaxLength, - operation.IsFixedLength, - operation.IsRowVersion, - model)); + ?? GetColumnType( + operation.Schema, + operation.Table, + operation.Name, + operation.ClrType, + operation.IsUnicode, + operation.MaxLength, + operation.IsFixedLength, + operation.IsRowVersion, + model)); private IReadOnlyList RewriteOperations( IReadOnlyList migrationOperations, @@ -154,16 +154,16 @@ protected override void Generate(AddColumnOperation operation, IModel model, Mig var dimension = operation[SqliteAnnotationNames.Dimension] as string; var geometryType = operation.ColumnType - ?? GetColumnType( - operation.Schema, - operation.Table, - operation.Name, - operation.ClrType, - operation.IsUnicode, - operation.MaxLength, - operation.IsFixedLength, - operation.IsRowVersion, - model); + ?? GetColumnType( + operation.Schema, + operation.Table, + operation.Name, + operation.ClrType, + operation.IsUnicode, + operation.MaxLength, + operation.IsFixedLength, + operation.IsRowVersion, + model); if (!string.IsNullOrEmpty(dimension)) { geometryType += dimension; diff --git a/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteEndsWithOptimizedTranslator.cs b/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteEndsWithOptimizedTranslator.cs index 97bd7f1e270..f877afd1483 100644 --- a/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteEndsWithOptimizedTranslator.cs +++ b/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteEndsWithOptimizedTranslator.cs @@ -33,11 +33,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) "substr", // ReSharper disable once PossibleNullReferenceException methodCallExpression.Object.Type, - new[] - { - methodCallExpression.Object, - Expression.Negate(new SqlFunctionExpression("length", typeof(int), new[] { patternExpression })) - }), + new[] { methodCallExpression.Object, Expression.Negate(new SqlFunctionExpression("length", typeof(int), new[] { patternExpression })) }), patternExpression)); return patternExpression is ConstantExpression patternConstantExpression diff --git a/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteExpression.cs b/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteExpression.cs index 3596f755edd..a3c955ac2c1 100644 --- a/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteExpression.cs +++ b/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteExpression.cs @@ -34,14 +34,13 @@ public static class SqliteExpression timestring = strftimeFunction.Arguments[1]; // Prepend its modifier arguments (if any) to the current call - modifiers = Enumerable.Concat(strftimeFunction.Arguments.Skip(2), modifiers); + modifiers = strftimeFunction.Arguments.Skip(2).Concat(modifiers); } return new SqlFunctionExpression( "strftime", returnType, - Enumerable.Concat( - new[] { Expression.Constant(format), timestring }, + new[] { Expression.Constant(format), timestring }.Concat( modifiers)); } } diff --git a/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteLengthTranslator.cs b/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteLengthTranslator.cs index 21faf4ef4ad..b881c8b6bf7 100644 --- a/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteLengthTranslator.cs +++ b/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteLengthTranslator.cs @@ -20,7 +20,7 @@ public class SqliteLengthTranslator : IMemberTranslator public virtual Expression Translate(MemberExpression memberExpression) => memberExpression.Expression != null && (memberExpression.Expression.Type == typeof(string) - || memberExpression.Expression.Type == typeof(byte[])) + || memberExpression.Expression.Type == typeof(byte[])) && memberExpression.Member.Name == nameof(string.Length) ? new SqlFunctionExpression("length", memberExpression.Type, new[] { memberExpression.Expression }) : null; diff --git a/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteStartsWithOptimizedTranslator.cs b/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteStartsWithOptimizedTranslator.cs index 85431f8dc80..1d342458e25 100644 --- a/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteStartsWithOptimizedTranslator.cs +++ b/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteStartsWithOptimizedTranslator.cs @@ -43,12 +43,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) "substr", // ReSharper disable once PossibleNullReferenceException methodCallExpression.Object.Type, - new[] - { - methodCallExpression.Object, - Expression.Constant(1), - new SqlFunctionExpression("length", typeof(int), new[] { patternExpression }) - }), + new[] { methodCallExpression.Object, Expression.Constant(1), new SqlFunctionExpression("length", typeof(int), new[] { patternExpression }) }), patternExpression))); return patternExpression is ConstantExpression patternConstantExpression diff --git a/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteStringSubstringTranslator.cs b/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteStringSubstringTranslator.cs index 0e1fe84bf1d..6b231922e6c 100644 --- a/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteStringSubstringTranslator.cs +++ b/src/EFCore.Sqlite.Core/Query/ExpressionTranslators/Internal/SqliteStringSubstringTranslator.cs @@ -28,9 +28,8 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) methodCallExpression.Type, new[] { - methodCallExpression.Object, - methodCallExpression.Arguments[0] is ConstantExpression constantExpression - && constantExpression.Value is int value + methodCallExpression.Object, methodCallExpression.Arguments[0] is ConstantExpression constantExpression + && constantExpression.Value is int value ? (Expression)Expression.Constant(value + 1) : Expression.Add( methodCallExpression.Arguments[0], diff --git a/src/EFCore.Sqlite.Core/Query/ExpressionVisitors/Internal/SqliteSqlTranslatingExpressionVisitor.cs b/src/EFCore.Sqlite.Core/Query/ExpressionVisitors/Internal/SqliteSqlTranslatingExpressionVisitor.cs index 219f420c7ba..7c591e4031f 100644 --- a/src/EFCore.Sqlite.Core/Query/ExpressionVisitors/Internal/SqliteSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.Sqlite.Core/Query/ExpressionVisitors/Internal/SqliteSqlTranslatingExpressionVisitor.cs @@ -138,9 +138,9 @@ protected override Expression VisitBinary(BinaryExpression binaryExpression) } return _restrictedBinaryExpressions.TryGetValue(visitedExpression.NodeType, out var restrictedTypes) - && visitedExpression is BinaryExpression visitedBinaryExpression - && (restrictedTypes.Contains(GetProviderType(visitedBinaryExpression.Left)) - || restrictedTypes.Contains(GetProviderType(visitedBinaryExpression.Right))) + && visitedExpression is BinaryExpression visitedBinaryExpression + && (restrictedTypes.Contains(GetProviderType(visitedBinaryExpression.Left)) + || restrictedTypes.Contains(GetProviderType(visitedBinaryExpression.Right))) ? null : visitedExpression; } diff --git a/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteCodeGenerator.cs b/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteCodeGenerator.cs index f8819a86982..a6676bdb9e1 100644 --- a/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteCodeGenerator.cs +++ b/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteCodeGenerator.cs @@ -32,7 +32,7 @@ public SqliteCodeGenerator([NotNull] ProviderCodeGeneratorDependencies dependenc => new MethodCallCodeFragment( nameof(SqliteDbContextOptionsBuilderExtensions.UseSqlite), providerOptions == null - ? new object[] { connectionString } - : new object[] { connectionString, new NestedClosureCodeFragment("x", providerOptions) }); + ? new object[] { connectionString } + : new object[] { connectionString, new NestedClosureCodeFragment("x", providerOptions) }); } } diff --git a/src/EFCore.Sqlite.Core/Storage/Internal/SqliteTypeMappingSource.cs b/src/EFCore.Sqlite.Core/Storage/Internal/SqliteTypeMappingSource.cs index c4fb05b3371..88e31dca3ed 100644 --- a/src/EFCore.Sqlite.Core/Storage/Internal/SqliteTypeMappingSource.cs +++ b/src/EFCore.Sqlite.Core/Storage/Internal/SqliteTypeMappingSource.cs @@ -68,7 +68,7 @@ public class SqliteTypeMappingSource : RelationalTypeMappingSource { IntegerTypeName, _integer }, { RealTypeName, _real }, { BlobTypeName, _blob }, - { TextTypeName, _text }, + { TextTypeName, _text } }; /// @@ -122,16 +122,14 @@ protected override RelationalTypeMapping FindMapping(in RelationalTypeMappingInf private readonly Func[] _typeRules = { - name => Contains(name, "INT") ? _integer : null, - name => Contains(name, "CHAR") - || Contains(name, "CLOB") - || Contains(name, "TEXT") + name => Contains(name, "INT") ? _integer : null, name => Contains(name, "CHAR") + || Contains(name, "CLOB") + || Contains(name, "TEXT") ? _text : null, - name => Contains(name, "BLOB") ? _blob : null, - name => Contains(name, "REAL") - || Contains(name, "FLOA") - || Contains(name, "DOUB") + name => Contains(name, "BLOB") ? _blob : null, name => Contains(name, "REAL") + || Contains(name, "FLOA") + || Contains(name, "DOUB") ? _real : null }; diff --git a/src/EFCore.Sqlite.NTS/Extensions/SqliteNetTopologySuiteDbContextOptionsBuilderExtensions.cs b/src/EFCore.Sqlite.NTS/Extensions/SqliteNetTopologySuiteDbContextOptionsBuilderExtensions.cs index 60660c41619..e9542fb49fa 100644 --- a/src/EFCore.Sqlite.NTS/Extensions/SqliteNetTopologySuiteDbContextOptionsBuilderExtensions.cs +++ b/src/EFCore.Sqlite.NTS/Extensions/SqliteNetTopologySuiteDbContextOptionsBuilderExtensions.cs @@ -9,7 +9,7 @@ namespace Microsoft.EntityFrameworkCore { /// - /// NetTopologySuite specific extension methods for . + /// NetTopologySuite specific extension methods for . /// public static class SqliteNetTopologySuiteDbContextOptionsBuilderExtensions { @@ -26,9 +26,9 @@ public static class SqliteNetTopologySuiteDbContextOptionsBuilderExtensions var coreOptionsBuilder = ((IRelationalDbContextOptionsBuilderInfrastructure)optionsBuilder).OptionsBuilder; var infrastructure = (IDbContextOptionsBuilderInfrastructure)coreOptionsBuilder; var sqliteExtension = coreOptionsBuilder.Options.FindExtension() - ?? new SqliteOptionsExtension(); + ?? new SqliteOptionsExtension(); var ntsExtension = coreOptionsBuilder.Options.FindExtension() - ?? new SqliteNetTopologySuiteOptionsExtension(); + ?? new SqliteNetTopologySuiteOptionsExtension(); infrastructure.AddOrUpdateExtension(sqliteExtension.WithLoadSpatialite(true)); infrastructure.AddOrUpdateExtension(ntsExtension); diff --git a/src/EFCore.Sqlite.NTS/Extensions/SqliteNetTopologySuitePropertyBuilderExtensions.cs b/src/EFCore.Sqlite.NTS/Extensions/SqliteNetTopologySuitePropertyBuilderExtensions.cs index 0e64f75cc88..270d57af575 100644 --- a/src/EFCore.Sqlite.NTS/Extensions/SqliteNetTopologySuitePropertyBuilderExtensions.cs +++ b/src/EFCore.Sqlite.NTS/Extensions/SqliteNetTopologySuitePropertyBuilderExtensions.cs @@ -30,6 +30,7 @@ public static class SqliteNetTopologySuitePropertyBuilderExtensions { dimension += "Z"; } + if (ordinates.HasFlag(Ordinates.M)) { dimension += "M"; diff --git a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryCollectionMethodTranslator.cs b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryCollectionMethodTranslator.cs index 0f7c4bec95a..281b4bfefe0 100644 --- a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryCollectionMethodTranslator.cs +++ b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryCollectionMethodTranslator.cs @@ -29,11 +29,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) return new SqlFunctionExpression( "GeometryN", methodCallExpression.Type, - new[] - { - methodCallExpression.Object, - Expression.Add(methodCallExpression.Arguments[0], Expression.Constant(1)) - }); + new[] { methodCallExpression.Object, Expression.Add(methodCallExpression.Arguments[0], Expression.Constant(1)) }); } return null; diff --git a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryMemberTranslator.cs b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryMemberTranslator.cs index 06e63937764..440c5e5e88b 100644 --- a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryMemberTranslator.cs +++ b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryMemberTranslator.cs @@ -60,6 +60,7 @@ public virtual Expression Translate(MemberExpression memberExpression) return newExpression; } + if (Equals(member, _geometryType)) { return new CaseExpression( @@ -82,6 +83,7 @@ public virtual Expression Translate(MemberExpression memberExpression) new CaseWhenClause(Expression.Constant("MULTIPOLYGON"), Expression.Constant("MultiPolygon")), new CaseWhenClause(Expression.Constant("GEOMETRYCOLLECTION"), Expression.Constant("GeometryCollection"))); } + if (Equals(member, _ogcGeometryType)) { return new CaseExpression( diff --git a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryMethodTranslator.cs b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryMethodTranslator.cs index 48ae05bbf64..b0731f523a4 100644 --- a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryMethodTranslator.cs +++ b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteGeometryMethodTranslator.cs @@ -74,17 +74,15 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) return newExpression; } + if (Equals(method, _getGeometryN)) { return new SqlFunctionExpression( "GeometryN", methodCallExpression.Type, - new[] - { - methodCallExpression.Object, - Expression.Add(methodCallExpression.Arguments[0], Expression.Constant(1)) - }); + new[] { methodCallExpression.Object, Expression.Add(methodCallExpression.Arguments[0], Expression.Constant(1)) }); } + if (Equals(method, _isWithinDistance)) { return Expression.LessThanOrEqual( diff --git a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteLineStringMethodTranslator.cs b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteLineStringMethodTranslator.cs index 0351c0e3d56..c1fb615b2b7 100644 --- a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteLineStringMethodTranslator.cs +++ b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteLineStringMethodTranslator.cs @@ -29,10 +29,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) return new SqlFunctionExpression( "PointN", methodCallExpression.Type, - new[] { - methodCallExpression.Object, - Expression.Add(methodCallExpression.Arguments[0], Expression.Constant(1)) - }); + new[] { methodCallExpression.Object, Expression.Add(methodCallExpression.Arguments[0], Expression.Constant(1)) }); } return null; diff --git a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteNetTopologySuiteMemberTranslatorPlugin.cs b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteNetTopologySuiteMemberTranslatorPlugin.cs index 70153d49f0c..5d6552a0c73 100644 --- a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteNetTopologySuiteMemberTranslatorPlugin.cs +++ b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteNetTopologySuiteMemberTranslatorPlugin.cs @@ -17,15 +17,6 @@ public class SqliteNetTopologySuiteMemberTranslatorPlugin : IMemberTranslatorPlu /// directly from your code. This API may change or be removed in future releases. /// public virtual IEnumerable Translators { get; } - = new IMemberTranslator[] - { - new SqliteCurveMemberTranslator(), - new SqliteGeometryMemberTranslator(), - new SqliteGeometryCollectionMemberTranslator(), - new SqliteLineStringMemberTranslator(), - new SqliteMultiCurveMemberTranslator(), - new SqlitePointMemberTranslator(), - new SqlitePolygonMemberTranslator() - }; + = new IMemberTranslator[] { new SqliteCurveMemberTranslator(), new SqliteGeometryMemberTranslator(), new SqliteGeometryCollectionMemberTranslator(), new SqliteLineStringMemberTranslator(), new SqliteMultiCurveMemberTranslator(), new SqlitePointMemberTranslator(), new SqlitePolygonMemberTranslator() }; } } diff --git a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteNetTopologySuiteMethodCallTranslatorPlugin.cs b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteNetTopologySuiteMethodCallTranslatorPlugin.cs index 4bd2f48ab9f..b673ce6a76e 100644 --- a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteNetTopologySuiteMethodCallTranslatorPlugin.cs +++ b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqliteNetTopologySuiteMethodCallTranslatorPlugin.cs @@ -16,12 +16,6 @@ public class SqliteNetTopologySuiteMethodCallTranslatorPlugin : IMethodCallTrans /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - public virtual IEnumerable Translators { get; } = new IMethodCallTranslator[] - { - new SqliteGeometryMethodTranslator(), - new SqliteGeometryCollectionMethodTranslator(), - new SqliteLineStringMethodTranslator(), - new SqlitePolygonMethodTranslator() - }; + public virtual IEnumerable Translators { get; } = new IMethodCallTranslator[] { new SqliteGeometryMethodTranslator(), new SqliteGeometryCollectionMethodTranslator(), new SqliteLineStringMethodTranslator(), new SqlitePolygonMethodTranslator() }; } } diff --git a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqlitePolygonMethodTranslator.cs b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqlitePolygonMethodTranslator.cs index 1bf63ba6b7f..7974c0f494a 100644 --- a/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqlitePolygonMethodTranslator.cs +++ b/src/EFCore.Sqlite.NTS/Query/ExpressionTranslators/Internal/SqlitePolygonMethodTranslator.cs @@ -29,11 +29,7 @@ public virtual Expression Translate(MethodCallExpression methodCallExpression) return new SqlFunctionExpression( "InteriorRingN", methodCallExpression.Type, - new[] - { - methodCallExpression.Object, - Expression.Add(methodCallExpression.Arguments[0], Expression.Constant(1)) - }); + new[] { methodCallExpression.Object, Expression.Add(methodCallExpression.Arguments[0], Expression.Constant(1)) }); } return null; diff --git a/src/EFCore.Sqlite.NTS/Storage/Internal/SqliteGeometryTypeMapping.cs b/src/EFCore.Sqlite.NTS/Storage/Internal/SqliteGeometryTypeMapping.cs index 319f42ca3d1..eeabf6a6b3a 100644 --- a/src/EFCore.Sqlite.NTS/Storage/Internal/SqliteGeometryTypeMapping.cs +++ b/src/EFCore.Sqlite.NTS/Storage/Internal/SqliteGeometryTypeMapping.cs @@ -43,7 +43,7 @@ public SqliteGeometryTypeMapping(IGeometryServices geometryServices, string stor /// protected SqliteGeometryTypeMapping( RelationalTypeMappingParameters parameters, - ValueConverter converter) + ValueConverter converter) : base(parameters, converter) { } diff --git a/src/EFCore/ChangeTracking/GeometryValueComparer.cs b/src/EFCore/ChangeTracking/GeometryValueComparer.cs index 2b00ee17a35..92739b03e46 100644 --- a/src/EFCore/ChangeTracking/GeometryValueComparer.cs +++ b/src/EFCore/ChangeTracking/GeometryValueComparer.cs @@ -13,13 +13,13 @@ namespace Microsoft.EntityFrameworkCore.ChangeTracking public class GeometryValueComparer : ValueComparer { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// public GeometryValueComparer() : base( - GetEqualsExpression(), - CreateDefaultHashCodeExpression(favorStructuralComparisons: false), - GetSnapshotExpression()) + GetEqualsExpression(), + CreateDefaultHashCodeExpression(favorStructuralComparisons: false), + GetSnapshotExpression()) { } diff --git a/src/EFCore/ChangeTracking/Internal/EntityGraphAttacher.cs b/src/EFCore/ChangeTracking/Internal/EntityGraphAttacher.cs index 0409f510439..d9a925b35b4 100644 --- a/src/EFCore/ChangeTracking/Internal/EntityGraphAttacher.cs +++ b/src/EFCore/ChangeTracking/Internal/EntityGraphAttacher.cs @@ -17,8 +17,7 @@ public class EntityGraphAttacher : IEntityGraphAttacher private readonly IEntityEntryGraphIterator _graphIterator; // Stored for perf - private static readonly object[] _boxedEntityStates = - { EntityState.Detached, EntityState.Unchanged, EntityState.Deleted, EntityState.Modified, EntityState.Added }; + private static readonly object[] _boxedEntityStates = { EntityState.Detached, EntityState.Unchanged, EntityState.Deleted, EntityState.Modified, EntityState.Added }; /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore/ChangeTracking/Internal/InternalEntityEntryFactory.cs b/src/EFCore/ChangeTracking/Internal/InternalEntityEntryFactory.cs index 9c4a7109b92..a4040c01769 100644 --- a/src/EFCore/ChangeTracking/Internal/InternalEntityEntryFactory.cs +++ b/src/EFCore/ChangeTracking/Internal/InternalEntityEntryFactory.cs @@ -51,8 +51,8 @@ private static InternalEntityEntry NewInternalEntityEntry(IStateManager stateMan return !entityType.HasClrType() ? new InternalShadowEntityEntry(stateManager, entityType, valueBuffer) : entityType.ShadowPropertyCount() > 0 - ? (InternalEntityEntry)new InternalMixedEntityEntry(stateManager, entityType, entity, valueBuffer) - : new InternalClrEntityEntry(stateManager, entityType, entity); + ? (InternalEntityEntry)new InternalMixedEntityEntry(stateManager, entityType, entity, valueBuffer) + : new InternalClrEntityEntry(stateManager, entityType, entity); } } } diff --git a/src/EFCore/ChangeTracking/Internal/NavigationFixer.cs b/src/EFCore/ChangeTracking/Internal/NavigationFixer.cs index 11b703f790b..0d1b7bfa1a9 100644 --- a/src/EFCore/ChangeTracking/Internal/NavigationFixer.cs +++ b/src/EFCore/ChangeTracking/Internal/NavigationFixer.cs @@ -830,6 +830,7 @@ private void DelayedFixup(InternalEntityEntry entry, INavigation navigation, Int { dependentEntry.SetProperty(dependentProperty, principalValue, setModified); } + dependentEntry.StateManager.UpdateDependentMap(dependentEntry, foreignKey); dependentEntry.SetRelationshipSnapshotValue(dependentProperty, principalValue); } diff --git a/src/EFCore/ChangeTracking/Internal/SnapshotFactoryFactory.cs b/src/EFCore/ChangeTracking/Internal/SnapshotFactoryFactory.cs index c5d4b1dc12e..167a9778891 100644 --- a/src/EFCore/ChangeTracking/Internal/SnapshotFactoryFactory.cs +++ b/src/EFCore/ChangeTracking/Internal/SnapshotFactoryFactory.cs @@ -29,8 +29,8 @@ public virtual Func CreateEmpty([NotNull] IEntityType entityType) return GetPropertyCount(entityType) == 0 ? (() => Snapshot.Empty) : Expression.Lambda>( - CreateConstructorExpression(entityType, null)) - .Compile(); + CreateConstructorExpression(entityType, null)) + .Compile(); } /// @@ -163,7 +163,6 @@ public virtual Func CreateEmpty([NotNull] IEntityType entityType) _snapshotCollectionMethod, memberAccess) : CreateSnapshotValueExpression(memberAccess, propertyBase); - } var constructorExpression = Expression.Convert( diff --git a/src/EFCore/ChangeTracking/Internal/StateManager.cs b/src/EFCore/ChangeTracking/Internal/StateManager.cs index 8a5ae9254f2..c2672ffd073 100644 --- a/src/EFCore/ChangeTracking/Internal/StateManager.cs +++ b/src/EFCore/ChangeTracking/Internal/StateManager.cs @@ -292,9 +292,9 @@ public virtual void BeginTrackingQuery() var clrType = entity.GetType(); var entityType = baseEntityType.ClrType == clrType - || baseEntityType.HasDefiningNavigation() - ? baseEntityType - : _model.FindRuntimeEntityType(clrType); + || baseEntityType.HasDefiningNavigation() + ? baseEntityType + : _model.FindRuntimeEntityType(clrType); var newEntry = valueBuffer.IsEmpty ? _internalEntityEntryFactory.Create(this, entityType, entity) @@ -444,7 +444,7 @@ private IIdentityMap FindIdentityMap(IKey key) } return _identityMaps == null - || !_identityMaps.TryGetValue(key, out var identityMap) + || !_identityMaps.TryGetValue(key, out var identityMap) ? null : identityMap; } diff --git a/src/EFCore/ChangeTracking/PropertyEntry.cs b/src/EFCore/ChangeTracking/PropertyEntry.cs index d36b63c4dc3..93c6868c5ec 100644 --- a/src/EFCore/ChangeTracking/PropertyEntry.cs +++ b/src/EFCore/ChangeTracking/PropertyEntry.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Metadata; diff --git a/src/EFCore/Diagnostics/CoreEventId.cs b/src/EFCore/Diagnostics/CoreEventId.cs index 97cc5f2a801..1a9e8207b3d 100644 --- a/src/EFCore/Diagnostics/CoreEventId.cs +++ b/src/EFCore/Diagnostics/CoreEventId.cs @@ -791,7 +791,7 @@ private enum Id /// /// - /// An was thrown during the call to + /// An was thrown during the call to /// /// /// diff --git a/src/EFCore/Extensions/Internal/AsyncQueryProviderExtensions.cs b/src/EFCore/Extensions/Internal/AsyncQueryProviderExtensions.cs index bfcc9e9f264..5e16385ff49 100644 --- a/src/EFCore/Extensions/Internal/AsyncQueryProviderExtensions.cs +++ b/src/EFCore/Extensions/Internal/AsyncQueryProviderExtensions.cs @@ -30,8 +30,7 @@ public static class AsyncQueryProviderExtensions _createEntityQueryableMethod .MakeGenericMethod(type) .Invoke( - null, new object[] - { entityQueryProvider })); + null, new object[] { entityQueryProvider })); } private static readonly MethodInfo _createEntityQueryableMethod diff --git a/src/EFCore/Extensions/Internal/CoreLoggerExtensions.cs b/src/EFCore/Extensions/Internal/CoreLoggerExtensions.cs index f30c5640832..7f83c3875be 100644 --- a/src/EFCore/Extensions/Internal/CoreLoggerExtensions.cs +++ b/src/EFCore/Extensions/Internal/CoreLoggerExtensions.cs @@ -1359,11 +1359,7 @@ private static string MultipleInversePropertiesSameTargetWarning(EventDefinition definition, NonDefiningInverseNavigationWarning, new[] { new Tuple(navigation, declaringType.ClrType) }, - new[] - { - new Tuple(inverseNavigation, targetType.ClrType), - new Tuple(definingNavigation, targetType.ClrType) - })); + new[] { new Tuple(inverseNavigation, targetType.ClrType), new Tuple(definingNavigation, targetType.ClrType) })); } } @@ -1417,11 +1413,7 @@ private static string NonDefiningInverseNavigationWarning(EventDefinitionBase de definition, NonOwnershipInverseNavigationWarning, new[] { new Tuple(navigation, declaringType.ClrType) }, - new[] - { - new Tuple(inverseNavigation, targetType.ClrType), - new Tuple(ownershipNavigation, targetType.ClrType) - })); + new[] { new Tuple(inverseNavigation, targetType.ClrType), new Tuple(ownershipNavigation, targetType.ClrType) })); } } @@ -1474,16 +1466,8 @@ private static string NonOwnershipInverseNavigationWarning(EventDefinitionBase d new TwoUnmappedPropertyCollectionsEventData( definition, ForeignKeyAttributesOnBothPropertiesWarning, - new[] - { - new Tuple(firstNavigation.GetIdentifyingMemberInfo(), firstNavigation.DeclaringEntityType.ClrType), - new Tuple(firstProperty, firstNavigation.DeclaringEntityType.ClrType) - }, - new[] - { - new Tuple(secondNavigation.GetIdentifyingMemberInfo(), secondNavigation.DeclaringEntityType.ClrType), - new Tuple(secondProperty, secondNavigation.DeclaringEntityType.ClrType) - })); + new[] { new Tuple(firstNavigation.GetIdentifyingMemberInfo(), firstNavigation.DeclaringEntityType.ClrType), new Tuple(firstProperty, firstNavigation.DeclaringEntityType.ClrType) }, + new[] { new Tuple(secondNavigation.GetIdentifyingMemberInfo(), secondNavigation.DeclaringEntityType.ClrType), new Tuple(secondProperty, secondNavigation.DeclaringEntityType.ClrType) })); } } diff --git a/src/EFCore/Extensions/Internal/ExpressionExtensions.cs b/src/EFCore/Extensions/Internal/ExpressionExtensions.cs index a3eb633dc84..e1315f27920 100644 --- a/src/EFCore/Extensions/Internal/ExpressionExtensions.cs +++ b/src/EFCore/Extensions/Internal/ExpressionExtensions.cs @@ -7,7 +7,6 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; -using System.Runtime.InteropServices; using System.Runtime.Versioning; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Extensions.Internal; @@ -473,5 +472,6 @@ private static ConstantExpression GenerateDefaultValueConstantExpressionInternal = typeof(FieldInfo) .GetTypeInfo() .GetDeclaredMethods(nameof(FieldInfo.SetValue)) - .Single(m => m.GetParameters().Length == 2); } + .Single(m => m.GetParameters().Length == 2); + } } diff --git a/src/EFCore/Infrastructure/Annotatable.cs b/src/EFCore/Infrastructure/Annotatable.cs index bb17f7a910c..9e7fa81b62d 100644 --- a/src/EFCore/Infrastructure/Annotatable.cs +++ b/src/EFCore/Infrastructure/Annotatable.cs @@ -132,8 +132,8 @@ public virtual Annotation FindAnnotation(string name) return !_annotations.HasValue ? null : _annotations.Value.TryGetValue(name, out var annotation) - ? annotation - : null; + ? annotation + : null; } /// diff --git a/src/EFCore/Infrastructure/DatabaseFacade.cs b/src/EFCore/Infrastructure/DatabaseFacade.cs index 26de0a68322..267d4bbffd2 100644 --- a/src/EFCore/Infrastructure/DatabaseFacade.cs +++ b/src/EFCore/Infrastructure/DatabaseFacade.cs @@ -8,7 +8,6 @@ using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Utilities; diff --git a/src/EFCore/Infrastructure/ModelSource.cs b/src/EFCore/Infrastructure/ModelSource.cs index c01ec228e0d..68c9e502738 100644 --- a/src/EFCore/Infrastructure/ModelSource.cs +++ b/src/EFCore/Infrastructure/ModelSource.cs @@ -8,7 +8,6 @@ using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal; -using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Infrastructure diff --git a/src/EFCore/Infrastructure/ModelValidator.cs b/src/EFCore/Infrastructure/ModelValidator.cs index 71bb83f7d25..9b98a3a1fc4 100644 --- a/src/EFCore/Infrastructure/ModelValidator.cs +++ b/src/EFCore/Infrastructure/ModelValidator.cs @@ -303,8 +303,9 @@ protected virtual void ValidateOwnership([NotNull] IModel model) throw new InvalidOperationException(CoreStrings.OwnedDerivedType(entityType.DisplayName())); } - foreach (var referencingFk in entityType.GetReferencingForeignKeys().Where(fk => !fk.IsOwnership - && !Contains(fk.DeclaringEntityType.FindOwnership(), fk))) + foreach (var referencingFk in entityType.GetReferencingForeignKeys().Where( + fk => !fk.IsOwnership + && !Contains(fk.DeclaringEntityType.FindOwnership(), fk))) { throw new InvalidOperationException( CoreStrings.PrincipalOwnedType( @@ -319,8 +320,9 @@ protected virtual void ValidateOwnership([NotNull] IModel model) entityType.DisplayName())); } - foreach (var fk in entityType.GetDeclaredForeignKeys().Where(fk => !fk.IsOwnership && fk.PrincipalToDependent != null - && !Contains(fk.DeclaringEntityType.FindOwnership(), fk))) + foreach (var fk in entityType.GetDeclaredForeignKeys().Where( + fk => !fk.IsOwnership && fk.PrincipalToDependent != null + && !Contains(fk.DeclaringEntityType.FindOwnership(), fk))) { throw new InvalidOperationException( CoreStrings.InverseToOwnedType( @@ -339,8 +341,8 @@ protected virtual void ValidateOwnership([NotNull] IModel model) private bool Contains(IForeignKey inheritedFk, IForeignKey derivedFk) => inheritedFk != null - && inheritedFk.PrincipalEntityType.IsAssignableFrom(derivedFk.PrincipalEntityType) - && PropertyListComparer.Instance.Equals(inheritedFk.Properties, derivedFk.Properties); + && inheritedFk.PrincipalEntityType.IsAssignableFrom(derivedFk.PrincipalEntityType) + && PropertyListComparer.Instance.Equals(inheritedFk.Properties, derivedFk.Properties); /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used @@ -569,7 +571,7 @@ protected virtual void ValidateData([NotNull] IModel model) { if (!property.IsNullable && ((!property.RequiresValueGenerator() - && (property.ValueGenerated & ValueGenerated.OnAdd) == 0) + && (property.ValueGenerated & ValueGenerated.OnAdd) == 0) || property.IsKey())) { throw new InvalidOperationException(CoreStrings.SeedDatumMissingValue(entityType.DisplayName(), property.Name)); @@ -583,6 +585,7 @@ protected virtual void ValidateData([NotNull] IModel model) { throw new InvalidOperationException(CoreStrings.SeedDatumSignedNumericValue(entityType.DisplayName(), property.Name)); } + throw new InvalidOperationException(CoreStrings.SeedDatumDefaultValue(entityType.DisplayName(), property.Name, property.ClrType.GetDefaultValue())); } else if (!property.ClrType.GetTypeInfo().IsAssignableFrom(value.GetType().GetTypeInfo())) diff --git a/src/EFCore/Internal/EntityFinder.cs b/src/EFCore/Internal/EntityFinder.cs index b2c7dcef3b4..2cd13c75ed8 100644 --- a/src/EFCore/Internal/EntityFinder.cs +++ b/src/EFCore/Internal/EntityFinder.cs @@ -55,7 +55,7 @@ public virtual TEntity Find(object[] keyValues) return keyValues?.Any(v => v == null) != false ? null : FindTracked(keyValues, out var keyProperties) - ?? _queryRoot.FirstOrDefault(BuildLambda(keyProperties, new ValueBuffer(keyValues))); + ?? _queryRoot.FirstOrDefault(BuildLambda(keyProperties, new ValueBuffer(keyValues))); } /// diff --git a/src/EFCore/Internal/ServiceProviderCache.cs b/src/EFCore/Internal/ServiceProviderCache.cs index cb8d107744b..7053c012166 100644 --- a/src/EFCore/Internal/ServiceProviderCache.cs +++ b/src/EFCore/Internal/ServiceProviderCache.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Globalization; using System.Linq; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; diff --git a/src/EFCore/Metadata/Builders/CollectionOwnershipBuilder.cs b/src/EFCore/Metadata/Builders/CollectionOwnershipBuilder.cs index 6fd6a25dc0b..475b487c5cc 100644 --- a/src/EFCore/Metadata/Builders/CollectionOwnershipBuilder.cs +++ b/src/EFCore/Metadata/Builders/CollectionOwnershipBuilder.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -163,8 +162,9 @@ public virtual CollectionOwnershipBuilder HasEntityTypeAnnotation([NotNull] stri /// The names of the properties that make up the primary key. /// An object that can be used to configure the primary key. public virtual KeyBuilder HasKey([NotNull] params string[] propertyNames) - => new KeyBuilder(DependentEntityType.Builder.PrimaryKey( - Check.NotEmpty(propertyNames, nameof(propertyNames)), ConfigurationSource.Explicit)); + => new KeyBuilder( + DependentEntityType.Builder.PrimaryKey( + Check.NotEmpty(propertyNames, nameof(propertyNames)), ConfigurationSource.Explicit)); /// /// @@ -252,8 +252,9 @@ public virtual CollectionOwnershipBuilder Ignore([NotNull] string propertyName) /// The names of the properties that make up the index. /// An object that can be used to configure the index. public virtual IndexBuilder HasIndex([NotNull] params string[] propertyNames) - => new IndexBuilder(DependentEntityType.Builder.HasIndex( - Check.NotEmpty(propertyNames, nameof(propertyNames)), ConfigurationSource.Explicit)); + => new IndexBuilder( + DependentEntityType.Builder.HasIndex( + Check.NotEmpty(propertyNames, nameof(propertyNames)), ConfigurationSource.Explicit)); /// /// diff --git a/src/EFCore/Metadata/Builders/CollectionOwnershipBuilder`.cs b/src/EFCore/Metadata/Builders/CollectionOwnershipBuilder`.cs index c614d666ca9..26dc69dc80f 100644 --- a/src/EFCore/Metadata/Builders/CollectionOwnershipBuilder`.cs +++ b/src/EFCore/Metadata/Builders/CollectionOwnershipBuilder`.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; @@ -223,8 +222,9 @@ public class CollectionOwnershipBuilder : CollectionO /// /// An object that can be used to configure the primary key. public virtual KeyBuilder HasKey([NotNull] Expression> keyExpression) - => new KeyBuilder(DependentEntityType.Builder.PrimaryKey( - Check.NotNull(keyExpression, nameof(keyExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); + => new KeyBuilder( + DependentEntityType.Builder.PrimaryKey( + Check.NotNull(keyExpression, nameof(keyExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); /// /// @@ -288,8 +288,9 @@ public virtual PropertyBuilder Property([NotNull] Expressi /// /// An object that can be used to configure the index. public virtual IndexBuilder HasIndex([NotNull] Expression> indexExpression) - => new IndexBuilder(DependentEntityType.Builder.HasIndex( - Check.NotNull(indexExpression, nameof(indexExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); + => new IndexBuilder( + DependentEntityType.Builder.HasIndex( + Check.NotNull(indexExpression, nameof(indexExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); /// /// @@ -338,8 +339,9 @@ public virtual IndexBuilder HasIndex([NotNull] Expression OwnsOne( [NotNull] Expression> navigationExpression) where TRelatedEntity : class - => OwnsOneBuilder(new PropertyIdentity( - Check.NotNull(navigationExpression, nameof(navigationExpression)).GetPropertyAccess())); + => OwnsOneBuilder( + new PropertyIdentity( + Check.NotNull(navigationExpression, nameof(navigationExpression)).GetPropertyAccess())); /// /// diff --git a/src/EFCore/Metadata/Builders/EntityTypeBuilder.cs b/src/EFCore/Metadata/Builders/EntityTypeBuilder.cs index 2279a8f1508..9a0124baff9 100644 --- a/src/EFCore/Metadata/Builders/EntityTypeBuilder.cs +++ b/src/EFCore/Metadata/Builders/EntityTypeBuilder.cs @@ -655,8 +655,8 @@ private CollectionOwnershipBuilder OwnsManyBuilder(in TypeIdentity ownedType, st /// protected virtual EntityType FindRelatedEntityType(string relatedTypeName, string navigationName) => (navigationName == null - ? null - : Builder.ModelBuilder.Metadata.FindEntityType(relatedTypeName, navigationName, Builder.Metadata)) + ? null + : Builder.ModelBuilder.Metadata.FindEntityType(relatedTypeName, navigationName, Builder.Metadata)) ?? Builder.ModelBuilder.Entity(relatedTypeName, ConfigurationSource.Explicit).Metadata; /// @@ -665,8 +665,8 @@ protected virtual EntityType FindRelatedEntityType(string relatedTypeName, strin /// protected virtual EntityType FindRelatedEntityType([NotNull] Type relatedType, [CanBeNull] string navigationName) => (navigationName == null - ? null - : Builder.ModelBuilder.Metadata.FindEntityType(relatedType, navigationName, Builder.Metadata)) + ? null + : Builder.ModelBuilder.Metadata.FindEntityType(relatedType, navigationName, Builder.Metadata)) ?? Builder.ModelBuilder.Entity(relatedType, ConfigurationSource.Explicit).Metadata; /// diff --git a/src/EFCore/Metadata/Builders/EntityTypeBuilder`.cs b/src/EFCore/Metadata/Builders/EntityTypeBuilder`.cs index dce43934b91..39221f1b1b9 100644 --- a/src/EFCore/Metadata/Builders/EntityTypeBuilder`.cs +++ b/src/EFCore/Metadata/Builders/EntityTypeBuilder`.cs @@ -84,8 +84,9 @@ public virtual EntityTypeBuilder HasBaseType() /// /// An object that can be used to configure the primary key. public virtual KeyBuilder HasKey([NotNull] Expression> keyExpression) - => new KeyBuilder(Builder.PrimaryKey( - Check.NotNull(keyExpression, nameof(keyExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); + => new KeyBuilder( + Builder.PrimaryKey( + Check.NotNull(keyExpression, nameof(keyExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); /// /// Creates an alternate key in the model for this entity type if one does not already exist over the specified @@ -166,8 +167,9 @@ public virtual EntityTypeBuilder HasQueryFilter([CanBeNull] Expression< /// /// An object that can be used to configure the index. public virtual IndexBuilder HasIndex([NotNull] Expression> indexExpression) - => new IndexBuilder(Builder.HasIndex( - Check.NotNull(indexExpression, nameof(indexExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); + => new IndexBuilder( + Builder.HasIndex( + Check.NotNull(indexExpression, nameof(indexExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); /// /// diff --git a/src/EFCore/Metadata/Builders/QueryTypeBuilder`.cs b/src/EFCore/Metadata/Builders/QueryTypeBuilder`.cs index e65418fae76..9731f689ca7 100644 --- a/src/EFCore/Metadata/Builders/QueryTypeBuilder`.cs +++ b/src/EFCore/Metadata/Builders/QueryTypeBuilder`.cs @@ -82,9 +82,9 @@ public QueryTypeBuilder([NotNull] InternalEntityTypeBuilder builder) /// An object that can be used to configure the property. public virtual PropertyBuilder Property( [NotNull] Expression> propertyExpression) => new PropertyBuilder( - Builder.Property( - Check.NotNull(propertyExpression, nameof(propertyExpression)).GetPropertyAccess(), - ConfigurationSource.Explicit)); + Builder.Property( + Check.NotNull(propertyExpression, nameof(propertyExpression)).GetPropertyAccess(), + ConfigurationSource.Explicit)); /// /// Excludes the given property from the query type. This method is typically used to remove properties diff --git a/src/EFCore/Metadata/Builders/ReferenceCollectionBuilderBase.cs b/src/EFCore/Metadata/Builders/ReferenceCollectionBuilderBase.cs index a16e8c222f8..453b00f007b 100644 --- a/src/EFCore/Metadata/Builders/ReferenceCollectionBuilderBase.cs +++ b/src/EFCore/Metadata/Builders/ReferenceCollectionBuilderBase.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.ComponentModel; -using System.Linq; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Internal; diff --git a/src/EFCore/Metadata/Builders/ReferenceCollectionBuilder`.cs b/src/EFCore/Metadata/Builders/ReferenceCollectionBuilder`.cs index 74db267d995..849155e0d77 100644 --- a/src/EFCore/Metadata/Builders/ReferenceCollectionBuilder`.cs +++ b/src/EFCore/Metadata/Builders/ReferenceCollectionBuilder`.cs @@ -64,7 +64,7 @@ public class ReferenceCollectionBuilder : Re /// of the entity class. /// /// - /// If is not specified, + /// If is not specified, /// then an attempt will be made to match the data type and order of foreign key properties against /// the primary key of the principal entity type. If they do not match, new shadow state properties /// that form a unique index will be added to the principal entity type to serve as the reference key. diff --git a/src/EFCore/Metadata/Builders/ReferenceOwnershipBuilder.cs b/src/EFCore/Metadata/Builders/ReferenceOwnershipBuilder.cs index 3105cfb2aeb..c7fdc60d1e9 100644 --- a/src/EFCore/Metadata/Builders/ReferenceOwnershipBuilder.cs +++ b/src/EFCore/Metadata/Builders/ReferenceOwnershipBuilder.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -165,8 +164,9 @@ public virtual ReferenceOwnershipBuilder HasEntityTypeAnnotation([NotNull] strin /// The names of the properties that make up the primary key. /// An object that can be used to configure the primary key. public virtual KeyBuilder HasKey([NotNull] params string[] propertyNames) - => new KeyBuilder(RelatedEntityType.Builder.PrimaryKey( - Check.NotEmpty(propertyNames, nameof(propertyNames)), ConfigurationSource.Explicit)); + => new KeyBuilder( + RelatedEntityType.Builder.PrimaryKey( + Check.NotEmpty(propertyNames, nameof(propertyNames)), ConfigurationSource.Explicit)); /// /// @@ -254,8 +254,9 @@ public virtual ReferenceOwnershipBuilder Ignore([NotNull] string propertyName) /// The names of the properties that make up the index. /// An object that can be used to configure the index. public virtual IndexBuilder HasIndex([NotNull] params string[] propertyNames) - => new IndexBuilder(RelatedEntityType.Builder.HasIndex( - Check.NotEmpty(propertyNames, nameof(propertyNames)), ConfigurationSource.Explicit)); + => new IndexBuilder( + RelatedEntityType.Builder.HasIndex( + Check.NotEmpty(propertyNames, nameof(propertyNames)), ConfigurationSource.Explicit)); /// /// diff --git a/src/EFCore/Metadata/Builders/ReferenceOwnershipBuilder`.cs b/src/EFCore/Metadata/Builders/ReferenceOwnershipBuilder`.cs index 398d02ab78d..2cd7b6e9c48 100644 --- a/src/EFCore/Metadata/Builders/ReferenceOwnershipBuilder`.cs +++ b/src/EFCore/Metadata/Builders/ReferenceOwnershipBuilder`.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; @@ -225,8 +224,9 @@ public class ReferenceOwnershipBuilder : ReferenceOwner /// /// An object that can be used to configure the primary key. public virtual KeyBuilder HasKey([NotNull] Expression> keyExpression) - => new KeyBuilder(RelatedEntityType.Builder.PrimaryKey( - Check.NotNull(keyExpression, nameof(keyExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); + => new KeyBuilder( + RelatedEntityType.Builder.PrimaryKey( + Check.NotNull(keyExpression, nameof(keyExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); /// /// @@ -290,8 +290,9 @@ public virtual PropertyBuilder Property([NotNull] Expressi /// /// An object that can be used to configure the index. public virtual IndexBuilder HasIndex([NotNull] Expression> indexExpression) - => new IndexBuilder(RelatedEntityType.Builder.HasIndex( - Check.NotNull(indexExpression, nameof(indexExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); + => new IndexBuilder( + RelatedEntityType.Builder.HasIndex( + Check.NotNull(indexExpression, nameof(indexExpression)).GetPropertyAccessList(), ConfigurationSource.Explicit)); /// /// @@ -340,8 +341,9 @@ public virtual IndexBuilder HasIndex([NotNull] Expression OwnsOne( [NotNull] Expression> navigationExpression) where TNewRelatedEntity : class - => OwnsOneBuilder(new PropertyIdentity( - Check.NotNull(navigationExpression, nameof(navigationExpression)).GetPropertyAccess())); + => OwnsOneBuilder( + new PropertyIdentity( + Check.NotNull(navigationExpression, nameof(navigationExpression)).GetPropertyAccess())); /// /// diff --git a/src/EFCore/Metadata/Builders/ReferenceReferenceBuilder.cs b/src/EFCore/Metadata/Builders/ReferenceReferenceBuilder.cs index a858f43083a..c95e8d06f88 100644 --- a/src/EFCore/Metadata/Builders/ReferenceReferenceBuilder.cs +++ b/src/EFCore/Metadata/Builders/ReferenceReferenceBuilder.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Reflection; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking; diff --git a/src/EFCore/Metadata/Builders/ReferenceReferenceBuilder`.cs b/src/EFCore/Metadata/Builders/ReferenceReferenceBuilder`.cs index a5d10ee6ad2..a3ccc171008 100644 --- a/src/EFCore/Metadata/Builders/ReferenceReferenceBuilder`.cs +++ b/src/EFCore/Metadata/Builders/ReferenceReferenceBuilder`.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; using System.Linq.Expressions; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking; diff --git a/src/EFCore/Metadata/Conventions/Internal/ConstructorBindingConvention.cs b/src/EFCore/Metadata/Conventions/Internal/ConstructorBindingConvention.cs index d7ca07dc12b..fb70047a6fb 100644 --- a/src/EFCore/Metadata/Conventions/Internal/ConstructorBindingConvention.cs +++ b/src/EFCore/Metadata/Conventions/Internal/ConstructorBindingConvention.cs @@ -84,17 +84,20 @@ public virtual InternalModelBuilder Apply(InternalModelBuilder modelBuilder) { var constructorErrors = bindingFailures.SelectMany(f => f) .GroupBy(f => f.Member as ConstructorInfo) - .Select(x => - CoreStrings.ConstructorBindingFailed( - string.Join("', '", x.Select(f => f.Name)), - entityType.DisplayName() + "(" + - string.Join(", ", x.Key.GetParameters().Select(y => - y.ParameterType.ShortDisplayName() + " " + y.Name) - ) + + .Select( + x => + CoreStrings.ConstructorBindingFailed( + string.Join("', '", x.Select(f => f.Name)), + entityType.DisplayName() + "(" + + string.Join( + ", ", x.Key.GetParameters().Select( + y => + y.ParameterType.ShortDisplayName() + " " + y.Name) + ) + ")" - ) + ) ); - + throw new InvalidOperationException( CoreStrings.ConstructorNotFound( entityType.DisplayName(), diff --git a/src/EFCore/Metadata/Conventions/Internal/CoreConventionSetBuilderDependencies.cs b/src/EFCore/Metadata/Conventions/Internal/CoreConventionSetBuilderDependencies.cs index 41e14b7cdad..23e56e0bb87 100644 --- a/src/EFCore/Metadata/Conventions/Internal/CoreConventionSetBuilderDependencies.cs +++ b/src/EFCore/Metadata/Conventions/Internal/CoreConventionSetBuilderDependencies.cs @@ -9,8 +9,6 @@ using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Storage; -using Microsoft.EntityFrameworkCore.Storage.Internal; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Utilities; using Microsoft.Extensions.Logging; @@ -58,11 +56,11 @@ public sealed class CoreConventionSetBuilderDependencies /// /// public CoreConventionSetBuilderDependencies( - [NotNull] ITypeMappingSource typeMappingSource, - [CanBeNull] IConstructorBindingFactory constructorBindingFactory, - [CanBeNull] IParameterBindingFactories parameterBindingFactories, - [CanBeNull] IMemberClassifier memberClassifier, - [CanBeNull] IDiagnosticsLogger logger) + [NotNull] ITypeMappingSource typeMappingSource, + [CanBeNull] IConstructorBindingFactory constructorBindingFactory, + [CanBeNull] IParameterBindingFactories parameterBindingFactories, + [CanBeNull] IMemberClassifier memberClassifier, + [CanBeNull] IDiagnosticsLogger logger) { Check.NotNull(typeMappingSource, nameof(typeMappingSource)); diff --git a/src/EFCore/Metadata/Conventions/Internal/DerivedTypeDiscoveryConvention.cs b/src/EFCore/Metadata/Conventions/Internal/DerivedTypeDiscoveryConvention.cs index f8725fb3cc1..4cfe9891801 100644 --- a/src/EFCore/Metadata/Conventions/Internal/DerivedTypeDiscoveryConvention.cs +++ b/src/EFCore/Metadata/Conventions/Internal/DerivedTypeDiscoveryConvention.cs @@ -29,13 +29,13 @@ public virtual InternalEntityTypeBuilder Apply(InternalEntityTypeBuilder entityT var model = entityType.Model; var directlyDerivedTypes = model.GetEntityTypes().Where( - t => t != entityType - && t.HasClrType() - && !t.HasDefiningNavigation() - && t.FindDeclaredOwnership() == null - && !model.ShouldBeOwnedType(model.GetDisplayName(t.ClrType)) - && ((t.BaseType == null && clrType.GetTypeInfo().IsAssignableFrom(t.ClrType.GetTypeInfo())) - || (t.BaseType == entityType.BaseType && FindClosestBaseType(t) == entityType))) + t => t != entityType + && t.HasClrType() + && !t.HasDefiningNavigation() + && t.FindDeclaredOwnership() == null + && !model.ShouldBeOwnedType(model.GetDisplayName(t.ClrType)) + && ((t.BaseType == null && clrType.GetTypeInfo().IsAssignableFrom(t.ClrType.GetTypeInfo())) + || (t.BaseType == entityType.BaseType && FindClosestBaseType(t) == entityType))) .ToList(); foreach (var directlyDerivedType in directlyDerivedTypes) diff --git a/src/EFCore/Metadata/Conventions/Internal/ForeignKeyAttributeConvention.cs b/src/EFCore/Metadata/Conventions/Internal/ForeignKeyAttributeConvention.cs index 0acb62f719a..7f6fc337172 100644 --- a/src/EFCore/Metadata/Conventions/Internal/ForeignKeyAttributeConvention.cs +++ b/src/EFCore/Metadata/Conventions/Internal/ForeignKeyAttributeConvention.cs @@ -121,6 +121,7 @@ var fkPropertiesOnDependentToPrincipal { return null; } + invertConfigurationSource = ConfigurationSource.DataAnnotation; fkPropertiesToSet = new List { @@ -200,10 +201,11 @@ var fkPropertiesOnDependentToPrincipal if (existingProperties != null) { var conflictingFk = foreignKey.DeclaringEntityType.FindForeignKeys(existingProperties) - .FirstOrDefault(fk => fk != foreignKey - && fk.PrincipalEntityType == foreignKey.PrincipalEntityType - && fk.GetConfigurationSource() == ConfigurationSource.DataAnnotation - && fk.GetForeignKeyPropertiesConfigurationSource() == ConfigurationSource.DataAnnotation); + .FirstOrDefault( + fk => fk != foreignKey + && fk.PrincipalEntityType == foreignKey.PrincipalEntityType + && fk.GetConfigurationSource() == ConfigurationSource.DataAnnotation + && fk.GetForeignKeyPropertiesConfigurationSource() == ConfigurationSource.DataAnnotation); if (conflictingFk != null) { throw new InvalidOperationException( @@ -239,12 +241,12 @@ private static InternalRelationshipBuilder SplitNavigationsToSeparateRelationshi return relationshipBuilder == null ? null : foreignKey.PrincipalEntityType.Builder.Relationship( - foreignKey.DeclaringEntityType.Builder, - principalToDepedentNavigationName, - null, - ConfigurationSource.DataAnnotation) == null - ? null - : relationshipBuilder; + foreignKey.DeclaringEntityType.Builder, + principalToDepedentNavigationName, + null, + ConfigurationSource.DataAnnotation) == null + ? null + : relationshipBuilder; } private static ForeignKeyAttribute GetForeignKeyAttribute(TypeBase entityType, string propertyName) @@ -394,10 +396,11 @@ var fkPropertyOnPrincipal = FindForeignKeyAttributeOnProperty(foreignKey.PrincipalEntityType, declaredNavigation.Name); if (fkPropertyOnPrincipal != null) { - throw new InvalidOperationException(CoreStrings.FkAttributeOnNonUniquePrincipal( - declaredNavigation.Name, - foreignKey.PrincipalEntityType.DisplayName(), - foreignKey.DeclaringEntityType.DisplayName())); + throw new InvalidOperationException( + CoreStrings.FkAttributeOnNonUniquePrincipal( + declaredNavigation.Name, + foreignKey.PrincipalEntityType.DisplayName(), + foreignKey.DeclaringEntityType.DisplayName())); } } } diff --git a/src/EFCore/Metadata/Conventions/Internal/ForeignKeyPropertyDiscoveryConvention.cs b/src/EFCore/Metadata/Conventions/Internal/ForeignKeyPropertyDiscoveryConvention.cs index 34f0a01b837..20d1f5a1a83 100644 --- a/src/EFCore/Metadata/Conventions/Internal/ForeignKeyPropertyDiscoveryConvention.cs +++ b/src/EFCore/Metadata/Conventions/Internal/ForeignKeyPropertyDiscoveryConvention.cs @@ -240,13 +240,14 @@ private InternalRelationshipBuilder ReuniquifyTemporaryProperties(ForeignKey for var relationshipBuilder = foreignKey.Builder; using (var batch = foreignKey.DeclaringEntityType.Model.ConventionDispatcher.StartBatch()) { - var temporaryProperties = foreignKey.Properties.Where(p => - p.IsShadowProperty - && ConfigurationSource.Convention.Overrides(p.GetConfigurationSource())).ToList(); + var temporaryProperties = foreignKey.Properties.Where( + p => + p.IsShadowProperty + && ConfigurationSource.Convention.Overrides(p.GetConfigurationSource())).ToList(); var keysToDetach = temporaryProperties.SelectMany( - p => p.GetContainingKeys() - .Where(k => ConfigurationSource.Convention.Overrides(k.GetConfigurationSource()))) + p => p.GetContainingKeys() + .Where(k => ConfigurationSource.Convention.Overrides(k.GetConfigurationSource()))) .Distinct().ToList(); List detachedRelationships = null; @@ -336,12 +337,12 @@ private static IReadOnlyList GetCompatiblePrimaryKeyProperties(EntityT { var dependentPkProperties = dependentEntityType.FindPrimaryKey()?.Properties; return (dependentPkProperties != null) - && ForeignKey.AreCompatible( - propertiesToReference, - dependentPkProperties, - principalEntityType, - dependentEntityType, - false) + && ForeignKey.AreCompatible( + propertiesToReference, + dependentPkProperties, + principalEntityType, + dependentEntityType, + false) ? dependentPkProperties : null; } @@ -433,13 +434,11 @@ private static IReadOnlyList GetCompatiblePrimaryKeyProperties(EntityT isKeyContainedInForeignKey = false; break; } - else + + if (!foreignKey.IsUnique) { - if (!foreignKey.IsUnique) - { - // Stop searching if match found, but is incompatible - return true; - } + // Stop searching if match found, but is incompatible + return true; } } diff --git a/src/EFCore/Metadata/Conventions/Internal/InversePropertyAttributeConvention.cs b/src/EFCore/Metadata/Conventions/Internal/InversePropertyAttributeConvention.cs index 1213b144bda..1ff97895935 100644 --- a/src/EFCore/Metadata/Conventions/Internal/InversePropertyAttributeConvention.cs +++ b/src/EFCore/Metadata/Conventions/Internal/InversePropertyAttributeConvention.cs @@ -199,17 +199,17 @@ public class InversePropertyAttributeConvention : } return entityType.Model.ShouldBeOwnedType(entityType.ClrType) - && !entityType.IsInOwnershipPath(targetEntityTypeBuilder.Metadata) + && !entityType.IsInOwnershipPath(targetEntityTypeBuilder.Metadata) ? targetEntityTypeBuilder.Owns( entityTypeBuilder.Metadata.ClrType, inverseNavigationPropertyInfo, navigationMemberInfo, ConfigurationSource.Convention) : targetEntityTypeBuilder.Relationship( - entityTypeBuilder, - inverseNavigationPropertyInfo, - navigationMemberInfo, - ConfigurationSource.DataAnnotation); + entityTypeBuilder, + inverseNavigationPropertyInfo, + navigationMemberInfo, + ConfigurationSource.DataAnnotation); } /// @@ -339,11 +339,7 @@ public virtual InternalModelBuilder Apply(InternalModelBuilder modelBuilder) if (ambiguousInverse != null) { _logger.MultipleInversePropertiesSameTargetWarning( - new[] - { - Tuple.Create(referencingNavigationWithAttribute.Item1, referencingNavigationWithAttribute.Item2.ClrType), - Tuple.Create(ambiguousInverse.Value.Item1, ambiguousInverse.Value.Item2.ClrType) - }, + new[] { Tuple.Create(referencingNavigationWithAttribute.Item1, referencingNavigationWithAttribute.Item2.ClrType), Tuple.Create(ambiguousInverse.Value.Item1, ambiguousInverse.Value.Item2.ClrType) }, inverseNavigation.Key, entityType.ClrType); break; diff --git a/src/EFCore/Metadata/Conventions/Internal/NavigationAttributeEntityTypeConvention.cs b/src/EFCore/Metadata/Conventions/Internal/NavigationAttributeEntityTypeConvention.cs index 1723d1c891c..8044786da89 100644 --- a/src/EFCore/Metadata/Conventions/Internal/NavigationAttributeEntityTypeConvention.cs +++ b/src/EFCore/Metadata/Conventions/Internal/NavigationAttributeEntityTypeConvention.cs @@ -204,7 +204,7 @@ private Type FindCandidateNavigationWithAttributePropertyType([NotNull] Property { var targetClrType = _memberClassifier.FindCandidateNavigationPropertyType(propertyInfo); return targetClrType == null - || !Attribute.IsDefined(propertyInfo, typeof(TAttribute), inherit: true) + || !Attribute.IsDefined(propertyInfo, typeof(TAttribute), inherit: true) ? null : targetClrType; } diff --git a/src/EFCore/Metadata/Conventions/Internal/NavigationAttributeNavigationConvention.cs b/src/EFCore/Metadata/Conventions/Internal/NavigationAttributeNavigationConvention.cs index bf9ceb2092b..0dad1a47731 100644 --- a/src/EFCore/Metadata/Conventions/Internal/NavigationAttributeNavigationConvention.cs +++ b/src/EFCore/Metadata/Conventions/Internal/NavigationAttributeNavigationConvention.cs @@ -69,7 +69,7 @@ public abstract class NavigationAttributeNavigationConvention : INav var property = entityType.GetRuntimeProperties().Find(propertyName); return property != null - && Attribute.IsDefined(property, typeof(TCustomAttribute), inherit: true) + && Attribute.IsDefined(property, typeof(TCustomAttribute), inherit: true) ? property.GetCustomAttributes(true) : Enumerable.Empty(); } diff --git a/src/EFCore/Metadata/Conventions/Internal/PropertyMappingValidationConvention.cs b/src/EFCore/Metadata/Conventions/Internal/PropertyMappingValidationConvention.cs index 229325ec69f..bc109e08af5 100644 --- a/src/EFCore/Metadata/Conventions/Internal/PropertyMappingValidationConvention.cs +++ b/src/EFCore/Metadata/Conventions/Internal/PropertyMappingValidationConvention.cs @@ -110,7 +110,7 @@ var isTargetWeakOrOwned // ReSharper disable CheckForReferenceEqualityInstead.1 // ReSharper disable CheckForReferenceEqualityInstead.3 if ((!entityType.IsQueryType - || targetSequenceType == null) + || targetSequenceType == null) && entityType.GetDerivedTypes().All( dt => dt.FindDeclaredNavigation(actualProperty.GetSimpleMemberName()) == null) && (!isTargetWeakOrOwned diff --git a/src/EFCore/Metadata/Conventions/Internal/RelationshipDiscoveryConvention.cs b/src/EFCore/Metadata/Conventions/Internal/RelationshipDiscoveryConvention.cs index 4b5d7978e36..a44f0bd8e1b 100644 --- a/src/EFCore/Metadata/Conventions/Internal/RelationshipDiscoveryConvention.cs +++ b/src/EFCore/Metadata/Conventions/Internal/RelationshipDiscoveryConvention.cs @@ -230,8 +230,9 @@ private IReadOnlyList FindRelationshipCandidates(Internal continue; } - candidates.Add(new RelationshipCandidate( - actualTargetEntityTypeBuilder, relationshipCandidate.NavigationProperties, relationshipCandidate.InverseProperties)); + candidates.Add( + new RelationshipCandidate( + actualTargetEntityTypeBuilder, relationshipCandidate.NavigationProperties, relationshipCandidate.InverseProperties)); } return candidates; @@ -246,7 +247,8 @@ private IReadOnlyList FindRelationshipCandidates(Internal Type targetClrType, MemberInfo navigationInfo, ConfigurationSource? configurationSource) - => GetTargetEntityTypeBuilder(entityTypeBuilder, targetClrType, navigationInfo, + => GetTargetEntityTypeBuilder( + entityTypeBuilder, targetClrType, navigationInfo, entityTypeBuilder.Metadata.FindOwnership(), configurationSource); private static InternalEntityTypeBuilder GetTargetEntityTypeBuilder( @@ -564,8 +566,9 @@ private IReadOnlyList FindRelationshipCandidates(Internal if (inverseCandidate != null) { var relationshipsToDerivedTypes = relationshipCandidatesHierarchy - .Where(r => r.TargetTypeBuilder != relationshipCandidate.TargetTypeBuilder - && relationshipCandidate.TargetTypeBuilder.Metadata.IsAssignableFrom(r.TargetTypeBuilder.Metadata)); + .Where( + r => r.TargetTypeBuilder != relationshipCandidate.TargetTypeBuilder + && relationshipCandidate.TargetTypeBuilder.Metadata.IsAssignableFrom(r.TargetTypeBuilder.Metadata)); foreach (var relationshipToDerivedType in relationshipsToDerivedTypes) { relationshipToDerivedType.InverseProperties.RemoveAll(i => i.GetSimpleMemberName() == inverseCandidate.GetSimpleMemberName()); @@ -647,8 +650,8 @@ private IReadOnlyList FindRelationshipCandidates(Internal { var existingNavigation = entityType.FindNavigation(relationshipCandidate.NavigationProperties.Single().GetSimpleMemberName()); if (existingNavigation != null - && existingNavigation.ForeignKey.DeclaringEntityType == targetEntityType - && existingNavigation.ForeignKey.GetPrincipalEndConfigurationSource().OverridesStrictly(ConfigurationSource.Convention)) + && existingNavigation.ForeignKey.DeclaringEntityType == targetEntityType + && existingNavigation.ForeignKey.GetPrincipalEndConfigurationSource().OverridesStrictly(ConfigurationSource.Convention)) { ambiguousOwnership = false; } diff --git a/src/EFCore/Metadata/Conventions/Internal/ValueGeneratorConvention.cs b/src/EFCore/Metadata/Conventions/Internal/ValueGeneratorConvention.cs index 5324e26f726..c11051283dc 100644 --- a/src/EFCore/Metadata/Conventions/Internal/ValueGeneratorConvention.cs +++ b/src/EFCore/Metadata/Conventions/Internal/ValueGeneratorConvention.cs @@ -102,8 +102,8 @@ public virtual bool Apply(InternalEntityTypeBuilder entityTypeBuilder, EntityTyp /// public virtual ValueGenerated? GetValueGenerated([NotNull] Property property) => !property.IsForeignKey() - && property.PrimaryKey?.Properties.Count(p => !p.IsForeignKey()) == 1 - && CanBeGenerated(property) + && property.PrimaryKey?.Properties.Count(p => !p.IsForeignKey()) == 1 + && CanBeGenerated(property) ? ValueGenerated.OnAdd : (ValueGenerated?)null; @@ -117,10 +117,10 @@ private static bool CanBeGenerated(Property property) { var propertyType = property.ClrType.UnwrapNullableType(); return (propertyType.IsInteger() - && propertyType != typeof(byte)) - || propertyType == typeof(Guid) - || propertyType == typeof(string) - || propertyType == typeof(byte[]) + && propertyType != typeof(byte)) + || propertyType == typeof(Guid) + || propertyType == typeof(string) + || propertyType == typeof(byte[]) ? true : false; } diff --git a/src/EFCore/Metadata/Internal/EntityType.cs b/src/EFCore/Metadata/Internal/EntityType.cs index 14d057923fa..0546a53a047 100644 --- a/src/EFCore/Metadata/Internal/EntityType.cs +++ b/src/EFCore/Metadata/Internal/EntityType.cs @@ -127,8 +127,7 @@ public EntityType([NotNull] Type clrType, [NotNull] Model model, ConfigurationSo /// public virtual InternalEntityTypeBuilder Builder { - [DebuggerStepThrough] - get; + [DebuggerStepThrough] get; [DebuggerStepThrough] [param: CanBeNull] set; @@ -575,7 +574,7 @@ public virtual Key FindPrimaryKey([CanBeNull] IReadOnlyList properties } return _primaryKey != null - && PropertyListComparer.Instance.Compare(_primaryKey.Properties, properties) == 0 + && PropertyListComparer.Instance.Compare(_primaryKey.Properties, properties) == 0 ? _primaryKey : null; } @@ -901,9 +900,9 @@ private void CheckKeyNotInUse(Key key) if (principalKey.ReferencingForeignKeys == null) { principalKey.ReferencingForeignKeys = new SortedSet(ForeignKeyComparer.Instance) - { - foreignKey - }; + { + foreignKey + }; } else { @@ -914,9 +913,9 @@ private void CheckKeyNotInUse(Key key) if (principalEntityType.DeclaredReferencingForeignKeys == null) { principalEntityType.DeclaredReferencingForeignKeys = new SortedSet(ForeignKeyComparer.Instance) - { - foreignKey - }; + { + foreignKey + }; } else { @@ -1632,7 +1631,6 @@ private Index RemoveIndex(Index index) isIndexedProperty: false); } - /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. @@ -2175,26 +2173,22 @@ public virtual void AddData([NotNull] IEnumerable data) IModel ITypeBase.Model { - [DebuggerStepThrough] - get => Model; + [DebuggerStepThrough] get => Model; } IMutableModel IMutableTypeBase.Model { - [DebuggerStepThrough] - get => Model; + [DebuggerStepThrough] get => Model; } IMutableModel IMutableEntityType.Model { - [DebuggerStepThrough] - get => Model; + [DebuggerStepThrough] get => Model; } IEntityType IEntityType.BaseType { - [DebuggerStepThrough] - get => _baseType; + [DebuggerStepThrough] get => _baseType; } IMutableEntityType IMutableEntityType.BaseType @@ -2211,8 +2205,7 @@ LambdaExpression IMutableEntityType.QueryFilter IEntityType IEntityType.DefiningEntityType { - [DebuggerStepThrough] - get => DefiningEntityType; + [DebuggerStepThrough] get => DefiningEntityType; } IMutableKey IMutableEntityType.SetPrimaryKey(IReadOnlyList properties) diff --git a/src/EFCore/Metadata/Internal/ForeignKey.cs b/src/EFCore/Metadata/Internal/ForeignKey.cs index 031eb7b5b02..a3250f39835 100644 --- a/src/EFCore/Metadata/Internal/ForeignKey.cs +++ b/src/EFCore/Metadata/Internal/ForeignKey.cs @@ -723,13 +723,13 @@ IMutableNavigation IMutableForeignKey.DependentToPrincipal } return principalProperties != null - && dependentProperties != null - && !AreCompatible( - principalProperties, - dependentProperties, - principalEntityType, - dependentEntityType, - shouldThrow) + && dependentProperties != null + && !AreCompatible( + principalProperties, + dependentProperties, + principalEntityType, + dependentEntityType, + shouldThrow) ? false : true; } diff --git a/src/EFCore/Metadata/Internal/IndexedPropertyGetterFactory.cs b/src/EFCore/Metadata/Internal/IndexedPropertyGetterFactory.cs index 5dffd2a82c3..afd68d7d56c 100644 --- a/src/EFCore/Metadata/Internal/IndexedPropertyGetterFactory.cs +++ b/src/EFCore/Metadata/Internal/IndexedPropertyGetterFactory.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using System.Linq.Expressions; using System.Reflection; using Microsoft.EntityFrameworkCore.ChangeTracking; @@ -35,7 +34,10 @@ public class IndexedPropertyGetterFactory : ClrAccessorFactory() { Expression.Constant(propertyBase.Name) }; + var indexerParameterList = new List + { + Expression.Constant(propertyBase.Name) + }; Expression readExpression = Expression.MakeIndex( entityParameter, propertyInfo, indexerParameterList); diff --git a/src/EFCore/Metadata/Internal/IndexedPropertySetterFactory.cs b/src/EFCore/Metadata/Internal/IndexedPropertySetterFactory.cs index f29370a8e93..4e7c472a39c 100644 --- a/src/EFCore/Metadata/Internal/IndexedPropertySetterFactory.cs +++ b/src/EFCore/Metadata/Internal/IndexedPropertySetterFactory.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using System.Linq.Expressions; using System.Reflection; using Microsoft.EntityFrameworkCore.Internal; @@ -35,7 +34,10 @@ public class IndexedPropertySetterFactory : ClrAccessorFactory() { Expression.Constant(propertyBase.Name) }; + var indexerParameterList = new List + { + Expression.Constant(propertyBase.Name) + }; // the indexer expects the value to be an object, but the indexed property // can have been declared as a different type so cast it to that if necessary diff --git a/src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs b/src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs index a735dd1f3a4..20ecf4a16b3 100644 --- a/src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs +++ b/src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs @@ -128,10 +128,8 @@ public InternalEntityTypeBuilder([NotNull] EntityType metadata, [NotNull] Intern // TODO: Use convention batch to get the updated builder, see #214 return Metadata.FindPrimaryKey(properties).Builder; } - else - { - return keyBuilder; - } + + return keyBuilder; } /// @@ -425,7 +423,7 @@ public virtual InternalPropertyBuilder Property([NotNull] MemberInfo clrProperty } return builder != null - && builder.Metadata.Builder == null + && builder.Metadata.Builder == null ? Metadata.FindProperty(propertyName)?.Builder : builder; } @@ -739,16 +737,16 @@ public virtual bool Ignore([NotNull] string name, ConfigurationSource configurat if (foreignKey.GetConfigurationSource() != navigationConfigurationSource) { if (foreignKey.Builder.Navigations( - isDependent ? PropertyIdentity.None : (PropertyIdentity?)null, - isDependent ? (PropertyIdentity?)null : PropertyIdentity.None, - configurationSource) == null) + isDependent ? PropertyIdentity.None : (PropertyIdentity?)null, + isDependent ? (PropertyIdentity?)null : PropertyIdentity.None, + configurationSource) == null) { Metadata.Unignore(name); return false; } } else if (foreignKey.DeclaringEntityType.Builder.RemoveForeignKey( - foreignKey, configurationSource, canOverrideSameSource: configurationSource == ConfigurationSource.Explicit) == null) + foreignKey, configurationSource, canOverrideSameSource: configurationSource == ConfigurationSource.Explicit) == null) { Metadata.Unignore(name); return false; @@ -984,8 +982,9 @@ public virtual InternalEntityTypeBuilder HasBaseType([CanBeNull] string baseEnti detachedProperties = DetachProperties(duplicatedProperties); var propertiesToRemove = Metadata.GetDerivedTypesInclusive().SelectMany(et => et.GetDeclaredProperties()) - .Where(p => !p.GetConfigurationSource() - .Overrides(baseEntityType.FindIgnoredMemberConfigurationSource(p.Name))) + .Where( + p => !p.GetConfigurationSource() + .Overrides(baseEntityType.FindIgnoredMemberConfigurationSource(p.Name))) .ToList(); foreach (var property in propertiesToRemove) { @@ -1067,8 +1066,9 @@ public virtual InternalEntityTypeBuilder HasBaseType([CanBeNull] string baseEnti } foreach (var key in Metadata.GetKeys() - .Where(k => k.ReferencingForeignKeys != null - && k.Properties.Any(p => removedInheritedProperties.Contains(p))).ToList()) + .Where( + k => k.ReferencingForeignKeys != null + && k.Properties.Any(p => removedInheritedProperties.Contains(p))).ToList()) { foreach (var referencingForeignKey in key.ReferencingForeignKeys.ToList()) { @@ -2199,7 +2199,7 @@ private static InternalIndexBuilder DetachIndex(Index indexToDetach) } if (existingNavigation.ForeignKey.DeclaringEntityType.Builder - .RemoveForeignKey(existingNavigation.ForeignKey, configurationSource) == null) + .RemoveForeignKey(existingNavigation.ForeignKey, configurationSource) == null) { return null; } @@ -2309,11 +2309,14 @@ private static InternalIndexBuilder DetachIndex(Index indexToDetach) public virtual bool RemoveNonOwnershipRelationships(ForeignKey ownership, ConfigurationSource configurationSource) { var incompatibleRelationships = Metadata.GetDerivedForeignKeysInclusive() - .Where(fk => !fk.IsOwnership && fk.PrincipalToDependent != null - && !Contains(ownership, fk)) - .Concat(Metadata.GetDerivedReferencingForeignKeysInclusive() - .Where(fk => !fk.IsOwnership - && !Contains(fk.DeclaringEntityType.FindOwnership(), fk))) + .Where( + fk => !fk.IsOwnership && fk.PrincipalToDependent != null + && !Contains(ownership, fk)) + .Concat( + Metadata.GetDerivedReferencingForeignKeysInclusive() + .Where( + fk => !fk.IsOwnership + && !Contains(fk.DeclaringEntityType.FindOwnership(), fk))) .Distinct() .ToList(); @@ -2332,8 +2335,8 @@ public virtual bool RemoveNonOwnershipRelationships(ForeignKey ownership, Config private bool Contains(IForeignKey inheritedFk, IForeignKey derivedFk) => inheritedFk != null - && inheritedFk.PrincipalEntityType.IsAssignableFrom(derivedFk.PrincipalEntityType) - && PropertyListComparer.Instance.Equals(inheritedFk.Properties, derivedFk.Properties); + && inheritedFk.PrincipalEntityType.IsAssignableFrom(derivedFk.PrincipalEntityType) + && PropertyListComparer.Instance.Equals(inheritedFk.Properties, derivedFk.Properties); /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used @@ -2574,6 +2577,7 @@ private bool Contains(IForeignKey inheritedFk, IForeignKey derivedFk) { canReuniquify = true; } + break; } @@ -2586,6 +2590,7 @@ private bool Contains(IForeignKey inheritedFk, IForeignKey derivedFk) { canReuniquify = true; } + break; } } @@ -2637,7 +2642,8 @@ private bool Contains(IForeignKey inheritedFk, IForeignKey derivedFk) { return null; } - else if (clrProperty != null) + + if (clrProperty != null) { propertyBuilder = Property(clrProperty, configurationSource.Value); } diff --git a/src/EFCore/Metadata/Internal/InternalMetadataBuilder.cs b/src/EFCore/Metadata/Internal/InternalMetadataBuilder.cs index 7c77392eb6c..829e5b26be4 100644 --- a/src/EFCore/Metadata/Internal/InternalMetadataBuilder.cs +++ b/src/EFCore/Metadata/Internal/InternalMetadataBuilder.cs @@ -90,7 +90,7 @@ public virtual bool CanSetAnnotation([NotNull] string name, [CanBeNull] object v var existingConfigurationSource = annotation.GetConfigurationSource(); return !configurationSource.Overrides(existingConfigurationSource) - || ((configurationSource == existingConfigurationSource) && !canOverrideSameSource) + || ((configurationSource == existingConfigurationSource) && !canOverrideSameSource) ? false : true; } diff --git a/src/EFCore/Metadata/Internal/InternalRelationshipBuilder.cs b/src/EFCore/Metadata/Internal/InternalRelationshipBuilder.cs index 8024c49a2bc..f3280bda0d3 100644 --- a/src/EFCore/Metadata/Internal/InternalRelationshipBuilder.cs +++ b/src/EFCore/Metadata/Internal/InternalRelationshipBuilder.cs @@ -909,7 +909,8 @@ public virtual InternalRelationshipBuilder IsOwnership(bool ownership, Configura return newRelationshipBuilder; } - else if (otherOwnerships.Count > 0) + + if (otherOwnerships.Count > 0) { if (!Metadata.GetConfigurationSource().Overrides(ConfigurationSource.Explicit) && Metadata.PrincipalEntityType.IsInDefinitionPath(Metadata.DeclaringEntityType.ClrType)) @@ -960,52 +961,48 @@ public virtual InternalRelationshipBuilder IsOwnership(bool ownership, Configura return batch.Run(newRelationshipBuilder); } } - else + + using (var batch = ModelBuilder.Metadata.ConventionDispatcher.StartBatch()) { - using (var batch = ModelBuilder.Metadata.ConventionDispatcher.StartBatch()) - { - Metadata.SetIsOwnership(true, configurationSource); + Metadata.SetIsOwnership(true, configurationSource); - newRelationshipBuilder = batch.Run(newRelationshipBuilder); - } + newRelationshipBuilder = batch.Run(newRelationshipBuilder); + } - if(newRelationshipBuilder == null - && Metadata.PrincipalEntityType.Builder != null) + if (newRelationshipBuilder == null + && Metadata.PrincipalEntityType.Builder != null) + { + newRelationshipBuilder = Metadata.PrincipalEntityType.FindNavigation(Metadata.PrincipalToDependent.Name) + ?.ForeignKey.Builder; + } + + using (var batch = ModelBuilder.Metadata.ConventionDispatcher.StartBatch()) + { + foreach (var invertedOwnership in invertedOwnerships) { - newRelationshipBuilder = Metadata.PrincipalEntityType.FindNavigation(Metadata.PrincipalToDependent.Name) - ?.ForeignKey.Builder; + invertedOwnership.DeclaringEntityType.Builder.RemoveForeignKey(invertedOwnership, configurationSource); } - using (var batch = ModelBuilder.Metadata.ConventionDispatcher.StartBatch()) + if (newRelationshipBuilder != null) { - foreach (var invertedOwnership in invertedOwnerships) - { - invertedOwnership.DeclaringEntityType.Builder.RemoveForeignKey(invertedOwnership, configurationSource); - } + newRelationshipBuilder.Metadata.DeclaringEntityType.Builder.HasBaseType((Type)null, configurationSource); - if (newRelationshipBuilder != null) + if (!newRelationshipBuilder.Metadata.DeclaringEntityType.Builder + .RemoveNonOwnershipRelationships(newRelationshipBuilder.Metadata, configurationSource)) { - newRelationshipBuilder.Metadata.DeclaringEntityType.Builder.HasBaseType((Type)null, configurationSource); - - if (!newRelationshipBuilder.Metadata.DeclaringEntityType.Builder - .RemoveNonOwnershipRelationships(newRelationshipBuilder.Metadata, configurationSource)) - { - return null; - } - - return batch.Run(newRelationshipBuilder); + return null; } - } - return null; + return batch.Run(newRelationshipBuilder); + } } - } - else - { - Metadata.SetIsOwnership(false, configurationSource); - return this; + return null; } + + Metadata.SetIsOwnership(false, configurationSource); + + return this; } /// @@ -1302,19 +1299,19 @@ private bool CanSetUnique(bool unique, ConfigurationSource? configurationSource, } if (!CanSetRelatedTypes( - principalEntityType, - dependentEntityType, - ConfigurationSource.Explicit, - null, - null, - configurationSource, - configurationSource == ConfigurationSource.Explicit, - out var shouldInvert, - out var shouldResetToPrincipal, - out var shouldResetToDependent, - out var shouldResetPrincipalProperties, - out var shouldResetDependentProperties, - out var shouldBeUnique) + principalEntityType, + dependentEntityType, + ConfigurationSource.Explicit, + null, + null, + configurationSource, + configurationSource == ConfigurationSource.Explicit, + out var shouldInvert, + out var shouldResetToPrincipal, + out var shouldResetToDependent, + out var shouldResetPrincipalProperties, + out var shouldResetDependentProperties, + out var shouldBeUnique) && configurationSource != ConfigurationSource.Explicit) { return null; @@ -1975,17 +1972,17 @@ private bool CanInvert(ConfigurationSource? configurationSource) || resetToDependent) { newRelationshipBuilder = newRelationshipBuilder.Navigations( - resetToPrincipal ? PropertyIdentity.None : (PropertyIdentity?)null, - resetToDependent ? PropertyIdentity.None : (PropertyIdentity?)null, - configurationSource) + resetToPrincipal ? PropertyIdentity.None : (PropertyIdentity?)null, + resetToDependent ? PropertyIdentity.None : (PropertyIdentity?)null, + configurationSource) ?? newRelationshipBuilder; } newRelationshipBuilder = newRelationshipBuilder.RelatedEntityTypes( - principalEntityTypeBuilder.Metadata, - dependentEntityTypeBuilder.Metadata, - principalEndConfigurationSource, - configurationSource) + principalEntityTypeBuilder.Metadata, + dependentEntityTypeBuilder.Metadata, + principalEndConfigurationSource, + configurationSource) ?? newRelationshipBuilder; if (dependentProperties?.Count > 0 @@ -2004,8 +2001,8 @@ private bool CanInvert(ConfigurationSource? configurationSource) if (foreignKeyPropertiesConfigurationSource.HasValue) { newRelationshipBuilder = newRelationshipBuilder.HasForeignKey( - dependentProperties, - foreignKeyPropertiesConfigurationSource.Value) + dependentProperties, + foreignKeyPropertiesConfigurationSource.Value) ?? newRelationshipBuilder; } } @@ -2023,8 +2020,8 @@ private bool CanInvert(ConfigurationSource? configurationSource) if (principalKeyConfigurationSource.HasValue) { newRelationshipBuilder = newRelationshipBuilder.HasPrincipalKey( - principalProperties, - principalKeyConfigurationSource.Value) + principalProperties, + principalKeyConfigurationSource.Value) ?? newRelationshipBuilder; } } @@ -2040,8 +2037,8 @@ private bool CanInvert(ConfigurationSource? configurationSource) if (isUniqueConfigurationSource.HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsUnique( - isUnique.Value, - isUniqueConfigurationSource.Value) + isUnique.Value, + isUniqueConfigurationSource.Value) ?? newRelationshipBuilder; } } @@ -2057,8 +2054,8 @@ private bool CanInvert(ConfigurationSource? configurationSource) if (isRequiredConfigurationSource.HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsRequired( - isRequired.Value, - isRequiredConfigurationSource.Value) + isRequired.Value, + isRequiredConfigurationSource.Value) ?? newRelationshipBuilder; } } @@ -2074,8 +2071,8 @@ private bool CanInvert(ConfigurationSource? configurationSource) if (deleteBehaviorConfigurationSource.HasValue) { newRelationshipBuilder = newRelationshipBuilder.DeleteBehavior( - deleteBehavior.Value, - deleteBehaviorConfigurationSource.Value) + deleteBehavior.Value, + deleteBehaviorConfigurationSource.Value) ?? newRelationshipBuilder; } } @@ -2094,9 +2091,9 @@ private bool CanInvert(ConfigurationSource? configurationSource) if (navigationToPrincipalConfigurationSource.HasValue) { newRelationshipBuilder = newRelationshipBuilder.Navigations( - navigationToPrincipal, - null, - navigationToPrincipalConfigurationSource.Value) + navigationToPrincipal, + null, + navigationToPrincipalConfigurationSource.Value) ?? newRelationshipBuilder; var oldNavigation = oldRelationshipInverted ? Metadata.PrincipalToDependent @@ -2123,9 +2120,9 @@ private bool CanInvert(ConfigurationSource? configurationSource) if (navigationToDependentConfigurationSource.HasValue) { newRelationshipBuilder = newRelationshipBuilder.Navigations( - null, - navigationToDependent, - navigationToDependentConfigurationSource.Value) + null, + navigationToDependent, + navigationToDependentConfigurationSource.Value) ?? newRelationshipBuilder; var oldNavigation = oldRelationshipInverted ? Metadata.DependentToPrincipal @@ -2149,8 +2146,8 @@ private bool CanInvert(ConfigurationSource? configurationSource) if (isOwnershipConfigurationSource.HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsOwnership( - isOwnership.Value, - isOwnershipConfigurationSource.Value) + isOwnership.Value, + isOwnershipConfigurationSource.Value) ?? newRelationshipBuilder; } } @@ -2158,8 +2155,8 @@ private bool CanInvert(ConfigurationSource? configurationSource) && Metadata.GetIsOwnershipConfigurationSource().HasValue) { newRelationshipBuilder = newRelationshipBuilder.IsOwnership( - Metadata.IsOwnership, - Metadata.GetIsOwnershipConfigurationSource().Value) + Metadata.IsOwnership, + Metadata.GetIsOwnershipConfigurationSource().Value) ?? newRelationshipBuilder; } @@ -2388,9 +2385,9 @@ private bool CanInvert(ConfigurationSource? configurationSource) } var candidates = unresolvableRelationships.Concat( - resolvableRelationships.Where(r => r.Item2).Concat( - resolvableRelationships.Where(r => !r.Item2 && !r.Item1.Metadata.GetConfigurationSource().Overrides(configurationSource))) - .Select(r => r.Item1)) + resolvableRelationships.Where(r => r.Item2).Concat( + resolvableRelationships.Where(r => !r.Item2 && !r.Item1.Metadata.GetConfigurationSource().Overrides(configurationSource))) + .Select(r => r.Item1)) .ToList(); InternalRelationshipBuilder newRelationshipBuilder = null; foreach (var candidateRelationship in candidates) diff --git a/src/EFCore/Metadata/Internal/MemberClassifier.cs b/src/EFCore/Metadata/Internal/MemberClassifier.cs index 46ed9bcf665..9bd4926d587 100644 --- a/src/EFCore/Metadata/Internal/MemberClassifier.cs +++ b/src/EFCore/Metadata/Internal/MemberClassifier.cs @@ -52,11 +52,11 @@ public virtual Type FindCandidateNavigationPropertyType(PropertyInfo propertyInf targetType = targetType.UnwrapNullableType(); return targetType.GetTypeInfo().IsInterface - || targetType.GetTypeInfo().IsValueType - || targetType == typeof(object) - || _parameterBindingFactories.FindFactory(propertyInfo.PropertyType, propertyInfo.GetSimpleMemberName()) != null - || _typeMappingSource.FindMapping(targetType) != null - || targetType.GetTypeInfo().IsArray + || targetType.GetTypeInfo().IsValueType + || targetType == typeof(object) + || _parameterBindingFactories.FindFactory(propertyInfo.PropertyType, propertyInfo.GetSimpleMemberName()) != null + || _typeMappingSource.FindMapping(targetType) != null + || targetType.GetTypeInfo().IsArray ? null : targetType; } diff --git a/src/EFCore/Metadata/Internal/Model.cs b/src/EFCore/Metadata/Internal/Model.cs index 278de5a08e6..ad65b3382c2 100644 --- a/src/EFCore/Metadata/Internal/Model.cs +++ b/src/EFCore/Metadata/Internal/Model.cs @@ -204,6 +204,7 @@ private EntityType AddEntityType(EntityType entityType) { throw new InvalidOperationException(CoreStrings.DuplicateQueryType(entityType.DisplayName())); } + throw new InvalidOperationException(CoreStrings.CannotAccessQueryAsEntity(entityType.DisplayName())); } @@ -211,6 +212,7 @@ private EntityType AddEntityType(EntityType entityType) { throw new InvalidOperationException(CoreStrings.CannotAccessEntityAsQuery(entityType.DisplayName())); } + throw new InvalidOperationException(CoreStrings.DuplicateEntityType(entityType.DisplayName())); } @@ -482,9 +484,9 @@ private bool EntityTypeShouldHaveDefiningNavigation(in TypeIdentity type) return !_entityTypesWithDefiningNavigation.TryGetValue(name, out var entityTypesWithSameType) ? null : entityTypesWithSameType - .FirstOrDefault( - e => e.DefiningNavigationName == definingNavigationName - && e.DefiningEntityType.Name == definingEntityTypeName); + .FirstOrDefault( + e => e.DefiningNavigationName == definingNavigationName + && e.DefiningEntityType.Name == definingEntityTypeName); } /// diff --git a/src/EFCore/Metadata/Internal/Navigation.cs b/src/EFCore/Metadata/Internal/Navigation.cs index 8fb0554dd85..25e52f45ccb 100644 --- a/src/EFCore/Metadata/Internal/Navigation.cs +++ b/src/EFCore/Metadata/Internal/Navigation.cs @@ -225,26 +225,22 @@ public virtual IClrCollectionAccessor CollectionAccessor IForeignKey INavigation.ForeignKey { - [DebuggerStepThrough] - get => ForeignKey; + [DebuggerStepThrough] get => ForeignKey; } IMutableForeignKey IMutableNavigation.ForeignKey { - [DebuggerStepThrough] - get => ForeignKey; + [DebuggerStepThrough] get => ForeignKey; } IEntityType INavigation.DeclaringEntityType { - [DebuggerStepThrough] - get => DeclaringEntityType; + [DebuggerStepThrough] get => DeclaringEntityType; } IMutableEntityType IMutableNavigation.DeclaringEntityType { - [DebuggerStepThrough] - get => DeclaringEntityType; + [DebuggerStepThrough] get => DeclaringEntityType; } /// diff --git a/src/EFCore/Metadata/Internal/PropertiesSnapshot.cs b/src/EFCore/Metadata/Internal/PropertiesSnapshot.cs index 8fe6149644c..ad71da32e3a 100644 --- a/src/EFCore/Metadata/Internal/PropertiesSnapshot.cs +++ b/src/EFCore/Metadata/Internal/PropertiesSnapshot.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using JetBrains.Annotations; namespace Microsoft.EntityFrameworkCore.Metadata.Internal diff --git a/src/EFCore/Metadata/Internal/PropertyBase.cs b/src/EFCore/Metadata/Internal/PropertyBase.cs index 8e3d986b725..e237c5f68e6 100644 --- a/src/EFCore/Metadata/Internal/PropertyBase.cs +++ b/src/EFCore/Metadata/Internal/PropertyBase.cs @@ -18,7 +18,7 @@ public abstract class PropertyBase : ConventionalAnnotatable, IMutablePropertyBa { private FieldInfo _fieldInfo; private ConfigurationSource? _fieldInfoConfigurationSource; - private bool _isIndexedProperty; + private readonly bool _isIndexedProperty; // Warning: Never access these fields directly as access needs to be thread-safe private IClrPropertyGetter _getter; @@ -41,7 +41,7 @@ public abstract class PropertyBase : ConventionalAnnotatable, IMutablePropertyBa PropertyInfo = propertyInfo; _fieldInfo = fieldInfo; _isIndexedProperty = propertyInfo != null - && propertyInfo.IsEFIndexerProperty(); + && propertyInfo.IsEFIndexerProperty(); } /// diff --git a/src/EFCore/Metadata/Internal/PropertyBaseExtensions.cs b/src/EFCore/Metadata/Internal/PropertyBaseExtensions.cs index 2b9e652a988..55c0c9b469b 100644 --- a/src/EFCore/Metadata/Internal/PropertyBaseExtensions.cs +++ b/src/EFCore/Metadata/Internal/PropertyBaseExtensions.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; -using System.Transactions; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; @@ -175,8 +174,8 @@ public static IClrPropertySetter GetSetter([NotNull] this IPropertyBase property } errorMessage = hasGetter - ? CoreStrings.NoSetter(propertyBase.Name, propertyBase.DeclaringType.DisplayName(),nameof(PropertyAccessMode)) - : CoreStrings.NoProperty(fieldInfo?.Name,propertyBase.DeclaringType.DisplayName(),nameof(PropertyAccessMode)); + ? CoreStrings.NoSetter(propertyBase.Name, propertyBase.DeclaringType.DisplayName(), nameof(PropertyAccessMode)) + : CoreStrings.NoProperty(fieldInfo?.Name, propertyBase.DeclaringType.DisplayName(), nameof(PropertyAccessMode)); return false; } @@ -255,7 +254,7 @@ public static IClrPropertySetter GetSetter([NotNull] this IPropertyBase property errorMessage = hasGetter ? CoreStrings.NoSetter(propertyBase.Name, propertyBase.DeclaringType.DisplayName(), nameof(PropertyAccessMode)) - : CoreStrings.NoProperty(fieldInfo?.Name,propertyBase.DeclaringType.DisplayName(),nameof(PropertyAccessMode)); + : CoreStrings.NoProperty(fieldInfo?.Name, propertyBase.DeclaringType.DisplayName(), nameof(PropertyAccessMode)); return false; } @@ -324,7 +323,7 @@ public static IClrPropertySetter GetSetter([NotNull] this IPropertyBase property errorMessage = hasSetter ? CoreStrings.NoGetter(propertyBase.Name, propertyBase.DeclaringType.DisplayName(), nameof(PropertyAccessMode)) - : CoreStrings.NoProperty(fieldInfo?.Name,propertyBase.DeclaringType.DisplayName(),nameof(PropertyAccessMode)); + : CoreStrings.NoProperty(fieldInfo?.Name, propertyBase.DeclaringType.DisplayName(), nameof(PropertyAccessMode)); return false; } diff --git a/src/EFCore/Metadata/Internal/TypeBase.cs b/src/EFCore/Metadata/Internal/TypeBase.cs index a8fe7a79681..76088827b64 100644 --- a/src/EFCore/Metadata/Internal/TypeBase.cs +++ b/src/EFCore/Metadata/Internal/TypeBase.cs @@ -18,6 +18,7 @@ namespace Microsoft.EntityFrameworkCore.Metadata.Internal public abstract class TypeBase : ConventionalAnnotatable, IMutableTypeBase { private ConfigurationSource _configurationSource; + private readonly Dictionary _ignoredMembers = new Dictionary(StringComparer.Ordinal); diff --git a/src/EFCore/ModelBuilder.cs b/src/EFCore/ModelBuilder.cs index 5e0fc5f0ccc..0cc441e24be 100644 --- a/src/EFCore/ModelBuilder.cs +++ b/src/EFCore/ModelBuilder.cs @@ -335,7 +335,8 @@ public virtual ModelBuilder ApplyConfiguration([NotNull] IQueryTypeConfi } /// - /// Applies configuration from all and instances that are defined in provided assembly. + /// Applies configuration from all and + /// instances that are defined in provided assembly. /// /// The assembly to scan. /// Optional predicate to filter types within the assembly. @@ -456,7 +457,7 @@ public virtual ModelBuilder UsePropertyAccessMode(PropertyAccessMode propertyAcc /// explicitly in cases where the automatic execution is not possible. /// /// - /// The finalized . + /// The finalized . /// public virtual IModel FinalizeModel() { diff --git a/src/EFCore/PropertyAccessMode.cs b/src/EFCore/PropertyAccessMode.cs index 34be57ff719..96b06b17651 100644 --- a/src/EFCore/PropertyAccessMode.cs +++ b/src/EFCore/PropertyAccessMode.cs @@ -13,8 +13,8 @@ namespace Microsoft.EntityFrameworkCore /// or backing field will be used when reading and writing to a property or field. /// /// - /// The default behavior is . Prior to EF Core 3.0, - /// the default behavior was . + /// The default behavior is . Prior to EF Core 3.0, + /// the default behavior was . /// /// public enum PropertyAccessMode diff --git a/src/EFCore/Query/EntityQueryModelVisitor.cs b/src/EFCore/Query/EntityQueryModelVisitor.cs index 4c3357e198f..7548e604ffe 100644 --- a/src/EFCore/Query/EntityQueryModelVisitor.cs +++ b/src/EFCore/Query/EntityQueryModelVisitor.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; @@ -644,11 +643,7 @@ var entityTrackingInfos .MakeGenericMethod(outputExpression.Type) .Invoke( null, - new object[] - { - entityTrackingInfos, - outputExpression - }))); + new object[] { entityTrackingInfos, outputExpression }))); } } @@ -1181,11 +1176,11 @@ var referencedQuerySource = subQueryModel?.MainFromClause.FromExpression.TryGetReferencedQuerySource(); return queryModel.BodyClauses.ElementAtOrDefault(index - 1) is GroupJoinClause groupJoinClause - && groupJoinClause == referencedQuerySource - && queryModel.CountQuerySourceReferences(groupJoinClause) == 1 - && subQueryModel.BodyClauses.Count == 0 - && subQueryModel.ResultOperators.Count == 1 - && subQueryModel.ResultOperators[0] is DefaultIfEmptyResultOperator + && groupJoinClause == referencedQuerySource + && queryModel.CountQuerySourceReferences(groupJoinClause) == 1 + && subQueryModel.BodyClauses.Count == 0 + && subQueryModel.ResultOperators.Count == 1 + && subQueryModel.ResultOperators[0] is DefaultIfEmptyResultOperator ? true : false; } @@ -1231,8 +1226,9 @@ var selector || !(selectClause.Selector is QuerySourceReferenceExpression)) && !queryModel.ResultOperators .Select(ro => ro.GetType()) - .Any(t => t == typeof(GroupResultOperator) - || t == typeof(AllResultOperator))) + .Any( + t => t == typeof(GroupResultOperator) + || t == typeof(AllResultOperator))) { var asyncSelector = selector; var taskLiftingExpressionVisitor = new TaskLiftingExpressionVisitor(); @@ -1465,10 +1461,10 @@ private static Expression ShiftMemberAccess(Expression targetExpression, Express && LinqOperatorProvider is AsyncLinqOperatorProvider asyncLinqOperatorProvider) { return Expression.Call( - asyncLinqOperatorProvider - .ToAsyncEnumerable - .MakeGenericMethod(elementType), - expression); + asyncLinqOperatorProvider + .ToAsyncEnumerable + .MakeGenericMethod(elementType), + expression); } } diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/AdditionalFromClauseOptimizingQueryModelVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/AdditionalFromClauseOptimizingQueryModelVisitor.cs index 13b274d9d3c..792de26ddf5 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/AdditionalFromClauseOptimizingQueryModelVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/AdditionalFromClauseOptimizingQueryModelVisitor.cs @@ -16,7 +16,7 @@ namespace Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal /// public class AdditionalFromClauseOptimizingQueryModelVisitor : QueryModelVisitorBase { - private QueryCompilationContext _queryCompilationContext; + private readonly QueryCompilationContext _queryCompilationContext; /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/ConditionalOptimizingExpressionVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/ConditionalOptimizingExpressionVisitor.cs index dda21b63668..7f41ee120bd 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/ConditionalOptimizingExpressionVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/ConditionalOptimizingExpressionVisitor.cs @@ -65,7 +65,7 @@ protected override Expression VisitConditional(ConditionalExpression conditional } return conditionalExpression.IsNullPropagationCandidate(out var testExpression, out var resultExpression) - && _nullCheckRewriteTester.CanRewriteNullCheck(testExpression, resultExpression) + && _nullCheckRewriteTester.CanRewriteNullCheck(testExpression, resultExpression) ? new NullConditionalExpression(testExpression, resultExpression) : base.VisitConditional(conditionalExpression); } diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/CorrelatedCollectionFindingExpressionVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/CorrelatedCollectionFindingExpressionVisitor.cs index 87c2e6cad80..6921f62c309 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/CorrelatedCollectionFindingExpressionVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/CorrelatedCollectionFindingExpressionVisitor.cs @@ -106,7 +106,8 @@ private void TryMarkSubQuery(SubQueryExpression expression) { var collectionNavigation = properties.OfType().SingleOrDefault(n => n.IsCollection()); - if (collectionNavigation != null && querySource != null) + if (collectionNavigation != null + && querySource != null) { _queryModelVisitor.QueryCompilationContext.RegisterCorrelatedSubqueryMetadata( subQueryModel.MainFromClause, diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/CorrelatedCollectionOptimizingVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/CorrelatedCollectionOptimizingVisitor.cs index 34c38f05c60..da63c4413e3 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/CorrelatedCollectionOptimizingVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/CorrelatedCollectionOptimizingVisitor.cs @@ -245,9 +245,15 @@ var collectionQuerySourceReferenceExpression foreach (var existingClonedOrdering in exisitingClonedOrderByClause.Orderings) { var matchingIndex = subQueryProjection - .Select((o, i) => new { o, i }) - .Where(e => ExpressionEqualityComparer.Instance.Equals(e.o, existingClonedOrdering.Expression) - || AreEquivalentPropertyExpressions(e.o, existingClonedOrdering.Expression)).Select(e => (int?)e.i).FirstOrDefault(); + .Select( + (o, i) => new + { + o, + i + }) + .Where( + e => ExpressionEqualityComparer.Instance.Equals(e.o, existingClonedOrdering.Expression) + || AreEquivalentPropertyExpressions(e.o, existingClonedOrdering.Expression)).Select(e => (int?)e.i).FirstOrDefault(); if (matchingIndex == null) { @@ -578,12 +584,12 @@ private static bool AreEquivalentPropertyExpressions(Expression expression1, Exp propertyName2 = memberExpression2.Member.Name; } - return qsre1!= null - && qsre2 != null - && propertyName1 != null - && propertyName2 != null - && qsre1.ReferencedQuerySource == qsre2.ReferencedQuerySource - && propertyName1 == propertyName2; + return qsre1 != null + && qsre2 != null + && propertyName1 != null + && propertyName2 != null + && qsre1.ReferencedQuerySource == qsre2.ReferencedQuerySource + && propertyName1 == propertyName2; } private static bool ProcessResultOperators(QueryModel queryModel) diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/EntityEqualityRewritingExpressionVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/EntityEqualityRewritingExpressionVisitor.cs index 8793bfe120a..81278fefa26 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/EntityEqualityRewritingExpressionVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/EntityEqualityRewritingExpressionVisitor.cs @@ -228,7 +228,7 @@ var nullConstantExpression private bool IsInvalidSubQueryExpression(Expression expression) => expression is SubQueryExpression subQuery - && _queryCompilationContext.DuplicateQueryModels.Contains(subQuery.QueryModel); + && _queryCompilationContext.DuplicateQueryModels.Contains(subQuery.QueryModel); private Expression RewriteEntityEquality(ExpressionType nodeType, Expression left, Expression right) { @@ -281,8 +281,8 @@ private Expression RewriteEntityEquality(ExpressionType nodeType, Expression lef // Skipping composite key with subquery since it requires to copy subquery // which would cause same subquery to be visited twice return keyProperties.Count > 1 - && (left.RemoveConvert() is SubQueryExpression - || right.RemoveConvert() is SubQueryExpression) + && (left.RemoveConvert() is SubQueryExpression + || right.RemoveConvert() is SubQueryExpression) ? null : Expression.MakeBinary( nodeType, @@ -310,10 +310,10 @@ private Expression RewriteEntityEquality(ExpressionType nodeType, Expression lef private static Expression UnwrapLastNavigation(Expression expression) => (expression as MemberExpression)?.Expression - ?? (expression is MethodCallExpression methodCallExpression - && methodCallExpression.Method.IsEFPropertyMethod() - ? methodCallExpression.Arguments[0] - : null); + ?? (expression is MethodCallExpression methodCallExpression + && methodCallExpression.Method.IsEFPropertyMethod() + ? methodCallExpression.Arguments[0] + : null); private static Expression CreateKeyAccessExpression( Expression target, diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/MemberAccessBindingExpressionVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/MemberAccessBindingExpressionVisitor.cs index 4a966e2d78b..9bc9b1601b2 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/MemberAccessBindingExpressionVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/MemberAccessBindingExpressionVisitor.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; @@ -129,7 +128,7 @@ protected override Expression VisitUnary(UnaryExpression node) { var newOperand = Visit(node.Operand); return node.NodeType == ExpressionType.Convert - && newOperand?.Type == typeof(ValueBuffer) + && newOperand?.Type == typeof(ValueBuffer) ? newOperand : node.Update(newOperand); } @@ -335,7 +334,7 @@ var newArguments querySource = querySource ?? newExpression.Arguments.FirstOrDefault(); return newExpression != methodCallExpression - && querySource?.Type == typeof(ValueBuffer) + && querySource?.Type == typeof(ValueBuffer) ? _queryModelVisitor.BindMethodCallToValueBuffer(methodCallExpression, querySource) ?? newExpression : _queryModelVisitor.BindMethodCallToEntity(methodCallExpression, newExpression) ?? newExpression; } diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/ModelExpressionApplyingExpressionVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/ModelExpressionApplyingExpressionVisitor.cs index 93eeb72b433..a84d7ad6c2f 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/ModelExpressionApplyingExpressionVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/ModelExpressionApplyingExpressionVisitor.cs @@ -130,8 +130,8 @@ var parameterizedQuery && entityType.QueryFilter != null) { var parameterizedFilter - = (LambdaExpression)_parameterExtractingExpressionVisitor - .ExtractParameters(entityType.QueryFilter); + = (LambdaExpression)_parameterExtractingExpressionVisitor + .ExtractParameters(entityType.QueryFilter); var oldParameterExpression = parameterizedFilter.Parameters[0]; var newParameterExpression = Expression.Parameter(type, oldParameterExpression.Name); diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/NavigationRewritingExpressionVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/NavigationRewritingExpressionVisitor.cs index 3a6d92abc48..09ce999a0c4 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/NavigationRewritingExpressionVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/NavigationRewritingExpressionVisitor.cs @@ -1033,7 +1033,7 @@ var optionalNavigationInChain if (!ShouldRewrite(navigation)) { - if(sourceExpression.Type != navigation.DeclaringEntityType.ClrType) + if (sourceExpression.Type != navigation.DeclaringEntityType.ClrType) { sourceExpression = Expression.Condition( Expression.TypeIs(sourceExpression, navigation.DeclaringEntityType.ClrType), @@ -1081,9 +1081,10 @@ var innerQuerySourceReferenceExpression var navigationJoin = navigationJoins - .FirstOrDefault(nj => - nj.QuerySource == (sourceExpression as QuerySourceReferenceExpression ?? sourceQsre).ReferencedQuerySource - && nj.Navigation == navigation); + .FirstOrDefault( + nj => + nj.QuerySource == (sourceExpression as QuerySourceReferenceExpression ?? sourceQsre).ReferencedQuerySource + && nj.Navigation == navigation); if (navigationJoin == null) { @@ -1132,8 +1133,8 @@ var navigationJoin return propertyType == null ? sourceExpression : optionalNavigationInChain - ? conditionalAccessPropertyCreator(sourceExpression) - : propertyCreator(sourceExpression); + ? conditionalAccessPropertyCreator(sourceExpression) + : propertyCreator(sourceExpression); } private void RewriteNavigationIntoGroupJoin( diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/ParameterExtractingExpressionVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/ParameterExtractingExpressionVisitor.cs index 1145c18f9c6..919772a0a47 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/ParameterExtractingExpressionVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/ParameterExtractingExpressionVisitor.cs @@ -144,9 +144,9 @@ private Expression TryGetConstantValue(Expression expression) private static bool ShortCircuitBinaryExpression(Expression expression, ExpressionType nodeType) => expression is ConstantExpression constantExpression - && constantExpression.Value is bool constantValue - && ((constantValue && nodeType == ExpressionType.OrElse) - || (!constantValue && nodeType == ExpressionType.AndAlso)); + && constantExpression.Value is bool constantValue + && ((constantValue && nodeType == ExpressionType.OrElse) + || (!constantValue && nodeType == ExpressionType.AndAlso)); protected override Expression VisitConstant(ConstantExpression constantExpression) { @@ -158,7 +158,7 @@ protected override Expression VisitConstant(ConstantExpression constantExpressio _currentQueryProvider = queryProvider; } else if (!ReferenceEquals(queryProvider, _currentQueryProvider) - && queryProvider.GetType() == _currentQueryProvider.GetType()) + && queryProvider.GetType() == _currentQueryProvider.GetType()) { throw new InvalidOperationException(CoreStrings.ErrorInvalidQueryable); } @@ -229,9 +229,9 @@ var compilerPrefixIndex parameterName = CompiledQueryCache.CompiledQueryParameterPrefix - + parameterName - + "_" - + _parameterValues.ParameterValues.Count; + + parameterName + + "_" + + _parameterValues.ParameterValues.Count; _parameterValues.AddParameter(parameterName, parameterValue); @@ -314,6 +314,7 @@ private object GetValue(Expression expression, out string parameterName) { // Try again when we compile the delegate } + break; case ConstantExpression constantExpression: @@ -324,9 +325,9 @@ private object GetValue(Expression expression, out string parameterName) break; case UnaryExpression unaryExpression - when (unaryExpression.NodeType == ExpressionType.Convert - || unaryExpression.NodeType == ExpressionType.ConvertChecked) - && (unaryExpression.Type.UnwrapNullableType() == unaryExpression.Operand.Type): + when (unaryExpression.NodeType == ExpressionType.Convert + || unaryExpression.NodeType == ExpressionType.ConvertChecked) + && (unaryExpression.Type.UnwrapNullableType() == unaryExpression.Operand.Type): return GetValue(unaryExpression.Operand, out parameterName); } @@ -386,8 +387,8 @@ public override Expression Visit(Expression expression) var parentContainsClosure = _containsClosure; _evaluatable = IsEvalutableNodeType(expression) - // Extension point to disable funcletization - && _evaluatableExpressionFilter.IsEvaluatableExpression(expression); + // Extension point to disable funcletization + && _evaluatableExpressionFilter.IsEvaluatableExpression(expression); _containsClosure = false; base.Visit(expression); @@ -503,10 +504,10 @@ protected override Expression VisitParameter(ParameterExpression parameterExpres protected override Expression VisitConstant(ConstantExpression constantExpression) { _evaluatable = !(constantExpression.Value is IDetachableContext) - && !(constantExpression.Value is IQueryable); + && !(constantExpression.Value is IQueryable); #pragma warning disable RCS1096 // Use bitwise operation instead of calling 'HasFlag'. _containsClosure = constantExpression.Type.Attributes.HasFlag(TypeAttributes.NestedPrivate) // Closure - || constantExpression.Type == typeof(ValueBuffer); // Find method + || constantExpression.Type == typeof(ValueBuffer); // Find method #pragma warning restore RCS1096 // Use bitwise operation instead of calling 'HasFlag'. return base.VisitConstant(constantExpression); diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/SubQueryMemberPushDownExpressionVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/SubQueryMemberPushDownExpressionVisitor.cs index a21c11eb102..c6e665eaffd 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/SubQueryMemberPushDownExpressionVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/SubQueryMemberPushDownExpressionVisitor.cs @@ -152,11 +152,7 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp = methodCallExpression .Update( null, - new[] - { - clonedSubSelector, - methodCallExpression.Arguments[1] - }); + new[] { clonedSubSelector, methodCallExpression.Arguments[1] }); subQueryModel.ResultTypeOverride = subQueryModel.SelectClause.Selector.Type; @@ -179,10 +175,10 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression) { var newOperand = Visit(unaryExpression.Operand); return newOperand is UnaryExpression innerUnaryExpression - && (innerUnaryExpression.NodeType == ExpressionType.Convert - || innerUnaryExpression.NodeType == ExpressionType.ConvertChecked) - && innerUnaryExpression.Operand.Type == unaryExpression.Type - && innerUnaryExpression.Operand.Type != typeof(object) + && (innerUnaryExpression.NodeType == ExpressionType.Convert + || innerUnaryExpression.NodeType == ExpressionType.ConvertChecked) + && innerUnaryExpression.Operand.Type == unaryExpression.Type + && innerUnaryExpression.Operand.Type != typeof(object) ? innerUnaryExpression.Operand : unaryExpression.Update(newOperand); } diff --git a/src/EFCore/Query/ExpressionVisitors/Internal/TaskLiftingExpressionVisitor.cs b/src/EFCore/Query/ExpressionVisitors/Internal/TaskLiftingExpressionVisitor.cs index 1e235c00629..b126f419980 100644 --- a/src/EFCore/Query/ExpressionVisitors/Internal/TaskLiftingExpressionVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/Internal/TaskLiftingExpressionVisitor.cs @@ -169,10 +169,10 @@ protected override Expression VisitMethodCall(MethodCallExpression methodCallExp methodCallExpression.Arguments[0]))); return Expression.Convert( - Expression.ArrayAccess( - _resultsParameter, - Expression.Constant(_taskExpressions.Count - 1)), - methodCallExpression.Method.ReturnType); + Expression.ArrayAccess( + _resultsParameter, + Expression.Constant(_taskExpressions.Count - 1)), + methodCallExpression.Method.ReturnType); } return base.VisitMethodCall(methodCallExpression); diff --git a/src/EFCore/Query/ExpressionVisitors/ProjectionExpressionVisitor.cs b/src/EFCore/Query/ExpressionVisitors/ProjectionExpressionVisitor.cs index 1f95b1a741b..379c2e3656a 100644 --- a/src/EFCore/Query/ExpressionVisitors/ProjectionExpressionVisitor.cs +++ b/src/EFCore/Query/ExpressionVisitors/ProjectionExpressionVisitor.cs @@ -89,20 +89,20 @@ when materializeCollectionNavigationMethodCallExpression.Method // We call .Result here so that the types still line up (we remove the .Result in TaskLiftingExpressionVisitor). return toQueryableMethodCallExpression.Arguments[0].Type.IsGenericType - && toQueryableMethodCallExpression.Arguments[0].Type.GetGenericTypeDefinition() == typeof(IAsyncEnumerable<>) - ? (Expression)Expression.Property( - ResultOperatorHandler.CallWithPossibleCancellationToken( - _materializeCollectionNavigationAsyncMethodInfo - .MakeGenericMethod( - materializeCollectionNavigationMethodCallExpression.Method - .GetGenericArguments()[0]), - materializeCollectionNavigationMethodCallExpression.Arguments[0], - toQueryableMethodCallExpression.Arguments[0]), - nameof(Task.Result)) - : Expression.Call( - materializeCollectionNavigationMethodCallExpression.Method, + && toQueryableMethodCallExpression.Arguments[0].Type.GetGenericTypeDefinition() == typeof(IAsyncEnumerable<>) + ? (Expression)Expression.Property( + ResultOperatorHandler.CallWithPossibleCancellationToken( + _materializeCollectionNavigationAsyncMethodInfo + .MakeGenericMethod( + materializeCollectionNavigationMethodCallExpression.Method + .GetGenericArguments()[0]), materializeCollectionNavigationMethodCallExpression.Arguments[0], - toQueryableMethodCallExpression.Arguments[0]); + toQueryableMethodCallExpression.Arguments[0]), + nameof(Task.Result)) + : Expression.Call( + materializeCollectionNavigationMethodCallExpression.Method, + materializeCollectionNavigationMethodCallExpression.Arguments[0], + toQueryableMethodCallExpression.Arguments[0]); } case MethodCallExpression newMethodCallExpression when newMethodCallExpression.Method.Equals(methodCallExpression.Method) @@ -232,7 +232,7 @@ protected override Expression VisitSubQuery(SubQueryExpression expression) return subExpression; } - /// Visits the children of the . + /// Visits the children of the . /// The expression to visit. /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. protected override Expression VisitUnary(UnaryExpression unaryExpression) diff --git a/src/EFCore/Query/Expressions/Internal/NullConditionalExpression.cs b/src/EFCore/Query/Expressions/Internal/NullConditionalExpression.cs index ceb8c94bfdc..d1efa6ea541 100644 --- a/src/EFCore/Query/Expressions/Internal/NullConditionalExpression.cs +++ b/src/EFCore/Query/Expressions/Internal/NullConditionalExpression.cs @@ -91,13 +91,13 @@ var operation } return Block( - new[] { nullableCaller, result }, - Assign(nullableCaller, Caller), - Assign(result, Default(_type)), - IfThen( - NotEqual(nullableCaller, Default(nullableCallerType)), - Assign(result, operation)), - result); + new[] { nullableCaller, result }, + Assign(nullableCaller, Caller), + Assign(result, Default(_type)), + IfThen( + NotEqual(nullableCaller, Default(nullableCallerType)), + Assign(result, operation)), + result); } /// @@ -115,8 +115,8 @@ protected override Expression VisitChildren(ExpressionVisitor visitor) var newAccessOperation = visitor.Visit(AccessOperation); return newCaller != Caller - || newAccessOperation != AccessOperation - && !(ExpressionEqualityComparer.Instance.Equals((newAccessOperation as NullConditionalExpression)?.AccessOperation, AccessOperation)) + || newAccessOperation != AccessOperation + && !(ExpressionEqualityComparer.Instance.Equals((newAccessOperation as NullConditionalExpression)?.AccessOperation, AccessOperation)) ? new NullConditionalExpression(newCaller, newAccessOperation) : (this); } diff --git a/src/EFCore/Query/Internal/AnonymousObject.cs b/src/EFCore/Query/Internal/AnonymousObject.cs index d876fe098f9..7453f7337cb 100644 --- a/src/EFCore/Query/Internal/AnonymousObject.cs +++ b/src/EFCore/Query/Internal/AnonymousObject.cs @@ -84,7 +84,7 @@ public override bool Equals(object obj) return obj is null ? false : obj is AnonymousObject anonymousObject - && _values.SequenceEqual(anonymousObject._values); + && _values.SequenceEqual(anonymousObject._values); } /// diff --git a/src/EFCore/Query/Internal/CompiledQueryCache.cs b/src/EFCore/Query/Internal/CompiledQueryCache.cs index 921dac69806..d9445f6a2ce 100644 --- a/src/EFCore/Query/Internal/CompiledQueryCache.cs +++ b/src/EFCore/Query/Internal/CompiledQueryCache.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Concurrent; -using System.Collections.Generic; using JetBrains.Annotations; using Microsoft.Extensions.Caching.Memory; diff --git a/src/EFCore/Query/Internal/EntityQueryProvider.cs b/src/EFCore/Query/Internal/EntityQueryProvider.cs index 93194a44946..8fd60ffb91d 100644 --- a/src/EFCore/Query/Internal/EntityQueryProvider.cs +++ b/src/EFCore/Query/Internal/EntityQueryProvider.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; diff --git a/src/EFCore/Query/Internal/EntityQueryable`.cs b/src/EFCore/Query/Internal/EntityQueryable`.cs index c1cfc28b347..f5e619cc1a5 100644 --- a/src/EFCore/Query/Internal/EntityQueryable`.cs +++ b/src/EFCore/Query/Internal/EntityQueryable`.cs @@ -19,9 +19,9 @@ namespace Microsoft.EntityFrameworkCore.Query.Internal /// public class EntityQueryable : IOrderedQueryable, - IAsyncEnumerable, - IDetachableContext, - IListSource + IAsyncEnumerable, + IDetachableContext, + IListSource { private static readonly EntityQueryable _detached = new EntityQueryable(NullAsyncQueryProvider.Instance); diff --git a/src/EFCore/Query/Internal/EvaluatableExpressionFilter.cs b/src/EFCore/Query/Internal/EvaluatableExpressionFilter.cs index 4ece1db6493..1ad2e685c20 100644 --- a/src/EFCore/Query/Internal/EvaluatableExpressionFilter.cs +++ b/src/EFCore/Query/Internal/EvaluatableExpressionFilter.cs @@ -7,7 +7,6 @@ namespace Microsoft.EntityFrameworkCore.Query.Internal { - public class EvaluatableExpressionFilter : EvaluatableExpressionFilterBase { // This methods are non-deterministic and result varies based on time of running the query. @@ -54,6 +53,7 @@ public override bool IsEvaluatableExpression(Expression expression) { return false; } + break; case MethodCallExpression methodCallExpression: @@ -66,6 +66,7 @@ public override bool IsEvaluatableExpression(Expression expression) { return false; } + break; } diff --git a/src/EFCore/Query/Internal/ExpressionEqualityComparer.cs b/src/EFCore/Query/Internal/ExpressionEqualityComparer.cs index 8959df8044f..d857971814b 100644 --- a/src/EFCore/Query/Internal/ExpressionEqualityComparer.cs +++ b/src/EFCore/Query/Internal/ExpressionEqualityComparer.cs @@ -317,7 +317,8 @@ private int GetHashCode(IList expressions) /// public virtual bool SequenceEquals(IEnumerable x, IEnumerable y) { - if (x == null || y == null) + if (x == null + || y == null) { return false; } @@ -469,8 +470,8 @@ private static bool CompareConstant(ConstantExpression a, ConstantExpression b) } return a.IsEntityQueryable() - && b.IsEntityQueryable() - && a.Value.GetType() == b.Value.GetType() + && b.IsEntityQueryable() + && a.Value.GetType() == b.Value.GetType() ? true : Equals(a.Value, b.Value); } diff --git a/src/EFCore/Query/Internal/IAsyncQueryProvider.cs b/src/EFCore/Query/Internal/IAsyncQueryProvider.cs index 4e14e0d4b01..7d8dde79584 100644 --- a/src/EFCore/Query/Internal/IAsyncQueryProvider.cs +++ b/src/EFCore/Query/Internal/IAsyncQueryProvider.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; diff --git a/src/EFCore/Query/Internal/ICompiledQueryCache.cs b/src/EFCore/Query/Internal/ICompiledQueryCache.cs index d9253a175fe..7bb16353560 100644 --- a/src/EFCore/Query/Internal/ICompiledQueryCache.cs +++ b/src/EFCore/Query/Internal/ICompiledQueryCache.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections.Generic; using JetBrains.Annotations; namespace Microsoft.EntityFrameworkCore.Query.Internal diff --git a/src/EFCore/Query/Internal/IQueryCompiler.cs b/src/EFCore/Query/Internal/IQueryCompiler.cs index 03d7cc80635..79ef20eaa1b 100644 --- a/src/EFCore/Query/Internal/IQueryCompiler.cs +++ b/src/EFCore/Query/Internal/IQueryCompiler.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; diff --git a/src/EFCore/Query/Internal/IQueryModelGenerator.cs b/src/EFCore/Query/Internal/IQueryModelGenerator.cs index 1f916a8d729..fdc152c56d7 100644 --- a/src/EFCore/Query/Internal/IQueryModelGenerator.cs +++ b/src/EFCore/Query/Internal/IQueryModelGenerator.cs @@ -3,7 +3,6 @@ using System.Linq.Expressions; using JetBrains.Annotations; -using Microsoft.EntityFrameworkCore.Diagnostics; using Remotion.Linq; namespace Microsoft.EntityFrameworkCore.Query.Internal diff --git a/src/EFCore/Query/Internal/IncludeCompiler.IncludeLoadTreeNode.cs b/src/EFCore/Query/Internal/IncludeCompiler.IncludeLoadTreeNode.cs index 89418dc7722..bb7b69977f8 100644 --- a/src/EFCore/Query/Internal/IncludeCompiler.IncludeLoadTreeNode.cs +++ b/src/EFCore/Query/Internal/IncludeCompiler.IncludeLoadTreeNode.cs @@ -414,7 +414,7 @@ var stateManagerProperty { blockExpressions.Add( collection - ? (Expression)Expression.Call( + ? Expression.Call( Expression.Constant(inverseNavigation.GetCollectionAccessor()), _collectionAccessorAddMethodInfo, relatedArrayAccessExpression, diff --git a/src/EFCore/Query/Internal/MaterializedAnonymousObject.cs b/src/EFCore/Query/Internal/MaterializedAnonymousObject.cs index 0bda6a099a0..a9ffbcce91d 100644 --- a/src/EFCore/Query/Internal/MaterializedAnonymousObject.cs +++ b/src/EFCore/Query/Internal/MaterializedAnonymousObject.cs @@ -90,7 +90,7 @@ public override bool Equals(object obj) return obj is null ? false : obj is MaterializedAnonymousObject anonymousObject - && _values.SequenceEqual(anonymousObject._values); + && _values.SequenceEqual(anonymousObject._values); } /// diff --git a/src/EFCore/Query/Internal/MethodInfoBasedNodeTypeRegistryFactory.cs b/src/EFCore/Query/Internal/MethodInfoBasedNodeTypeRegistryFactory.cs index 9618abf8c50..97adc5490be 100644 --- a/src/EFCore/Query/Internal/MethodInfoBasedNodeTypeRegistryFactory.cs +++ b/src/EFCore/Query/Internal/MethodInfoBasedNodeTypeRegistryFactory.cs @@ -19,6 +19,7 @@ namespace Microsoft.EntityFrameworkCore.Query.Internal public class MethodInfoBasedNodeTypeRegistryFactory : INodeTypeProviderFactory { private static readonly object _syncLock = new object(); + private static readonly MethodNameBasedNodeTypeRegistry _methodNameBasedNodeTypeRegistry = MethodNameBasedNodeTypeRegistry.CreateFromRelinqAssembly(); @@ -50,11 +51,7 @@ public class MethodInfoBasedNodeTypeRegistryFactory : INodeTypeProviderFactory _methodInfoBasedNodeTypeRegistry .Register(ThenIncludeExpressionNode.SupportedMethods, typeof(ThenIncludeExpressionNode)); - _nodeTypeProviders = new INodeTypeProvider[] - { - _methodInfoBasedNodeTypeRegistry, - _methodNameBasedNodeTypeRegistry - }; + _nodeTypeProviders = new INodeTypeProvider[] { _methodInfoBasedNodeTypeRegistry, _methodNameBasedNodeTypeRegistry }; } /// @@ -70,11 +67,7 @@ public virtual void RegisterMethods(IEnumerable methods, Type nodeTy lock (_syncLock) { _methodInfoBasedNodeTypeRegistry.Register(methods, nodeType); - _nodeTypeProviders = new INodeTypeProvider[] - { - _methodInfoBasedNodeTypeRegistry, - _methodNameBasedNodeTypeRegistry - }; + _nodeTypeProviders = new INodeTypeProvider[] { _methodInfoBasedNodeTypeRegistry, _methodNameBasedNodeTypeRegistry }; } } diff --git a/src/EFCore/Query/Internal/NullAsyncQueryProvider.cs b/src/EFCore/Query/Internal/NullAsyncQueryProvider.cs index 741e9588faf..070e50d8b36 100644 --- a/src/EFCore/Query/Internal/NullAsyncQueryProvider.cs +++ b/src/EFCore/Query/Internal/NullAsyncQueryProvider.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; diff --git a/src/EFCore/Query/Internal/QueryCompiler.cs b/src/EFCore/Query/Internal/QueryCompiler.cs index dd7d1236371..06e7256376b 100644 --- a/src/EFCore/Query/Internal/QueryCompiler.cs +++ b/src/EFCore/Query/Internal/QueryCompiler.cs @@ -276,8 +276,8 @@ var resultItemType try { return (Func)CompileAsyncQueryMethod - .MakeGenericMethod(resultItemType) - .Invoke(database, new object[] { queryModel }); + .MakeGenericMethod(resultItemType) + .Invoke(database, new object[] { queryModel }); } catch (TargetInvocationException e) { diff --git a/src/EFCore/Query/Internal/QueryModelGenerator.cs b/src/EFCore/Query/Internal/QueryModelGenerator.cs index c3c7243f853..3abeafa844b 100644 --- a/src/EFCore/Query/Internal/QueryModelGenerator.cs +++ b/src/EFCore/Query/Internal/QueryModelGenerator.cs @@ -58,10 +58,6 @@ private QueryParser CreateQueryParser(INodeTypeProvider nodeTypeProvider) new ExpressionTreeParser( nodeTypeProvider, new CompoundExpressionTreeProcessor( - new IExpressionTreeProcessor[] - { - new PartialEvaluatingExpressionTreeProcessor(_reLinqEvaluatableExpressionFilter), - new TransformingExpressionTreeProcessor(ExpressionTransformerRegistry.CreateDefault()) - }))); + new IExpressionTreeProcessor[] { new PartialEvaluatingExpressionTreeProcessor(_reLinqEvaluatableExpressionFilter), new TransformingExpressionTreeProcessor(ExpressionTransformerRegistry.CreateDefault()) }))); } } diff --git a/src/EFCore/Query/Internal/QueryOptimizer.cs b/src/EFCore/Query/Internal/QueryOptimizer.cs index 1c3c3a12f07..f97ebdfa36b 100644 --- a/src/EFCore/Query/Internal/QueryOptimizer.cs +++ b/src/EFCore/Query/Internal/QueryOptimizer.cs @@ -225,7 +225,7 @@ var subqueryInMainClauseWithoutResultOperatorsProjectingItsMainClause var isGeneratedNameOuter = fromClause.HasGeneratedItemName(); var itemName = innerMainFromClause.HasGeneratedItemName() - && !isGeneratedNameOuter + && !isGeneratedNameOuter ? fromClause.ItemName : innerMainFromClause.ItemName; @@ -297,7 +297,7 @@ public override void VisitResultOperator(ResultOperatorBase resultOperator, Quer else { var entityType = _queryCompilationContext.Model.FindEntityType(searchedItemType) - ?? _queryCompilationContext.FindEntityType(queryModel.MainFromClause); + ?? _queryCompilationContext.FindEntityType(queryModel.MainFromClause); if (entityType != null) { @@ -412,6 +412,7 @@ private void UpdateQueryAnnotations(QueryModel queryModel, QuerySourceMapping qu { _queryCompilationContext.AddOrUpdateMapping(newQuerySource, entityType); } + foreach (var queryAnnotation in _queryCompilationContext.QueryAnnotations.Where(qa => qa.QuerySource == oldQuerySource)) { queryAnnotation.QuerySource = newQuerySource; diff --git a/src/EFCore/Query/Internal/ReLinqEvaluatableExpressionFilter.cs b/src/EFCore/Query/Internal/ReLinqEvaluatableExpressionFilter.cs index 42dcae2add9..9cdcfc3952c 100644 --- a/src/EFCore/Query/Internal/ReLinqEvaluatableExpressionFilter.cs +++ b/src/EFCore/Query/Internal/ReLinqEvaluatableExpressionFilter.cs @@ -53,9 +53,9 @@ public override bool IsEvaluatableMethodCall(MethodCallExpression methodCallExpr var method = methodCallExpression.Method; return Equals(method, _guidNewGuid) - || Equals(method, _randomNextNoArgs) - || Equals(method, _randomNextOneArg) - || Equals(method, _randomNextTwoArgs) + || Equals(method, _randomNextNoArgs) + || Equals(method, _randomNextOneArg) + || Equals(method, _randomNextTwoArgs) ? false : base.IsEvaluatableMethodCall(methodCallExpression); } @@ -69,10 +69,10 @@ public override bool IsEvaluatableMember(MemberExpression memberExpression) var member = memberExpression.Member; return Equals(member, _dateTimeNow) - || Equals(member, _dateTimeUtcNow) - || Equals(member, _dateTimeToday) - || Equals(member, _dateTimeOffsetNow) - || Equals(member, _dateTimeOffsetUtcNow) + || Equals(member, _dateTimeUtcNow) + || Equals(member, _dateTimeToday) + || Equals(member, _dateTimeOffsetNow) + || Equals(member, _dateTimeOffsetUtcNow) ? false : base.IsEvaluatableMember(memberExpression); } diff --git a/src/EFCore/Query/Internal/WeakReferenceIdentityMap.cs b/src/EFCore/Query/Internal/WeakReferenceIdentityMap.cs index b5dabe64945..c9261383113 100644 --- a/src/EFCore/Query/Internal/WeakReferenceIdentityMap.cs +++ b/src/EFCore/Query/Internal/WeakReferenceIdentityMap.cs @@ -142,9 +142,9 @@ public IIncludeKeyComparer CreateIncludeKeyComparer(INavigation navigation, in V ? (IIncludeKeyComparer)new DependentToPrincipalIncludeComparer(keyValue, PrincipalKeyValueFactory) : new NullIncludeComparer() : new PrincipalToDependentIncludeComparer( - (TKey)PrincipalKeyValueFactory.CreateFromBuffer(valueBuffer), - navigation.ForeignKey.GetDependentKeyValueFactory(), - PrincipalKeyValueFactory); + (TKey)PrincipalKeyValueFactory.CreateFromBuffer(valueBuffer), + navigation.ForeignKey.GetDependentKeyValueFactory(), + PrincipalKeyValueFactory); } /// @@ -158,9 +158,9 @@ public IIncludeKeyComparer CreateIncludeKeyComparer(INavigation navigation, Inte ? new DependentToPrincipalIncludeComparer(keyValue, PrincipalKeyValueFactory) : (IIncludeKeyComparer)new NullIncludeComparer() : new PrincipalToDependentIncludeComparer( - PrincipalKeyValueFactory.CreateFromCurrentValues(entry), - navigation.ForeignKey.GetDependentKeyValueFactory(), - PrincipalKeyValueFactory); + PrincipalKeyValueFactory.CreateFromCurrentValues(entry), + navigation.ForeignKey.GetDependentKeyValueFactory(), + PrincipalKeyValueFactory); } } } diff --git a/src/EFCore/Query/QueryCompilationContext.cs b/src/EFCore/Query/QueryCompilationContext.cs index f13df9bd94a..6cd493dfffd 100644 --- a/src/EFCore/Query/QueryCompilationContext.cs +++ b/src/EFCore/Query/QueryCompilationContext.cs @@ -6,7 +6,6 @@ using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; -using System.Threading; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Extensions.Internal; diff --git a/src/EFCore/Query/ResultOperatorHandler.cs b/src/EFCore/Query/ResultOperatorHandler.cs index 6cd130d6c75..b69cb0a16af 100644 --- a/src/EFCore/Query/ResultOperatorHandler.cs +++ b/src/EFCore/Query/ResultOperatorHandler.cs @@ -130,9 +130,9 @@ var resultItemTypeInfo .IsAssignableFrom(resultItemTypeInfo) ? entityQueryModelVisitor.Expression : Expression.Call( - entityQueryModelVisitor.LinqOperatorProvider - .Cast.MakeGenericMethod(castResultOperator.CastItemType), - entityQueryModelVisitor.Expression); + entityQueryModelVisitor.LinqOperatorProvider + .Cast.MakeGenericMethod(castResultOperator.CastItemType), + entityQueryModelVisitor.Expression); } private static Expression HandleConcat( @@ -371,9 +371,9 @@ public async Task MoveNext(CancellationToken cancellationToken) { if (entityQueryModelVisitor.Expression is MethodCallExpression methodCallExpression && (methodCallExpression.Method - .MethodIsClosedFormOf(entityQueryModelVisitor.LinqOperatorProvider.Select) + .MethodIsClosedFormOf(entityQueryModelVisitor.LinqOperatorProvider.Select) || methodCallExpression.Method - .MethodIsClosedFormOf(AsyncLinqOperatorProvider.SelectAsyncMethod))) + .MethodIsClosedFormOf(AsyncLinqOperatorProvider.SelectAsyncMethod))) { // Push Last down below Select @@ -443,9 +443,9 @@ var countExpression if (entityQueryModelVisitor.Expression is MethodCallExpression methodCallExpression && (methodCallExpression.Method - .MethodIsClosedFormOf(entityQueryModelVisitor.LinqOperatorProvider.Select) + .MethodIsClosedFormOf(entityQueryModelVisitor.LinqOperatorProvider.Select) || methodCallExpression.Method - .MethodIsClosedFormOf(AsyncLinqOperatorProvider.SelectAsyncMethod))) + .MethodIsClosedFormOf(AsyncLinqOperatorProvider.SelectAsyncMethod))) { // Push Skip down below Select @@ -482,9 +482,9 @@ var countExpression if (entityQueryModelVisitor.Expression is MethodCallExpression methodCallExpression && (methodCallExpression.Method - .MethodIsClosedFormOf(entityQueryModelVisitor.LinqOperatorProvider.Select) + .MethodIsClosedFormOf(entityQueryModelVisitor.LinqOperatorProvider.Select) || methodCallExpression.Method - .MethodIsClosedFormOf(AsyncLinqOperatorProvider.SelectAsyncMethod))) + .MethodIsClosedFormOf(AsyncLinqOperatorProvider.SelectAsyncMethod))) { // Push Take down below Select diff --git a/src/EFCore/Query/ResultOperators/Internal/IgnoreQueryFiltersExpressionNode.cs b/src/EFCore/Query/ResultOperators/Internal/IgnoreQueryFiltersExpressionNode.cs index 9ed69eb9779..67b928b80f1 100644 --- a/src/EFCore/Query/ResultOperators/Internal/IgnoreQueryFiltersExpressionNode.cs +++ b/src/EFCore/Query/ResultOperators/Internal/IgnoreQueryFiltersExpressionNode.cs @@ -19,8 +19,7 @@ public class IgnoreQueryFiltersExpressionNode : ResultOperatorExpressionNodeBase /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - public static readonly IReadOnlyCollection SupportedMethods = new[] - { EntityFrameworkQueryableExtensions.IgnoreQueryFiltersMethodInfo }; + public static readonly IReadOnlyCollection SupportedMethods = new[] { EntityFrameworkQueryableExtensions.IgnoreQueryFiltersMethodInfo }; /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore/Query/ResultOperators/Internal/IncludeExpressionNode.cs b/src/EFCore/Query/ResultOperators/Internal/IncludeExpressionNode.cs index 9e0aaea2a4a..fe69a91f0bd 100644 --- a/src/EFCore/Query/ResultOperators/Internal/IncludeExpressionNode.cs +++ b/src/EFCore/Query/ResultOperators/Internal/IncludeExpressionNode.cs @@ -23,8 +23,7 @@ public class IncludeExpressionNode : IncludeExpressionNodeBase /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - public static readonly IReadOnlyCollection SupportedMethods = new[] - { EntityFrameworkQueryableExtensions.IncludeMethodInfo }; + public static readonly IReadOnlyCollection SupportedMethods = new[] { EntityFrameworkQueryableExtensions.IncludeMethodInfo }; /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore/Query/ResultOperators/Internal/StringIncludeExpressionNode.cs b/src/EFCore/Query/ResultOperators/Internal/StringIncludeExpressionNode.cs index 82c1d9df7f0..ee71a88a79c 100644 --- a/src/EFCore/Query/ResultOperators/Internal/StringIncludeExpressionNode.cs +++ b/src/EFCore/Query/ResultOperators/Internal/StringIncludeExpressionNode.cs @@ -21,8 +21,7 @@ public class StringIncludeExpressionNode : ResultOperatorExpressionNodeBase /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - public static readonly IReadOnlyCollection SupportedMethods = new[] - { EntityFrameworkQueryableExtensions.StringIncludeMethodInfo }; + public static readonly IReadOnlyCollection SupportedMethods = new[] { EntityFrameworkQueryableExtensions.StringIncludeMethodInfo }; private readonly ConstantExpression _navigationPropertyPath; diff --git a/src/EFCore/Query/ResultOperators/Internal/TagExpressionNode.cs b/src/EFCore/Query/ResultOperators/Internal/TagExpressionNode.cs index 67d83fd1c4c..9923aca070b 100644 --- a/src/EFCore/Query/ResultOperators/Internal/TagExpressionNode.cs +++ b/src/EFCore/Query/ResultOperators/Internal/TagExpressionNode.cs @@ -20,8 +20,7 @@ public class TagExpressionNode : ResultOperatorExpressionNodeBase /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - public static readonly IReadOnlyCollection SupportedMethods = new[] - { EntityFrameworkQueryableExtensions.TagWithMethodInfo }; + public static readonly IReadOnlyCollection SupportedMethods = new[] { EntityFrameworkQueryableExtensions.TagWithMethodInfo }; private readonly ConstantExpression _tagExpression; diff --git a/src/EFCore/Query/ResultOperators/Internal/ThenIncludeExpressionNode.cs b/src/EFCore/Query/ResultOperators/Internal/ThenIncludeExpressionNode.cs index fd3450f69b6..48bd8453105 100644 --- a/src/EFCore/Query/ResultOperators/Internal/ThenIncludeExpressionNode.cs +++ b/src/EFCore/Query/ResultOperators/Internal/ThenIncludeExpressionNode.cs @@ -23,11 +23,7 @@ public class ThenIncludeExpressionNode : IncludeExpressionNodeBase /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - public static readonly IReadOnlyCollection SupportedMethods = new[] - { - EntityFrameworkQueryableExtensions.ThenIncludeAfterEnumerableMethodInfo, - EntityFrameworkQueryableExtensions.ThenIncludeAfterReferenceMethodInfo - }; + public static readonly IReadOnlyCollection SupportedMethods = new[] { EntityFrameworkQueryableExtensions.ThenIncludeAfterEnumerableMethodInfo, EntityFrameworkQueryableExtensions.ThenIncludeAfterReferenceMethodInfo }; /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore/Query/ResultOperators/Internal/TrackingExpressionNode.cs b/src/EFCore/Query/ResultOperators/Internal/TrackingExpressionNode.cs index 117d755ee98..28ce44be0bf 100644 --- a/src/EFCore/Query/ResultOperators/Internal/TrackingExpressionNode.cs +++ b/src/EFCore/Query/ResultOperators/Internal/TrackingExpressionNode.cs @@ -19,11 +19,7 @@ public class TrackingExpressionNode : ResultOperatorExpressionNodeBase /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - public static readonly IReadOnlyCollection SupportedMethods = new[] - { - EntityFrameworkQueryableExtensions.AsNoTrackingMethodInfo, - EntityFrameworkQueryableExtensions.AsTrackingMethodInfo - }; + public static readonly IReadOnlyCollection SupportedMethods = new[] { EntityFrameworkQueryableExtensions.AsNoTrackingMethodInfo, EntityFrameworkQueryableExtensions.AsTrackingMethodInfo }; /// /// This API supports the Entity Framework Core infrastructure and is not intended to be used diff --git a/src/EFCore/Storage/CoreTypeMapping.cs b/src/EFCore/Storage/CoreTypeMapping.cs index 9d112e3944f..8d0604ff13c 100644 --- a/src/EFCore/Storage/CoreTypeMapping.cs +++ b/src/EFCore/Storage/CoreTypeMapping.cs @@ -123,7 +123,7 @@ public CoreTypeMappingParameters WithComposedConverter([CanBeNull] ValueConverte private ValueComparer _comparer; private ValueComparer _keyComparer; - private ValueComparer _structuralComparer; + private readonly ValueComparer _structuralComparer; /// /// Initializes a new instance of the class. diff --git a/src/EFCore/Storage/MaterializationContext.cs b/src/EFCore/Storage/MaterializationContext.cs index 117a7a8938f..458dddee5c0 100644 --- a/src/EFCore/Storage/MaterializationContext.cs +++ b/src/EFCore/Storage/MaterializationContext.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; @@ -21,7 +20,7 @@ namespace Microsoft.EntityFrameworkCore.Storage public readonly struct MaterializationContext { /// - /// The for the get method. + /// The for the get method. /// public static readonly MethodInfo GetValueBufferMethod = typeof(MaterializationContext).GetProperty(nameof(ValueBuffer)).GetMethod; diff --git a/src/EFCore/Storage/ValueBuffer.cs b/src/EFCore/Storage/ValueBuffer.cs index 0cc06028f18..43a5f58ff1f 100644 --- a/src/EFCore/Storage/ValueBuffer.cs +++ b/src/EFCore/Storage/ValueBuffer.cs @@ -109,7 +109,7 @@ public override bool Equals(object obj) return obj is null ? false : obj is ValueBuffer buffer - && Equals(buffer); + && Equals(buffer); } private bool Equals(ValueBuffer other) diff --git a/src/EFCore/Storage/ValueConversion/DateTimeOffsetToStringConverter.cs b/src/EFCore/Storage/ValueConversion/DateTimeOffsetToStringConverter.cs index c0adfb655a5..85d2e774f8c 100644 --- a/src/EFCore/Storage/ValueConversion/DateTimeOffsetToStringConverter.cs +++ b/src/EFCore/Storage/ValueConversion/DateTimeOffsetToStringConverter.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Globalization; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal; diff --git a/src/EFCore/Storage/ValueConversion/EnumToStringConverter.cs b/src/EFCore/Storage/ValueConversion/EnumToStringConverter.cs index d8cc3d23ad9..8eb21017791 100644 --- a/src/EFCore/Storage/ValueConversion/EnumToStringConverter.cs +++ b/src/EFCore/Storage/ValueConversion/EnumToStringConverter.cs @@ -1,10 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; -using System.Linq.Expressions; using JetBrains.Annotations; -using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal; namespace Microsoft.EntityFrameworkCore.Storage.ValueConversion diff --git a/src/EFCore/Storage/ValueConversion/GuidToStringConverter.cs b/src/EFCore/Storage/ValueConversion/GuidToStringConverter.cs index d098e2d08c1..b05c37da450 100644 --- a/src/EFCore/Storage/ValueConversion/GuidToStringConverter.cs +++ b/src/EFCore/Storage/ValueConversion/GuidToStringConverter.cs @@ -4,7 +4,6 @@ using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal; -using Microsoft.EntityFrameworkCore.ValueGeneration; namespace Microsoft.EntityFrameworkCore.Storage.ValueConversion { diff --git a/src/EFCore/Storage/ValueConversion/Internal/StringCharConverter.cs b/src/EFCore/Storage/ValueConversion/Internal/StringCharConverter.cs index 63ce519c688..cc95848fb4b 100644 --- a/src/EFCore/Storage/ValueConversion/Internal/StringCharConverter.cs +++ b/src/EFCore/Storage/ValueConversion/Internal/StringCharConverter.cs @@ -30,7 +30,7 @@ public class StringCharConverter : ValueConverter - protected new static Expression> ToString() + protected static new Expression> ToString() => v => string.Format(CultureInfo.InvariantCulture, "{0}", v); /// diff --git a/src/EFCore/Storage/ValueConversion/Internal/StringDateTimeConverter.cs b/src/EFCore/Storage/ValueConversion/Internal/StringDateTimeConverter.cs index 5b2ec143253..06aa5a135e9 100644 --- a/src/EFCore/Storage/ValueConversion/Internal/StringDateTimeConverter.cs +++ b/src/EFCore/Storage/ValueConversion/Internal/StringDateTimeConverter.cs @@ -38,7 +38,7 @@ public class StringDateTimeConverter : ValueConverter - protected new static Expression> ToString() + protected static new Expression> ToString() => v => v.ToString(@"yyyy\-MM\-dd HH\:mm\:ss.FFFFFFF"); /// diff --git a/src/EFCore/Storage/ValueConversion/Internal/StringDateTimeOffsetConverter.cs b/src/EFCore/Storage/ValueConversion/Internal/StringDateTimeOffsetConverter.cs index 164a27065e3..7e8c2030466 100644 --- a/src/EFCore/Storage/ValueConversion/Internal/StringDateTimeOffsetConverter.cs +++ b/src/EFCore/Storage/ValueConversion/Internal/StringDateTimeOffsetConverter.cs @@ -38,7 +38,7 @@ public class StringDateTimeOffsetConverter : ValueConverter - protected new static Expression> ToString() + protected static new Expression> ToString() => v => v.ToString(@"yyyy\-MM\-dd HH\:mm\:ss.FFFFFFFzzz"); /// diff --git a/src/EFCore/Storage/ValueConversion/Internal/StringEnumConverter.cs b/src/EFCore/Storage/ValueConversion/Internal/StringEnumConverter.cs index 27976241504..26b29b64b08 100644 --- a/src/EFCore/Storage/ValueConversion/Internal/StringEnumConverter.cs +++ b/src/EFCore/Storage/ValueConversion/Internal/StringEnumConverter.cs @@ -31,7 +31,7 @@ public class StringEnumConverter : ValueConverter - protected new static Expression> ToString() + protected static new Expression> ToString() => v => v.ToString(); /// diff --git a/src/EFCore/Storage/ValueConversion/Internal/StringGuidConverter.cs b/src/EFCore/Storage/ValueConversion/Internal/StringGuidConverter.cs index 71fb058ce75..e839219a50f 100644 --- a/src/EFCore/Storage/ValueConversion/Internal/StringGuidConverter.cs +++ b/src/EFCore/Storage/ValueConversion/Internal/StringGuidConverter.cs @@ -40,7 +40,7 @@ public class StringGuidConverter : ValueConverter - protected new static Expression> ToString() + protected static new Expression> ToString() => v => v.ToString("D"); /// diff --git a/src/EFCore/Storage/ValueConversion/Internal/StringNumberConverter.cs b/src/EFCore/Storage/ValueConversion/Internal/StringNumberConverter.cs index 71a400a59bb..2add1befa8b 100644 --- a/src/EFCore/Storage/ValueConversion/Internal/StringNumberConverter.cs +++ b/src/EFCore/Storage/ValueConversion/Internal/StringNumberConverter.cs @@ -78,7 +78,7 @@ public class StringNumberConverter : ValueConverter< /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// - protected new static Expression> ToString() + protected static new Expression> ToString() { var type = typeof(TNumber).UnwrapNullableType(); diff --git a/src/EFCore/Storage/ValueConversion/Internal/StringTimeSpanConverter.cs b/src/EFCore/Storage/ValueConversion/Internal/StringTimeSpanConverter.cs index 932686a5635..7af2022e9e3 100644 --- a/src/EFCore/Storage/ValueConversion/Internal/StringTimeSpanConverter.cs +++ b/src/EFCore/Storage/ValueConversion/Internal/StringTimeSpanConverter.cs @@ -38,7 +38,7 @@ public class StringTimeSpanConverter : ValueConverter - protected new static Expression> ToString() + protected static new Expression> ToString() => v => v.ToString("c"); /// diff --git a/src/EFCore/Storage/ValueConversion/NumberToBytesConverter.cs b/src/EFCore/Storage/ValueConversion/NumberToBytesConverter.cs index ba2d4572019..ef603e4c361 100644 --- a/src/EFCore/Storage/ValueConversion/NumberToBytesConverter.cs +++ b/src/EFCore/Storage/ValueConversion/NumberToBytesConverter.cs @@ -163,16 +163,13 @@ private static Expression EnsureEndian(Expression expression) BindingFlags.Static | BindingFlags.NonPublic); private static byte[] ReverseLong(byte[] bytes) - => new[] - { bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0] }; + => new[] { bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0] }; private static byte[] ReverseInt(byte[] bytes) - => new[] - { bytes[3], bytes[2], bytes[1], bytes[0] }; + => new[] { bytes[3], bytes[2], bytes[1], bytes[0] }; private static byte[] ReverseShort(byte[] bytes) - => new[] - { bytes[1], bytes[0] }; + => new[] { bytes[1], bytes[0] }; private static int GetByteCount() { diff --git a/src/EFCore/Storage/ValueConversion/StringToBoolConverter.cs b/src/EFCore/Storage/ValueConversion/StringToBoolConverter.cs index 8969439b6de..3d935f82ec0 100644 --- a/src/EFCore/Storage/ValueConversion/StringToBoolConverter.cs +++ b/src/EFCore/Storage/ValueConversion/StringToBoolConverter.cs @@ -15,7 +15,7 @@ public class StringToBoolConverter : ValueConverter /// Creates a new instance of this converter. /// /// - /// Hints that can be used by the to create data types with appropriate + /// Hints that can be used by the to create data types with appropriate /// facets for the converted data. /// public StringToBoolConverter( diff --git a/src/EFCore/Storage/ValueConversion/StringToCharConverter.cs b/src/EFCore/Storage/ValueConversion/StringToCharConverter.cs index 821e76d4e5c..a7b2b64c4fc 100644 --- a/src/EFCore/Storage/ValueConversion/StringToCharConverter.cs +++ b/src/EFCore/Storage/ValueConversion/StringToCharConverter.cs @@ -18,7 +18,7 @@ public class StringToCharConverter : StringCharConverter /// Creates a new instance of this converter. This converter preserves order. /// /// - /// Hints that can be used by the to create data types with appropriate + /// Hints that can be used by the to create data types with appropriate /// facets for the converted data. /// public StringToCharConverter([CanBeNull] ConverterMappingHints mappingHints = null) diff --git a/src/EFCore/Storage/ValueConversion/StringToDateTimeConverter.cs b/src/EFCore/Storage/ValueConversion/StringToDateTimeConverter.cs index c6bbd8cf860..e59c6903136 100644 --- a/src/EFCore/Storage/ValueConversion/StringToDateTimeConverter.cs +++ b/src/EFCore/Storage/ValueConversion/StringToDateTimeConverter.cs @@ -16,7 +16,7 @@ public class StringToDateTimeConverter : StringDateTimeConverter /// - /// Hints that can be used by the to create data types with appropriate + /// Hints that can be used by the to create data types with appropriate /// facets for the converted data. /// public StringToDateTimeConverter([CanBeNull] ConverterMappingHints mappingHints = null) diff --git a/src/EFCore/Storage/ValueConversion/StringToDateTimeOffsetConverter.cs b/src/EFCore/Storage/ValueConversion/StringToDateTimeOffsetConverter.cs index b58d128ee91..563fec5c951 100644 --- a/src/EFCore/Storage/ValueConversion/StringToDateTimeOffsetConverter.cs +++ b/src/EFCore/Storage/ValueConversion/StringToDateTimeOffsetConverter.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Globalization; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal; @@ -17,7 +16,7 @@ public class StringToDateTimeOffsetConverter : StringDateTimeOffsetConverter /// - /// Hints that can be used by the to create data types with appropriate + /// Hints that can be used by the to create data types with appropriate /// facets for the converted data. /// public StringToDateTimeOffsetConverter( diff --git a/src/EFCore/Storage/ValueConversion/StringToEnumConverter.cs b/src/EFCore/Storage/ValueConversion/StringToEnumConverter.cs index 2ca0d7892d3..d612ed241a4 100644 --- a/src/EFCore/Storage/ValueConversion/StringToEnumConverter.cs +++ b/src/EFCore/Storage/ValueConversion/StringToEnumConverter.cs @@ -16,7 +16,7 @@ public class StringToEnumConverter : StringEnumConverter /// - /// Hints that can be used by the to create data types with appropriate + /// Hints that can be used by the to create data types with appropriate /// facets for the converted data. /// public StringToEnumConverter([CanBeNull] ConverterMappingHints mappingHints = null) diff --git a/src/EFCore/Storage/ValueConversion/StringToGuidConverter.cs b/src/EFCore/Storage/ValueConversion/StringToGuidConverter.cs index 0160b7648b5..a2f017eeb99 100644 --- a/src/EFCore/Storage/ValueConversion/StringToGuidConverter.cs +++ b/src/EFCore/Storage/ValueConversion/StringToGuidConverter.cs @@ -17,7 +17,7 @@ public class StringToGuidConverter : StringGuidConverter /// Creates a new instance of this converter. /// /// - /// Hints that can be used by the to create data types with appropriate + /// Hints that can be used by the to create data types with appropriate /// facets for the converted data. /// public StringToGuidConverter([CanBeNull] ConverterMappingHints mappingHints = null) diff --git a/src/EFCore/Storage/ValueConversion/StringToNumberConverter.cs b/src/EFCore/Storage/ValueConversion/StringToNumberConverter.cs index 0cf776db786..f79d587b2da 100644 --- a/src/EFCore/Storage/ValueConversion/StringToNumberConverter.cs +++ b/src/EFCore/Storage/ValueConversion/StringToNumberConverter.cs @@ -15,15 +15,15 @@ public class StringToNumberConverter : StringNumberConverter /// - /// Hints that can be used by the to create data types with appropriate + /// Hints that can be used by the to create data types with appropriate /// facets for the converted data. /// public StringToNumberConverter( [CanBeNull] ConverterMappingHints mappingHints = null) : base( - ToNumber(), - ToString(), - _defaultHints.With(mappingHints)) + ToNumber(), + ToString(), + _defaultHints.With(mappingHints)) { } diff --git a/src/EFCore/Storage/ValueConversion/StringToTimeSpanConverter.cs b/src/EFCore/Storage/ValueConversion/StringToTimeSpanConverter.cs index 529e994f809..ae3a1452f2e 100644 --- a/src/EFCore/Storage/ValueConversion/StringToTimeSpanConverter.cs +++ b/src/EFCore/Storage/ValueConversion/StringToTimeSpanConverter.cs @@ -16,7 +16,7 @@ public class StringToTimeSpanConverter : StringTimeSpanConverter /// - /// Hints that can be used by the to create data types with appropriate + /// Hints that can be used by the to create data types with appropriate /// facets for the converted data. /// public StringToTimeSpanConverter([CanBeNull] ConverterMappingHints mappingHints = null) diff --git a/src/EFCore/Storage/ValueConversion/ValueConverterSelector.cs b/src/EFCore/Storage/ValueConversion/ValueConverterSelector.cs index 6f0dfb13215..656ac81ab22 100644 --- a/src/EFCore/Storage/ValueConversion/ValueConverterSelector.cs +++ b/src/EFCore/Storage/ValueConversion/ValueConverterSelector.cs @@ -21,24 +21,15 @@ public class ValueConverterSelector : IValueConverterSelector private readonly ConcurrentDictionary<(Type ModelClrType, Type ProviderClrType), ValueConverterInfo> _converters = new ConcurrentDictionary<(Type, Type), ValueConverterInfo>(); - private static readonly Type[] _signedPreferred = - { typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(decimal) }; + private static readonly Type[] _signedPreferred = { typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(decimal) }; - private static readonly Type[] _unsignedPreferred = - { typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(decimal) }; + private static readonly Type[] _unsignedPreferred = { typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(decimal) }; - private static readonly Type[] _floatingPreferred = - { typeof(float), typeof(double), typeof(decimal) }; + private static readonly Type[] _floatingPreferred = { typeof(float), typeof(double), typeof(decimal) }; - private static readonly Type[] _charPreferred = - { typeof(char), typeof(int), typeof(ushort), typeof(uint), typeof(long), typeof(ulong), typeof(decimal) }; + private static readonly Type[] _charPreferred = { typeof(char), typeof(int), typeof(ushort), typeof(uint), typeof(long), typeof(ulong), typeof(decimal) }; - private static readonly Type[] _numerics = - { - typeof(int), typeof(long), typeof(short), typeof(byte), - typeof(ulong), typeof(uint), typeof(ushort), typeof(sbyte), - typeof(decimal), typeof(double), typeof(float) - }; + private static readonly Type[] _numerics = { typeof(int), typeof(long), typeof(short), typeof(byte), typeof(ulong), typeof(uint), typeof(ushort), typeof(sbyte), typeof(decimal), typeof(double), typeof(float) }; /// /// Initializes a new instance of the class. diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteBlob.cs b/src/Microsoft.Data.Sqlite.Core/SqliteBlob.cs index 990451b4237..5bba86b8dc9 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteBlob.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteBlob.cs @@ -10,7 +10,7 @@ namespace Microsoft.Data.Sqlite { /// - /// Provides methods to access the contents of a blob. + /// Provides methods to access the contents of a blob. /// public class SqliteBlob : Stream { @@ -19,7 +19,7 @@ public class SqliteBlob : Stream private long _position; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// An open connection to the database. /// The name of table containing the blob. @@ -37,7 +37,7 @@ public class SqliteBlob : Stream } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// An open connection to the database. /// The name of the attached database containing the blob. @@ -57,10 +57,12 @@ public class SqliteBlob : Stream { throw new InvalidOperationException(Resources.SqlBlobRequiresOpenConnection); } + if (string.IsNullOrEmpty(tableName)) { throw new ArgumentNullException(nameof(tableName)); } + if (string.IsNullOrEmpty(columnName)) { throw new ArgumentNullException(nameof(columnName)); @@ -81,33 +83,33 @@ public class SqliteBlob : Stream } /// - /// Gets a value indicating whether the current stream supports reading. - /// Always true. + /// Gets a value indicating whether the current stream supports reading. + /// Always true. /// /// true if the stream supports reading; otherwise, false. public override bool CanRead => true; /// - /// Gets a value indicating whether the current stream supports writing. + /// Gets a value indicating whether the current stream supports writing. /// /// true if the stream supports writing; otherwise, false. public override bool CanWrite { get; } /// - /// Gets a value indicating whether the current stream supports seeking. - /// Always true. + /// Gets a value indicating whether the current stream supports seeking. + /// Always true. /// /// true if the stream supports seeking; otherwise, false. public override bool CanSeek => true; /// - /// Gets the length in bytes of the stream. + /// Gets the length in bytes of the stream. /// /// A long value representing the length of the stream in bytes. public override long Length { get; } /// - /// Gets or sets the position within the current stream. + /// Gets or sets the position within the current stream. /// /// The current position within the stream. public override long Position @@ -126,11 +128,13 @@ public override long Position } /// - /// Reads a sequence of bytes from the current stream and advances the position - /// within the stream by the number of bytes read. + /// Reads a sequence of bytes from the current stream and advances the position + /// within the stream by the number of bytes read. /// - /// An array of bytes. When this method returns, the buffer contains the specified byte array - /// with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. + /// + /// An array of bytes. When this method returns, the buffer contains the specified byte array + /// with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. + /// /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. /// The maximum number of bytes to be read from the current stream. /// The total number of bytes read into the buffer. @@ -140,19 +144,23 @@ public override int Read(byte[] buffer, int offset, int count) { throw new ArgumentNullException(nameof(buffer)); } + if (offset < 0) { // NB: Message is provided by the framework throw new ArgumentOutOfRangeException(nameof(offset), offset, message: null); } + if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, message: null); } + if (offset + count > buffer.Length) { throw new ArgumentException(Resources.InvalidOffsetAndCount); } + if (_blob == null) { throw new ObjectDisposedException(objectName: null); @@ -176,8 +184,8 @@ public override int Read(byte[] buffer, int offset, int count) } /// - /// Writes a sequence of bytes to the current stream and advances the current position - /// within this stream by the number of bytes written. + /// Writes a sequence of bytes to the current stream and advances the current position + /// within this stream by the number of bytes written. /// /// An array of bytes. This method copies count bytes from buffer to the current stream. /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream. @@ -188,23 +196,28 @@ public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(Resources.WriteNotSupported); } + if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } + if (offset < 0) { // NB: Message is provided by the framework throw new ArgumentOutOfRangeException(nameof(offset), offset, message: null); } + if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, message: null); } + if (offset + count > buffer.Length) { throw new ArgumentException(Resources.InvalidOffsetAndCount); } + if (_blob == null) { throw new ObjectDisposedException(objectName: null); @@ -227,7 +240,7 @@ public override void Write(byte[] buffer, int offset, int count) } /// - /// Sets the position within the current stream. + /// Sets the position within the current stream. /// /// A byte offset relative to the origin parameter. /// A value indicating the reference point used to obtain the new position. @@ -274,16 +287,16 @@ protected override void Dispose(bool disposing) } /// - /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. - /// Does nothing. + /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. + /// Does nothing. /// public override void Flush() { } /// - /// Sets the length of the current stream. This is not supported by sqlite blobs. - /// Not supported. + /// Sets the length of the current stream. This is not supported by sqlite blobs. + /// Not supported. /// /// The desired length of the current stream in bytes. /// Always. diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs b/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs index 0cca8453e57..fc5def6a71a 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs @@ -311,6 +311,7 @@ public new virtual SqliteDataReader ExecuteReader(CommandBehavior behavior) ? Resources.TransactionRequired : Resources.TransactionConnectionMismatch); } + if (_connection.Transaction?.ExternalRollback == true) { throw new InvalidOperationException(Resources.TransactionCompleted); @@ -480,6 +481,7 @@ public override int ExecuteNonQuery() { throw new InvalidOperationException(Resources.CallRequiresOpenConnection(nameof(ExecuteNonQuery))); } + if (_commandText == null) { throw new InvalidOperationException(Resources.CallRequiresSetCommandText(nameof(ExecuteNonQuery))); @@ -502,6 +504,7 @@ public override object ExecuteScalar() { throw new InvalidOperationException(Resources.CallRequiresOpenConnection(nameof(ExecuteScalar))); } + if (_commandText == null) { throw new InvalidOperationException(Resources.CallRequiresSetCommandText(nameof(ExecuteScalar))); @@ -539,6 +542,7 @@ private IEnumerable PrepareAndEnumerateStatements(Stopwatch timer) Thread.Sleep(150); } + tail = nextTail; SqliteException.ThrowExceptionForRC(rc, _connection.Handle); @@ -583,7 +587,7 @@ private void DisposePreparedStatements(bool disposing = true) private static bool IsBusy(int rc) => rc == raw.SQLITE_LOCKED - || rc == raw.SQLITE_BUSY - || rc == raw.SQLITE_LOCKED_SHAREDCACHE; + || rc == raw.SQLITE_BUSY + || rc == raw.SQLITE_LOCKED_SHAREDCACHE; } } diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteConnection.cs b/src/Microsoft.Data.Sqlite.Core/SqliteConnection.cs index 89932004818..218f3b4a4be 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteConnection.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteConnection.cs @@ -7,7 +7,6 @@ using System.Data.Common; using System.Diagnostics; using System.IO; -using System.Reflection; using Microsoft.Data.Sqlite.Properties; using Microsoft.Data.Sqlite.Utilities; using SQLitePCL; @@ -103,11 +102,11 @@ public override string DataSource } /// - /// Gets or sets the default value for commands created using + /// Gets or sets the default value for commands created using /// this connection. This is also used for internal commands in methods like - /// . + /// . /// - /// The default value. + /// The default value. public virtual int DefaultTimeout { get; set; } = 30; /// @@ -148,6 +147,7 @@ public override void Open() { return; } + if (ConnectionString == null) { throw new InvalidOperationException(Resources.OpenRequiresSetConnectionString); @@ -178,6 +178,7 @@ public override void Open() flags |= raw.SQLITE_OPEN_URI; filename = "file:" + filename; } + break; default: @@ -218,7 +219,6 @@ public override void Open() { filename = Path.Combine(dataDirectory, filename); } - } var rc = raw.sqlite3_open_v2(filename, out _db, flags, vfs: null); @@ -325,7 +325,12 @@ protected override void Dispose(bool disposing) /// transaction. /// public new virtual SqliteCommand CreateCommand() - => new SqliteCommand { Connection = this, CommandTimeout = DefaultTimeout, Transaction = Transaction }; + => new SqliteCommand + { + Connection = this, + CommandTimeout = DefaultTimeout, + Transaction = Transaction + }; /// /// Creates a new command associated with the connection. @@ -407,6 +412,7 @@ public new virtual SqliteTransaction BeginTransaction(IsolationLevel isolationLe { throw new InvalidOperationException(Resources.CallRequiresOpenConnection(nameof(BeginTransaction))); } + if (Transaction != null) { throw new InvalidOperationException(Resources.ParallelTransactionsNotSupported); @@ -460,6 +466,7 @@ public virtual void BackupDatabase(SqliteConnection destination, string destinat { throw new InvalidOperationException(Resources.CallRequiresOpenConnection(nameof(BackupDatabase))); } + if (destination == null) { throw new ArgumentNullException(nameof(destination)); @@ -471,6 +478,7 @@ public virtual void BackupDatabase(SqliteConnection destination, string destinat destination.Open(); close = true; } + try { using (var backup = raw.sqlite3_backup_init(destination._db, destinationName, _db, sourceName)) @@ -516,28 +524,28 @@ public virtual void BackupDatabase(SqliteConnection destination, string destinat if (function != null) { func = (ctx, user_data, args) => + { + // TODO: Avoid allocation when niladic + var values = new SqliteParameterReader(name, args); + + try { - // TODO: Avoid allocation when niladic - var values = new SqliteParameterReader(name, args); + // TODO: Avoid closure by passing function via user_data + var result = function((TState)user_data, values); - try - { - // TODO: Avoid closure by passing function via user_data - var result = function((TState)user_data, values); + new SqliteResultBinder(ctx, result).Bind(); + } + catch (Exception ex) + { + raw.sqlite3_result_error(ctx, ex.Message); - new SqliteResultBinder(ctx, result).Bind(); - } - catch (Exception ex) + if (ex is SqliteException sqlEx) { - raw.sqlite3_result_error(ctx, ex.Message); - - if (ex is SqliteException sqlEx) - { - // NB: This must be called after sqlite3_result_error() - raw.sqlite3_result_error_code(ctx, sqlEx.SqliteErrorCode); - } + // NB: This must be called after sqlite3_result_error() + raw.sqlite3_result_error_code(ctx, sqlEx.SqliteErrorCode); } - }; + } + }; } var rc = raw.sqlite3_create_function( @@ -572,62 +580,62 @@ public virtual void BackupDatabase(SqliteConnection destination, string destinat if (func != null) { func_step = (ctx, user_data, args) => + { + var context = (AggregateContext)user_data; + if (context.Exception != null) { - var context = (AggregateContext)user_data; - if (context.Exception != null) - { - return; - } + return; + } - // TODO: Avoid allocation when niladic - var reader = new SqliteParameterReader(name, args); + // TODO: Avoid allocation when niladic + var reader = new SqliteParameterReader(name, args); - try - { - // TODO: Avoid closure by passing func via user_data - // NB: No need to set ctx.state since we just mutate the instance - context.Accumulate = func(context.Accumulate, reader); - } - catch (Exception ex) - { - context.Exception = ex; - } - }; + try + { + // TODO: Avoid closure by passing func via user_data + // NB: No need to set ctx.state since we just mutate the instance + context.Accumulate = func(context.Accumulate, reader); + } + catch (Exception ex) + { + context.Exception = ex; + } + }; } delegate_function_aggregate_final func_final = null; if (resultSelector != null) { func_final = (ctx, user_data) => + { + var context = (AggregateContext)user_data; + + if (context.Exception == null) { - var context = (AggregateContext)user_data; + try + { + // TODO: Avoid closure by passing resultSelector via user_data + var result = resultSelector(context.Accumulate); - if (context.Exception == null) + new SqliteResultBinder(ctx, result).Bind(); + } + catch (Exception ex) { - try - { - // TODO: Avoid closure by passing resultSelector via user_data - var result = resultSelector(context.Accumulate); - - new SqliteResultBinder(ctx, result).Bind(); - } - catch (Exception ex) - { - context.Exception = ex; - } + context.Exception = ex; } + } - if (context.Exception != null) - { - raw.sqlite3_result_error(ctx, context.Exception.Message); + if (context.Exception != null) + { + raw.sqlite3_result_error(ctx, context.Exception.Message); - if (context.Exception is SqliteException sqlEx) - { - // NB: This must be called after sqlite3_result_error() - raw.sqlite3_result_error_code(ctx, sqlEx.SqliteErrorCode); - } + if (context.Exception is SqliteException sqlEx) + { + // NB: This must be called after sqlite3_result_error() + raw.sqlite3_result_error_code(ctx, sqlEx.SqliteErrorCode); } - }; + } + }; } var rc = raw.sqlite3_create_function( diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs index 71fb96f6c04..c11b9c30eed 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteConnectionStringBuilder.cs @@ -48,7 +48,6 @@ private enum Keywords private bool _foreignKeys; private bool _recursiveTriggers; - static SqliteConnectionStringBuilder() { var validKeywords = new string[6]; diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteDataReader.cs b/src/Microsoft.Data.Sqlite.Core/SqliteDataReader.cs index eab48743dbf..49295328408 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteDataReader.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteDataReader.cs @@ -408,8 +408,8 @@ public override long GetChars(int ordinal, long dataOffset, char[] buffer, int b /// /// Retrieves data as a Stream. If the reader includes rowid (or any of its aliases), a - /// is returned. Otherwise, the all of the data is read into memory and a - /// is returned. + /// is returned. Otherwise, the all of the data is read into memory and a + /// is returned. /// /// The zero-based column ordinal. /// The returned object. @@ -444,6 +444,7 @@ public override object GetValue(int ordinal) { throw new InvalidOperationException(Resources.DataReaderClosed(nameof(GetValue))); } + if (!_stepped || _done) { throw new InvalidOperationException(Resources.NoData); diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteDataRecord.cs b/src/Microsoft.Data.Sqlite.Core/SqliteDataRecord.cs index b1fb90e154c..99959101a39 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteDataRecord.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteDataRecord.cs @@ -178,12 +178,13 @@ public virtual long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bu { var blob = GetCachedBlob(ordinal); - long bytesToRead = (long)blob.Length - dataOffset; + long bytesToRead = blob.Length - dataOffset; if (buffer != null) { - bytesToRead = System.Math.Min(bytesToRead, length); + bytesToRead = Math.Min(bytesToRead, length); Array.Copy(blob, dataOffset, buffer, bufferOffset, bytesToRead); } + return bytesToRead; } @@ -192,14 +193,15 @@ public virtual long GetChars(int ordinal, long dataOffset, char[] buffer, int bu var text = GetString(ordinal); int charsToRead = text.Length - (int)dataOffset; - charsToRead = System.Math.Min(charsToRead, length); + charsToRead = Math.Min(charsToRead, length); text.CopyTo((int)dataOffset, buffer, bufferOffset, charsToRead); return charsToRead; } public virtual Stream GetStream(int ordinal) { - if (ordinal < 0 || ordinal >= FieldCount) + if (ordinal < 0 + || ordinal >= FieldCount) { throw new ArgumentOutOfRangeException(nameof(ordinal), ordinal, message: null); } @@ -228,7 +230,9 @@ public virtual Stream GetStream(int ordinal) } var columnName = raw.sqlite3_column_origin_name(_stmt, i); - if ((columnName == "rowid") || (columnName == "_rowid_") || (columnName == "oid")) + if ((columnName == "rowid") + || (columnName == "_rowid_") + || (columnName == "oid")) { rowidOrdinal = i; break; @@ -245,7 +249,8 @@ public virtual Stream GetStream(int ordinal) out var primaryKey, out var autoInc); SqliteException.ThrowExceptionForRC(rc, _connection.Handle); - if ((dataType == "INTEGER") && (primaryKey != 0)) + if ((dataType == "INTEGER") + && (primaryKey != 0)) { rowidOrdinal = i; break; @@ -273,7 +278,8 @@ internal void Clear() private byte[] GetCachedBlob(int ordinal) { - if (ordinal < 0 || ordinal >= FieldCount) + if (ordinal < 0 + || ordinal >= FieldCount) { // NB: Message is provided by the framework throw new ArgumentOutOfRangeException(nameof(ordinal), ordinal, message: null); diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteException.cs b/src/Microsoft.Data.Sqlite.Core/SqliteException.cs index ea9d1711962..08d2f80ed93 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteException.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteException.cs @@ -20,14 +20,16 @@ public class SqliteException : DbException /// The SQLite error code. public SqliteException(string message, int errorCode) : this(message, errorCode, errorCode) - { } + { + } /// /// Initializes a new instance of the class. /// /// The message to display for the exception. Can be null. /// The SQLite error code. - /// /// The extended SQLite error code. + /// /// + /// The extended SQLite error code. public SqliteException(string message, int errorCode, int extendedErrorCode) : base(message) { @@ -68,7 +70,9 @@ public static void ThrowExceptionForRC(int rc, sqlite3 db) string message; int extendedErrorCode; - if (db == null || db.ptr == IntPtr.Zero || rc != raw.sqlite3_errcode(db)) + if (db == null + || db.ptr == IntPtr.Zero + || rc != raw.sqlite3_errcode(db)) { message = raw.sqlite3_errstr(rc) + " " + Resources.DefaultNativeError; extendedErrorCode = rc; diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs b/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs index 4099880b4f4..aee2fd42027 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteParameter.cs @@ -150,11 +150,11 @@ public override string ParameterName public override int Size { get => _size - ?? (_value is string stringValue - ? stringValue.Length - : _value is byte[] byteArray - ? byteArray.Length - : 0); + ?? (_value is string stringValue + ? stringValue.Length + : _value is byte[] byteArray + ? byteArray.Length + : 0); set { diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteParameterBinder.cs b/src/Microsoft.Data.Sqlite.Core/SqliteParameterBinder.cs index df76379e7b3..27c02ffa242 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteParameterBinder.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteParameterBinder.cs @@ -51,7 +51,7 @@ protected override void BindText(string value) private bool ShouldTruncate(int length) => _size.HasValue - && length > _size.Value - && _size.Value != -1; + && length > _size.Value + && _size.Value != -1; } } diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteParameterCollection.cs b/src/Microsoft.Data.Sqlite.Core/SqliteParameterCollection.cs index b0613016f09..c10cf71a420 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteParameterCollection.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteParameterCollection.cs @@ -330,6 +330,7 @@ internal int Bind(sqlite3_stmt stmt) bound++; } } + return bound; } diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteTransaction.cs b/src/Microsoft.Data.Sqlite.Core/SqliteTransaction.cs index 2fedaf69970..0b5460406fb 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteTransaction.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteTransaction.cs @@ -17,7 +17,6 @@ public class SqliteTransaction : DbTransaction private SqliteConnection _connection; private readonly IsolationLevel _isolationLevel; private bool _completed; - private bool _externalRollback; internal SqliteTransaction(SqliteConnection connection, IsolationLevel isolationLevel) { @@ -66,8 +65,7 @@ public new virtual SqliteConnection Connection protected override DbConnection DbConnection => Connection; - internal bool ExternalRollback - => _externalRollback; + internal bool ExternalRollback { get; private set; } /// /// Gets the isolation level for the transaction. This cannot be changed if the transaction is completed or @@ -89,7 +87,9 @@ public override IsolationLevel IsolationLevel /// public override void Commit() { - if (_externalRollback || _completed || _connection.State != ConnectionState.Open) + if (ExternalRollback + || _completed + || _connection.State != ConnectionState.Open) { throw new InvalidOperationException(Resources.TransactionCompleted); } @@ -137,7 +137,7 @@ private void Complete() private void RollbackInternal() { - if (!_externalRollback) + if (!ExternalRollback) { raw.sqlite3_rollback_hook(_connection.Handle, null, null); _connection.ExecuteNonQuery("ROLLBACK;"); @@ -149,7 +149,7 @@ private void RollbackInternal() private void RollbackExternal(object userData) { raw.sqlite3_rollback_hook(_connection.Handle, null, null); - _externalRollback = true; + ExternalRollback = true; } } } diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteValueBinder.cs b/src/Microsoft.Data.Sqlite.Core/SqliteValueBinder.cs index 688b2a663c3..7f234dc7d02 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteValueBinder.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteValueBinder.cs @@ -206,28 +206,28 @@ public virtual void Bind() } private static readonly Dictionary _sqliteTypeMapping = - new Dictionary() + new Dictionary { - {typeof(bool), SqliteType.Integer}, - {typeof(byte),SqliteType.Integer}, - {typeof(byte[]), SqliteType.Blob}, - {typeof(char),SqliteType.Integer}, - {typeof(DateTime), SqliteType.Text}, - {typeof(DateTimeOffset), SqliteType.Text}, - {typeof(DBNull), SqliteType.Text}, - {typeof(decimal),SqliteType.Text}, - {typeof(double), SqliteType.Real}, - {typeof(float), SqliteType.Real}, - {typeof(Guid), SqliteType.Blob}, - {typeof(int), SqliteType.Integer}, - {typeof(long), SqliteType.Integer}, - {typeof(sbyte),SqliteType.Integer}, - {typeof(short), SqliteType.Integer}, - {typeof(string), SqliteType.Integer}, - {typeof(TimeSpan), SqliteType.Text}, - {typeof(uint), SqliteType.Integer}, - {typeof(ulong), SqliteType.Integer}, - {typeof(ushort), SqliteType.Integer}, + { typeof(bool), SqliteType.Integer }, + { typeof(byte), SqliteType.Integer }, + { typeof(byte[]), SqliteType.Blob }, + { typeof(char), SqliteType.Integer }, + { typeof(DateTime), SqliteType.Text }, + { typeof(DateTimeOffset), SqliteType.Text }, + { typeof(DBNull), SqliteType.Text }, + { typeof(decimal), SqliteType.Text }, + { typeof(double), SqliteType.Real }, + { typeof(float), SqliteType.Real }, + { typeof(Guid), SqliteType.Blob }, + { typeof(int), SqliteType.Integer }, + { typeof(long), SqliteType.Integer }, + { typeof(sbyte), SqliteType.Integer }, + { typeof(short), SqliteType.Integer }, + { typeof(string), SqliteType.Integer }, + { typeof(TimeSpan), SqliteType.Text }, + { typeof(uint), SqliteType.Integer }, + { typeof(ulong), SqliteType.Integer }, + { typeof(ushort), SqliteType.Integer } }; internal static SqliteType GetSqliteType(object value) @@ -242,10 +242,8 @@ internal static SqliteType GetSqliteType(object value) { return sqliteType; } - else - { - throw new InvalidOperationException(Resources.UnknownDataType(type)); - } + + throw new InvalidOperationException(Resources.UnknownDataType(type)); } private static double ToJulianDate(DateTime dateTime) diff --git a/src/Microsoft.Data.Sqlite.Core/SqliteValueReader.cs b/src/Microsoft.Data.Sqlite.Core/SqliteValueReader.cs index 7096b5f59db..ae349afe99f 100644 --- a/src/Microsoft.Data.Sqlite.Core/SqliteValueReader.cs +++ b/src/Microsoft.Data.Sqlite.Core/SqliteValueReader.cs @@ -143,79 +143,98 @@ public virtual T GetFieldValue(int ordinal) { return (T)(object)GetBoolean(ordinal); } + if (type == typeof(byte)) { return (T)(object)GetByte(ordinal); } + if (type == typeof(byte[])) { return (T)(object)GetBlob(ordinal); } + if (type == typeof(char)) { return (T)(object)GetChar(ordinal); } + if (type == typeof(DateTime)) { return (T)(object)GetDateTime(ordinal); } + if (type == typeof(DateTimeOffset)) { return (T)(object)GetDateTimeOffset(ordinal); } + if (type == typeof(DBNull)) { // NB: NULL values handled above throw new InvalidCastException(); } + if (type == typeof(decimal)) { return (T)(object)GetDecimal(ordinal); } + if (type == typeof(double)) { return (T)(object)GetDouble(ordinal); } + if (type == typeof(float)) { return (T)(object)GetFloat(ordinal); } + if (type == typeof(Guid)) { return (T)(object)GetGuid(ordinal); } + if (type == typeof(int)) { return (T)(object)GetInt32(ordinal); } + if (type == typeof(long)) { return (T)(object)GetInt64(ordinal); } + if (type == typeof(sbyte)) { return (T)(object)((sbyte)GetInt64(ordinal)); } + if (type == typeof(short)) { return (T)(object)GetInt16(ordinal); } + if (type == typeof(string)) { return (T)(object)GetString(ordinal); } + if (type == typeof(TimeSpan)) { return (T)(object)GetTimeSpan(ordinal); } + if (type == typeof(uint)) { return (T)(object)((uint)GetInt64(ordinal)); } + if (type == typeof(ulong)) { return (T)(object)((ulong)GetInt64(ordinal)); } + if (type == typeof(ushort)) { return (T)(object)((ushort)GetInt64(ordinal)); diff --git a/src/Shared/CodeAnnotations.cs b/src/Shared/CodeAnnotations.cs index 3644f2d10b4..6ddac8cd76b 100644 --- a/src/Shared/CodeAnnotations.cs +++ b/src/Shared/CodeAnnotations.cs @@ -6,16 +6,20 @@ namespace JetBrains.Annotations { [AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter - | AttributeTargets.Property | AttributeTargets.Delegate + AttributeTargets.Method + | AttributeTargets.Parameter + | AttributeTargets.Property + | AttributeTargets.Delegate | AttributeTargets.Field)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter - | AttributeTargets.Property | AttributeTargets.Delegate + AttributeTargets.Method + | AttributeTargets.Parameter + | AttributeTargets.Property + | AttributeTargets.Delegate | AttributeTargets.Field)] internal sealed class CanBeNullAttribute : Attribute { diff --git a/src/Shared/MemberInfoExtensions.cs b/src/Shared/MemberInfoExtensions.cs index c281eff37c4..b1b6d004c14 100644 --- a/src/Shared/MemberInfoExtensions.cs +++ b/src/Shared/MemberInfoExtensions.cs @@ -35,10 +35,12 @@ public static MemberInfo OnInterface(this MemberInfo targetMember, Type interfac { return targetMember; } + if (targetMember is MethodInfo targetMethod) { return targetMethod.OnInterface(interfaceType); } + if (targetMember is PropertyInfo targetProperty) { var targetGetMethod = targetProperty.GetMethod; diff --git a/src/Shared/SharedTypeExtensions.cs b/src/Shared/SharedTypeExtensions.cs index 27ab1500e1b..29a6cb33677 100644 --- a/src/Shared/SharedTypeExtensions.cs +++ b/src/Shared/SharedTypeExtensions.cs @@ -39,9 +39,9 @@ public static bool IsNumeric(this Type type) type = type.UnwrapNullableType(); return type.IsInteger() - || type == typeof(decimal) - || type == typeof(float) - || type == typeof(double); + || type == typeof(decimal) + || type == typeof(float) + || type == typeof(double); } public static bool IsInteger(this Type type) @@ -61,9 +61,9 @@ public static bool IsInteger(this Type type) public static bool IsSignedInteger(this Type type) => type == typeof(int) - || type == typeof(long) - || type == typeof(short) - || type == typeof(sbyte); + || type == typeof(long) + || type == typeof(short) + || type == typeof(sbyte); public static bool IsAnonymousType(this Type type) => type.Name.StartsWith("<>") diff --git a/test/EFCore.Cosmos.FunctionalTests/Internal/CosmosDatabaseCreatorTest.cs b/test/EFCore.Cosmos.FunctionalTests/Internal/CosmosDatabaseCreatorTest.cs index 563fbe1b911..282fa2186f3 100644 --- a/test/EFCore.Cosmos.FunctionalTests/Internal/CosmosDatabaseCreatorTest.cs +++ b/test/EFCore.Cosmos.FunctionalTests/Internal/CosmosDatabaseCreatorTest.cs @@ -15,7 +15,7 @@ public class CosmosDatabaseCreatorTest { [ConditionalTheory] [InlineData(true)] - //[InlineData(false)] + [InlineData(false)] public async Task EnsureCreated_returns_true_when_database_does_not_exist(bool async) { using (var testDatabase = CosmosTestStore.Create("NonExisting")) @@ -31,7 +31,7 @@ public async Task EnsureCreated_returns_true_when_database_does_not_exist(bool a [ConditionalTheory] [InlineData(true)] - //[InlineData(false)] + [InlineData(false)] public async Task EnsureCreated_returns_true_when_database_exists_but_collections_does_not(bool async) { using (var testDatabase = CosmosTestStore.CreateInitialized("EnsureCreatedTest")) @@ -45,8 +45,8 @@ public async Task EnsureCreated_returns_true_when_database_exists_but_collection } } - [ConditionalTheory] - [InlineData(true)] + //[ConditionalTheory] + //[InlineData(true)] //[InlineData(false)] public async Task EnsureCreated_returns_false_when_database_and_collections_exists(bool async) { @@ -65,7 +65,7 @@ public async Task EnsureCreated_returns_false_when_database_and_collections_exis [ConditionalTheory] [InlineData(true)] - //[InlineData(false)] + [InlineData(false)] public async Task EnsureDeleted_returns_true_when_database_exists(bool async) { using (var testDatabase = CosmosTestStore.CreateInitialized("EnsureDeleteBlogging")) @@ -79,8 +79,8 @@ public async Task EnsureDeleted_returns_true_when_database_exists(bool async) } } - [ConditionalTheory] - [InlineData(true)] + //[ConditionalTheory] + //[InlineData(true)] //[InlineData(false)] public async Task EnsureDeleted_returns_false_when_database_does_not_exist(bool async) {