From 027962ea1cc5517f4db5fd2a97f46e1962bc07ee Mon Sep 17 00:00:00 2001 From: Steve Smith Date: Tue, 18 Jan 2022 16:52:15 -0500 Subject: [PATCH] Adding and Applying EditorConfig (#226) * Adding editorconfig * apply formatting rules * adding documentationfiles * Enabled XML comments for Ardalis.Specification project. Co-authored-by: Fati Iseni --- .editorconfig | 126 +++ Ardalis.Specification.sln | 1 + ...alis.Specification.EntityFramework6.csproj | 1 + .../Evaluators/AsNoTrackingEvaluator.cs | 28 +- .../Evaluators/IncludeEvaluator.cs | 54 +- .../Evaluators/OrderEvaluator.cs | 164 ++-- .../Evaluators/SearchEvaluator.cs | 26 +- .../Evaluators/SpecificationEvaluator.cs | 86 +- .../Extensions/DbSetExtensions.cs | 42 +- .../Extensions/IncludeExtensions.cs | 86 +- .../Extensions/ParameterReplacerVisitor.cs | 50 +- .../Extensions/SearchExtension.cs | 76 +- .../RepositoryBaseOfT.cs | 278 +++--- .../Configurations/AddressConfiguration.cs | 18 +- .../Configurations/CompanyConfiguration.cs | 28 +- .../Configurations/CountryConfiguration.cs | 18 +- .../Configurations/ProductConfiguration.cs | 18 +- .../Configurations/StoreConfiguration.cs | 22 +- .../Fixture/DbInitializer.cs | 32 +- .../Fixture/IntegrationTestBase.cs | 24 +- .../Fixture/RepositoryOfT.cs | 18 +- .../Fixture/SharedDatabaseFixture.cs | 64 +- .../Fixture/TestDbContext.cs | 52 +- .../RepositoryOfT_AnyAsync.cs | 46 +- .../RepositoryOfT_GetById.cs | 40 +- .../RepositoryOfT_GetBySpec.cs | 192 ++-- .../RepositoryOfT_ListAsync.cs | 288 +++--- ...s.Specification.EntityFrameworkCore.csproj | 1 + .../CachedReadConcurrentDictionary.cs | 392 ++++---- .../Evaluators/AsNoTrackingEvaluator.cs | 30 +- ...TrackingWithIdentityResolutionEvaluator.cs | 30 +- .../Evaluators/AsSplitQueryEvaluator.cs | 30 +- .../Evaluators/IgnoreQueryFiltersEvaluator.cs | 38 +- .../Evaluators/IncludeEvaluator.cs | 304 +++--- .../Evaluators/SearchEvaluator.cs | 26 +- .../Evaluators/SpecificationEvaluator.cs | 84 +- .../Extensions/DbSetExtensions.cs | 44 +- .../Extensions/ParameterReplacerVisitor.cs | 50 +- .../Extensions/SearchExtension.cs | 94 +- .../RepositoryBaseOfT.cs | 278 +++--- .../Fixture/IntegrationTestBase.cs | 22 +- .../Fixture/LoggerFactoryProvider.cs | 18 +- .../Fixture/RepositoryOfT.cs | 16 +- .../Fixture/SharedDatabaseFixture.cs | 134 +-- .../Fixture/TestDbContext.cs | 58 +- .../RepositoryOfT_AnyAsync.cs | 58 +- .../RepositoryOfT_GetById.cs | 50 +- .../RepositoryOfT_GetBySpec.cs | 196 ++-- .../RepositoryOfT_ListAsync.cs | 288 +++--- .../Ardalis.Specification.csproj | 1 + .../Builder/CacheSpecificationBuilder.cs | 26 +- .../Builder/ICacheSpecificationBuilder.cs | 8 +- .../IIncludableSpecificationBuilder.cs | 8 +- .../Builder/IOrderedSpecificationBuilder.cs | 8 +- .../Builder/ISpecificationBuilder.cs | 16 +- .../Builder/IncludableBuilderExtensions.cs | 96 +- .../Builder/IncludableSpecificationBuilder.cs | 26 +- .../Builder/OrderedBuilderExtensions.cs | 80 +- .../Builder/OrderedSpecificationBuilder.cs | 26 +- .../Builder/SpecificationBuilder.cs | 30 +- .../Builder/SpecificationBuilderExtensions.cs | 884 +++++++++--------- .../Evaluators/IEvaluator.cs | 10 +- .../Evaluators/IInMemoryEvaluator.cs | 8 +- .../IInMemorySpecificationEvaluator.cs | 10 +- .../Evaluators/ISpecificationEvaluator.cs | 40 +- .../InMemorySpecificationEvaluator.cs | 80 +- .../Evaluators/OrderEvaluator.cs | 152 +-- .../Evaluators/PaginationEvaluator.cs | 72 +- .../Evaluators/SearchEvaluator.cs | 24 +- .../Evaluators/SearchExtension.cs | 268 +++--- .../Evaluators/WhereEvaluator.cs | 42 +- .../DuplicateOrderChainException.cs | 22 +- .../Exceptions/DuplicateSkipException.cs | 22 +- .../Exceptions/DuplicateTakeException.cs | 22 +- .../InvalidSearchPatternException.cs | 22 +- .../Exceptions/SelectorNotFoundException.cs | 22 +- .../Expressions/IncludeExpressionInfo.cs | 142 +-- .../Expressions/OrderExpressionInfo.cs | 62 +- .../Expressions/SearchExpressionInfo.cs | 88 +- .../Expressions/WhereExpressionInfo.cs | 50 +- .../src/Ardalis.Specification/IEntity.cs | 10 +- .../IReadRepositoryBase.cs | 210 ++--- .../IRepositoryBaseOfT.cs | 80 +- .../ISingleResultSpecification.cs | 14 +- .../ISingleResultSpecificationOfT.cs | 6 +- .../Ardalis.Specification/ISpecification.cs | 256 ++--- .../Ardalis.Specification/IncludeTypeEnum.cs | 10 +- .../Ardalis.Specification/OrderTypeEnum.cs | 20 +- .../Ardalis.Specification/Specification.cs | 168 ++-- .../Validators/ISpecificationValidator.cs | 8 +- .../Validators/IValidator.cs | 8 +- .../Validators/SearchValidator.cs | 24 +- .../Validators/SpecificationValidator.cs | 46 +- .../Validators/WhereValidator.cs | 24 +- ...IncludableBuilderExtensions_ThenInclude.cs | 64 +- .../OrderedBuilderExtensions_ThenBy.cs | 58 +- ...deredBuilderExtensions_ThenByDescending.cs | 58 +- ...ificationBuilderExtensions_AsNoTracking.cs | 38 +- ...ions_AsNoTrackingWithIdentityResolution.cs | 38 +- ...ificationBuilderExtensions_AsSplitQuery.cs | 38 +- ...ionBuilderExtensions_IgnoreQueryFilters.cs | 38 +- .../SpecificationBuilderExtensions_Include.cs | 48 +- ...ficationBuilderExtensions_IncludeString.cs | 50 +- .../SpecificationBuilderExtensions_OrderBy.cs | 48 +- ...tionBuilderExtensions_OrderByDescending.cs | 48 +- ...nBuilderExtensions_PostProcessingAction.cs | 58 +- .../SpecificationBuilderExtensions_Search.cs | 88 +- .../SpecificationBuilderExtensions_Select.cs | 34 +- .../SpecificationBuilderExtensions_Skip.cs | 52 +- .../SpecificationBuilderExtensions_Take.cs | 50 +- .../SpecificationBuilderExtensions_Where.cs | 58 +- .../InMemorySpecificationEvaluatorTests.cs | 218 ++--- .../SearchEvaluator_Evaluate.cs | 58 +- .../EvaluatorTests/SearchExtension_Like.cs | 168 ++-- .../DuplicateOrderChainExceptionTests.cs | 36 +- .../DuplicateSkipExceptionTests.cs | 36 +- .../DuplicateTakeExceptionTests.cs | 36 +- .../InvalidSearchPatternExceptionTests.cs | 38 +- .../SelectorNotFoundExceptionTests.cs | 36 +- .../Fixture/Entities/Address.cs | 20 +- .../Fixture/Entities/Company.cs | 16 +- .../Fixture/Entities/Country.cs | 12 +- .../Fixture/Entities/Product.cs | 14 +- .../Fixture/Entities/Seeds/AddressSeed.cs | 32 +- .../Fixture/Entities/Seeds/CompanySeed.cs | 54 +- .../Fixture/Entities/Seeds/CountrySeed.cs | 32 +- .../Fixture/Entities/Seeds/ProductSeed.cs | 42 +- .../Fixture/Entities/Seeds/StoreSeed.cs | 114 +-- .../Fixture/Entities/Store.cs | 28 +- .../Fixture/Specs/CompanyByIdAsSplitQuery.cs | 16 +- .../Specs/CompanyByIdAsUntrackedSpec.cs | 10 +- ...IdAsUntrackedWithIdentityResolutionSpec.cs | 10 +- .../Specs/CompanyByIdIgnoreQueryFilters.cs | 10 +- ...ByIdIncludeStoresThenIncludeAddressSpec.cs | 16 +- ...yIdIncludeStoresThenIncludeProductsSpec.cs | 14 +- .../Fixture/Specs/CompanyByIdSpec.cs | 10 +- .../Specs/CompanyByIdWithFalseConditions.cs | 44 +- ...nyByIdWithFalseConditionsForInnerChains.cs | 46 +- .../Fixture/Specs/StoreByIdAndNameSpec.cs | 12 +- .../StoreByIdIncludeAddressAndProductsSpec.cs | 14 +- .../Specs/StoreByIdIncludeAddressSpec.cs | 14 +- ...ompanyAndCountryAndStoresForCompanySpec.cs | 14 +- .../Specs/StoreByIdIncludeProductsSpec.cs | 14 +- ...StoreByIdIncludeProductsUsingStringSpec.cs | 14 +- .../Specs/StoreByIdSearchByNameAndCitySpec.cs | 14 +- .../Specs/StoreByIdSearchByNameOrCitySpec.cs | 14 +- .../Fixture/Specs/StoreByIdSpec.cs | 10 +- .../Fixture/Specs/StoreDuplicateSkipSpec.cs | 14 +- .../Fixture/Specs/StoreDuplicateTakeSpec.cs | 14 +- .../Fixture/Specs/StoreEmptySpec.cs | 8 +- .../Fixture/Specs/StoreNamesEmptySpec.cs | 8 +- .../Fixture/Specs/StoreNamesPaginatedSpec.cs | 18 +- .../Fixture/Specs/StoreNamesSpec.cs | 12 +- .../StoreNamesWithPostProcessingActionSpec.cs | 14 +- .../Specs/StoreSearchByNameAndCitySpec.cs | 12 +- .../Specs/StoreSearchByNameOrCitySpec.cs | 12 +- .../Fixture/Specs/StoreSearchByNameSpec.cs | 10 +- .../StoreWithPostProcessingActionSpec.cs | 12 +- .../StoresByCompanyOrderedDescByNameSpec.cs | 14 +- ...ompanyOrderedDescByNameThenByDescIdSpec.cs | 16 +- ...sByCompanyOrderedDescByNameThenByIdSpec.cs | 16 +- ...ByCompanyPaginatedOrderedDescByNameSpec.cs | 22 +- .../Specs/StoresByCompanyPaginatedSpec.cs | 18 +- .../Fixture/Specs/StoresByIdListSpec.cs | 14 +- .../StoresOrderedDescendingByNameSpec.cs | 12 +- .../Fixture/Specs/StoresOrderedSpecByName.cs | 12 +- .../Specs/StoresOrderedTwoChainsSpec.cs | 14 +- .../Fixture/Specs/StoresPaginatedSpec.cs | 16 +- .../CompanyIncludeFilteredStoresSpec.cs | 18 +- .../StoreIncludeAddressAndProductsSpec.cs | 16 +- .../StoreIncludeAddressSpec.cs | 16 +- ...reIncludeCompanyCountryDotSeparatedSpec.cs | 16 +- ...reIncludeCompanyThenCountryAsStringSpec.cs | 14 +- .../StoreIncludeCompanyThenCountrySpec.cs | 16 +- .../StoreIncludeCompanyThenNameSpec.cs | 16 +- .../StoreIncludeCompanyThenStoresSpec.cs | 14 +- .../StoreIncludeMethodOfNavigationSpec.cs | 16 +- .../StoreIncludeMethodSpec.cs | 16 +- .../StoreIncludeNameSpec.cs | 14 +- .../StoreIncludeProductsSpec.cs | 14 +- .../StoreWithFaultyIncludeSpec.cs | 16 +- .../IncludeExpressionInfoTests.cs | 92 +- .../SpecificationValidator_Tests.cs | 124 +-- .../Entities/CustomerAggregate/Customer.cs | 68 +- .../Entities/CustomerAggregate/Store.cs | 24 +- .../Entities/Seeds/CustomerSeed.cs | 26 +- .../Interfaces/IAggregateRoot.cs | 6 +- .../Interfaces/ICustomerRepository.cs | 14 +- .../Interfaces/IRepository.cs | 16 +- .../Specifications/CustomerByNameSpec.cs | 14 +- .../CustomerByNameWithStoresSpec.cs | 14 +- .../Specifications/CustomerSpec.cs | 34 +- .../Specifications/Filters/BaseFilter.cs | 14 +- .../Specifications/Filters/CustomerFilter.cs | 12 +- .../Specifications/PaginationHelper.cs | 42 +- .../Data/CachedCustomerRepository.cs | 219 +++-- .../Data/CustomerRepository.cs | 43 +- .../Data/MyRepository.cs | 25 +- .../Configurations/CustomerConfiguration.cs | 29 +- .../Configurations/StoreConfiguration.cs | 25 +- .../DataAccess/SampleDbContext.cs | 33 +- .../DataAccess/SampleDbContextSeed.cs | 63 +- .../Migrations/20201102224526_SampleDB-v1.cs | 101 +- .../Ardalis.SampleApp.Web/AutomapperMaps.cs | 31 +- .../Controllers/CustomersController.cs | 79 +- .../Interfaces/ICustomerUiService.cs | 19 +- .../Models/BaseFilterDto.cs | 23 +- .../Models/CustomerDto.cs | 17 +- .../Models/CustomerFilterDto.cs | 13 +- .../Ardalis.SampleApp.Web/Models/StoreDto.cs | 13 +- .../Pages/Index.cshtml.cs | 45 +- sample/Ardalis.SampleApp.Web/Program.cs | 59 +- .../Services/CustomerUiService.cs | 87 +- sample/Ardalis.SampleApp.Web/Startup.cs | 75 +- 214 files changed, 5808 insertions(+), 5703 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..0ee58191 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,126 @@ +# To learn more about .editorconfig see https://aka.ms/editorconfigdocs +############################### +# Core EditorConfig Options # +############################### +# All files +[*] +indent_style = space +# Code files +[*.{cs,csx,vb,vbx}] +indent_size =2 +insert_final_newline = true +charset = utf-8-bom +############################### +# .NET Coding Conventions # +############################### +[*.{cs,vb}] +# Organize usings +dotnet_sort_system_directives_first = true +# this. preferences +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_property = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_event = false:silent +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true:silent +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent +dotnet_style_readonly_field = true:suggestion +# Expression-level preferences +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +# Namespace preferences +csharp_style_namespace_declarations = file_scoped:warning +############################### +# Naming Conventions # +############################### +# Style Definitions +dotnet_naming_style.pascal_case_style.capitalization = pascal_case +# Use PascalCase for constant fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style +dotnet_naming_symbols.constant_fields.applicable_kinds = field +dotnet_naming_symbols.constant_fields.applicable_accessibilities = * +dotnet_naming_symbols.constant_fields.required_modifiers = const +tab_width=2 +############################### +# C# Coding Conventions # +############################### +[*.cs] +# var preferences +csharp_style_var_for_built_in_types = true:silent +csharp_style_var_when_type_is_apparent = true:silent +csharp_style_var_elsewhere = true:silent +# Expression-bodied members +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +# Pattern matching preferences +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +# Null-checking preferences +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion +# Modifier preferences +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion +# Expression-level preferences +csharp_prefer_braces = true:silent +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_pattern_local_over_anonymous_function = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +############################### +# C# Formatting Rules # +############################### +# New line preferences +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true +# Indentation preferences +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left +# Space preferences +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_around_binary_operators = before_and_after +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +# Wrapping preferences +csharp_preserve_single_line_statements = true +csharp_preserve_single_line_blocks = true +############################### +# VB Coding Conventions # +############################### +[*.vb] +# Modifier preferences +visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:suggestion diff --git a/Ardalis.Specification.sln b/Ardalis.Specification.sln index 5e9f766b..01b56ed9 100644 --- a/Ardalis.Specification.sln +++ b/Ardalis.Specification.sln @@ -28,6 +28,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docker", "Docker", "{A74A4C EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Solution Items", "_Solution Items", "{C443291A-7311-455F-9AC6-995EB29DD6D2}" ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig README.md = README.md EndProjectSection EndProject diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Ardalis.Specification.EntityFramework6.csproj b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Ardalis.Specification.EntityFramework6.csproj index 7b7ee81c..b0e65a48 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Ardalis.Specification.EntityFramework6.csproj +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Ardalis.Specification.EntityFramework6.csproj @@ -23,6 +23,7 @@ true true $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + bin\$(Configuration)\Ardalis.Specification.EntityFramework6.xml diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/AsNoTrackingEvaluator.cs b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/AsNoTrackingEvaluator.cs index 5e6a29c6..ffccb719 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/AsNoTrackingEvaluator.cs +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/AsNoTrackingEvaluator.cs @@ -3,21 +3,21 @@ namespace Ardalis.Specification.EntityFramework6 { - public class AsNoTrackingEvaluator : IEvaluator - { - private AsNoTrackingEvaluator() { } - public static AsNoTrackingEvaluator Instance { get; } = new AsNoTrackingEvaluator(); + public class AsNoTrackingEvaluator : IEvaluator + { + private AsNoTrackingEvaluator() { } + public static AsNoTrackingEvaluator Instance { get; } = new AsNoTrackingEvaluator(); - public bool IsCriteriaEvaluator { get; } = true; + public bool IsCriteriaEvaluator { get; } = true; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - if (specification.AsNoTracking) - { - query = query.AsNoTracking(); - } + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + if (specification.AsNoTracking) + { + query = query.AsNoTracking(); + } - return query; - } + return query; } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/IncludeEvaluator.cs b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/IncludeEvaluator.cs index 9152ec69..50734215 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/IncludeEvaluator.cs +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/IncludeEvaluator.cs @@ -1,35 +1,35 @@ -using System.Linq; -using System.Data.Entity; +using System.Data.Entity; +using System.Linq; namespace Ardalis.Specification.EntityFramework6 { - public class IncludeEvaluator : IEvaluator - { - private IncludeEvaluator() { } - public static IncludeEvaluator Instance { get; } = new IncludeEvaluator(); - - public bool IsCriteriaEvaluator { get; } = false; + public class IncludeEvaluator : IEvaluator + { + private IncludeEvaluator() { } + public static IncludeEvaluator Instance { get; } = new IncludeEvaluator(); - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - foreach (var includeString in specification.IncludeStrings) - { - query = query.Include(includeString); - } + public bool IsCriteriaEvaluator { get; } = false; - foreach (var includeInfo in specification.IncludeExpressions) - { - if (includeInfo.Type == IncludeTypeEnum.Include) - { - query = query.Include(includeInfo); - } - else if (includeInfo.Type == IncludeTypeEnum.ThenInclude) - { - query = query.ThenInclude(includeInfo); - } - } + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + foreach (var includeString in specification.IncludeStrings) + { + query = query.Include(includeString); + } - return query; + foreach (var includeInfo in specification.IncludeExpressions) + { + if (includeInfo.Type == IncludeTypeEnum.Include) + { + query = query.Include(includeInfo); + } + else if (includeInfo.Type == IncludeTypeEnum.ThenInclude) + { + query = query.ThenInclude(includeInfo); } + } + + return query; } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/OrderEvaluator.cs b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/OrderEvaluator.cs index 0979bff7..5f4a328e 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/OrderEvaluator.cs +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/OrderEvaluator.cs @@ -4,100 +4,100 @@ namespace Ardalis.Specification.EntityFramework6 { - public class OrderEvaluator : IEvaluator, IInMemoryEvaluator - { - private OrderEvaluator() { } - public static OrderEvaluator Instance { get; } = new OrderEvaluator(); + public class OrderEvaluator : IEvaluator, IInMemoryEvaluator + { + private OrderEvaluator() { } + public static OrderEvaluator Instance { get; } = new OrderEvaluator(); - public bool IsCriteriaEvaluator { get; } = false; + public bool IsCriteriaEvaluator { get; } = false; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + if (specification.OrderExpressions != null) + { + if (specification.OrderExpressions.Count(x => x.OrderType == OrderTypeEnum.OrderBy + || x.OrderType == OrderTypeEnum.OrderByDescending) > 1) { - if (specification.OrderExpressions != null) - { - if (specification.OrderExpressions.Count(x => x.OrderType == OrderTypeEnum.OrderBy - || x.OrderType == OrderTypeEnum.OrderByDescending) > 1) - { - throw new DuplicateOrderChainException(); - } - - IOrderedQueryable orderedQuery = null; - foreach (var orderExpression in specification.OrderExpressions) - { - if (orderExpression.OrderType == OrderTypeEnum.OrderBy) - { - orderedQuery = Queryable.OrderBy((dynamic)query, (dynamic)RemoveConvert(orderExpression.KeySelector)); - } - else if (orderExpression.OrderType == OrderTypeEnum.OrderByDescending) - { - orderedQuery = Queryable.OrderByDescending((dynamic)query, (dynamic)RemoveConvert(orderExpression.KeySelector)); - } - else if (orderExpression.OrderType == OrderTypeEnum.ThenBy) - { - orderedQuery = Queryable.ThenBy((dynamic)orderedQuery, (dynamic)RemoveConvert(orderExpression.KeySelector)); - } - else if (orderExpression.OrderType == OrderTypeEnum.ThenByDescending) - { - orderedQuery = Queryable.ThenByDescending((dynamic)orderedQuery, (dynamic)RemoveConvert(orderExpression.KeySelector)); - } - } - - if (orderedQuery != null) - { - query = orderedQuery; - } - } - - return query; + throw new DuplicateOrderChainException(); } - public IEnumerable Evaluate(IEnumerable query, ISpecification specification) + IOrderedQueryable orderedQuery = null; + foreach (var orderExpression in specification.OrderExpressions) { - if (specification.OrderExpressions != null) - { - if (specification.OrderExpressions.Count(x => x.OrderType == OrderTypeEnum.OrderBy - || x.OrderType == OrderTypeEnum.OrderByDescending) > 1) - { - throw new DuplicateOrderChainException(); - } + if (orderExpression.OrderType == OrderTypeEnum.OrderBy) + { + orderedQuery = Queryable.OrderBy((dynamic)query, (dynamic)RemoveConvert(orderExpression.KeySelector)); + } + else if (orderExpression.OrderType == OrderTypeEnum.OrderByDescending) + { + orderedQuery = Queryable.OrderByDescending((dynamic)query, (dynamic)RemoveConvert(orderExpression.KeySelector)); + } + else if (orderExpression.OrderType == OrderTypeEnum.ThenBy) + { + orderedQuery = Queryable.ThenBy((dynamic)orderedQuery, (dynamic)RemoveConvert(orderExpression.KeySelector)); + } + else if (orderExpression.OrderType == OrderTypeEnum.ThenByDescending) + { + orderedQuery = Queryable.ThenByDescending((dynamic)orderedQuery, (dynamic)RemoveConvert(orderExpression.KeySelector)); + } + } - IOrderedEnumerable orderedQuery = null; - foreach (var orderExpression in specification.OrderExpressions) - { - if (orderExpression.OrderType == OrderTypeEnum.OrderBy) - { - orderedQuery = Queryable.OrderBy((dynamic)query, (dynamic)RemoveConvert(orderExpression.KeySelector)); - } - else if (orderExpression.OrderType == OrderTypeEnum.OrderByDescending) - { - orderedQuery = Queryable.OrderByDescending((dynamic)query, (dynamic)RemoveConvert(orderExpression.KeySelector)); - } - else if (orderExpression.OrderType == OrderTypeEnum.ThenBy) - { - orderedQuery = Queryable.ThenBy((dynamic)orderedQuery, (dynamic)RemoveConvert(orderExpression.KeySelector)); - } - else if (orderExpression.OrderType == OrderTypeEnum.ThenByDescending) - { - orderedQuery = Queryable.ThenByDescending((dynamic)orderedQuery, (dynamic)RemoveConvert(orderExpression.KeySelector)); - } - } + if (orderedQuery != null) + { + query = orderedQuery; + } + } - if (orderedQuery != null) - { - query = orderedQuery; - } - } + return query; + } - return query; + public IEnumerable Evaluate(IEnumerable query, ISpecification specification) + { + if (specification.OrderExpressions != null) + { + if (specification.OrderExpressions.Count(x => x.OrderType == OrderTypeEnum.OrderBy + || x.OrderType == OrderTypeEnum.OrderByDescending) > 1) + { + throw new DuplicateOrderChainException(); } - private LambdaExpression RemoveConvert(LambdaExpression source) + IOrderedEnumerable orderedQuery = null; + foreach (var orderExpression in specification.OrderExpressions) { - var body = source.Body; - while (body.NodeType == ExpressionType.Convert) - body = ((UnaryExpression)body).Operand; + if (orderExpression.OrderType == OrderTypeEnum.OrderBy) + { + orderedQuery = Queryable.OrderBy((dynamic)query, (dynamic)RemoveConvert(orderExpression.KeySelector)); + } + else if (orderExpression.OrderType == OrderTypeEnum.OrderByDescending) + { + orderedQuery = Queryable.OrderByDescending((dynamic)query, (dynamic)RemoveConvert(orderExpression.KeySelector)); + } + else if (orderExpression.OrderType == OrderTypeEnum.ThenBy) + { + orderedQuery = Queryable.ThenBy((dynamic)orderedQuery, (dynamic)RemoveConvert(orderExpression.KeySelector)); + } + else if (orderExpression.OrderType == OrderTypeEnum.ThenByDescending) + { + orderedQuery = Queryable.ThenByDescending((dynamic)orderedQuery, (dynamic)RemoveConvert(orderExpression.KeySelector)); + } + } - return Expression.Lambda(body, source.Parameters); + if (orderedQuery != null) + { + query = orderedQuery; } + } + + return query; + } + + private LambdaExpression RemoveConvert(LambdaExpression source) + { + var body = source.Body; + while (body.NodeType == ExpressionType.Convert) + body = ((UnaryExpression)body).Operand; + + return Expression.Lambda(body, source.Parameters); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/SearchEvaluator.cs b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/SearchEvaluator.cs index df77ee79..67d8ddda 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/SearchEvaluator.cs +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/SearchEvaluator.cs @@ -2,21 +2,21 @@ namespace Ardalis.Specification.EntityFramework6 { - public class SearchEvaluator : IEvaluator - { - private SearchEvaluator() { } - public static SearchEvaluator Instance { get; } = new SearchEvaluator(); + public class SearchEvaluator : IEvaluator + { + private SearchEvaluator() { } + public static SearchEvaluator Instance { get; } = new SearchEvaluator(); - public bool IsCriteriaEvaluator { get; } = true; + public bool IsCriteriaEvaluator { get; } = true; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - foreach (var searchCriteria in specification.SearchCriterias.GroupBy(x => x.SearchGroup)) - { - query = query.Search(searchCriteria); - } + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + foreach (var searchCriteria in specification.SearchCriterias.GroupBy(x => x.SearchGroup)) + { + query = query.Search(searchCriteria); + } - return query; - } + return query; } + } } diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/SpecificationEvaluator.cs b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/SpecificationEvaluator.cs index dad9f2aa..4e2ba08b 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/SpecificationEvaluator.cs +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Evaluators/SpecificationEvaluator.cs @@ -4,55 +4,55 @@ namespace Ardalis.Specification.EntityFramework6 { - /// - public class SpecificationEvaluator : ISpecificationEvaluator - { - // Will use singleton for default configuration. Yet, it can be instantiated if necessary, with default or provided evaluators. - public static SpecificationEvaluator Default { get; } = new SpecificationEvaluator(); + /// + public class SpecificationEvaluator : ISpecificationEvaluator + { + // Will use singleton for default configuration. Yet, it can be instantiated if necessary, with default or provided evaluators. + public static SpecificationEvaluator Default { get; } = new SpecificationEvaluator(); - private readonly List evaluators = new List(); + private readonly List evaluators = new List(); - public SpecificationEvaluator() - { - this.evaluators.AddRange(new IEvaluator[] - { + public SpecificationEvaluator() + { + this.evaluators.AddRange(new IEvaluator[] + { WhereEvaluator.Instance, SearchEvaluator.Instance, IncludeEvaluator.Instance, OrderEvaluator.Instance, PaginationEvaluator.Instance, AsNoTrackingEvaluator.Instance - }); - } - public SpecificationEvaluator(IEnumerable evaluators) - { - this.evaluators.AddRange(evaluators); - } - - /// - public virtual IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - if (specification is null) throw new ArgumentNullException("Specification is required"); - if (specification.Selector is null) throw new SelectorNotFoundException(); - - query = GetQuery(query, (ISpecification)specification); - - return query.Select(specification.Selector); - } - - /// - public virtual IQueryable GetQuery(IQueryable query, ISpecification specification, bool evaluateCriteriaOnly = false) where T : class - { - if (specification is null) throw new ArgumentNullException("Specification is required"); - - var evaluators = evaluateCriteriaOnly ? this.evaluators.Where(x => x.IsCriteriaEvaluator) : this.evaluators; - - foreach (var evaluator in evaluators) - { - query = evaluator.GetQuery(query, specification); - } - - return query; - } + }); + } + public SpecificationEvaluator(IEnumerable evaluators) + { + this.evaluators.AddRange(evaluators); + } + + /// + public virtual IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + if (specification is null) throw new ArgumentNullException("Specification is required"); + if (specification.Selector is null) throw new SelectorNotFoundException(); + + query = GetQuery(query, (ISpecification)specification); + + return query.Select(specification.Selector); + } + + /// + public virtual IQueryable GetQuery(IQueryable query, ISpecification specification, bool evaluateCriteriaOnly = false) where T : class + { + if (specification is null) throw new ArgumentNullException("Specification is required"); + + var evaluators = evaluateCriteriaOnly ? this.evaluators.Where(x => x.IsCriteriaEvaluator) : this.evaluators; + + foreach (var evaluator in evaluators) + { + query = evaluator.GetQuery(query, specification); + } + + return query; } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/DbSetExtensions.cs b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/DbSetExtensions.cs index 8e47bee3..7ae435a3 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/DbSetExtensions.cs +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/DbSetExtensions.cs @@ -6,30 +6,30 @@ namespace Ardalis.Specification.EntityFramework6 { - public static class DbSetExtensions + public static class DbSetExtensions + { + public static async Task> ToListAsync(this DbSet source, ISpecification specification, CancellationToken cancellationToken = default) where TSource : class { - public static async Task> ToListAsync(this DbSet source, ISpecification specification, CancellationToken cancellationToken = default) where TSource : class - { - var result = await SpecificationEvaluator.Default.GetQuery(source, specification).ToListAsync(cancellationToken); + var result = await SpecificationEvaluator.Default.GetQuery(source, specification).ToListAsync(cancellationToken); - return specification.PostProcessingAction == null - ? result - : specification.PostProcessingAction(result).ToList(); - } + return specification.PostProcessingAction == null + ? result + : specification.PostProcessingAction(result).ToList(); + } - public static async Task> ToEnumerableAsync(this DbSet source, ISpecification specification, CancellationToken cancellationToken = default) where TSource : class - { - var result = await SpecificationEvaluator.Default.GetQuery(source, specification).ToListAsync(cancellationToken); + public static async Task> ToEnumerableAsync(this DbSet source, ISpecification specification, CancellationToken cancellationToken = default) where TSource : class + { + var result = await SpecificationEvaluator.Default.GetQuery(source, specification).ToListAsync(cancellationToken); - return specification.PostProcessingAction == null - ? result - : specification.PostProcessingAction(result); - } + return specification.PostProcessingAction == null + ? result + : specification.PostProcessingAction(result); + } - public static IQueryable WithSpecification(this IQueryable source, ISpecification specification, ISpecificationEvaluator evaluator = null) where TSource : class - { - evaluator = evaluator ?? SpecificationEvaluator.Default; - return evaluator.GetQuery(source, specification); - } + public static IQueryable WithSpecification(this IQueryable source, ISpecification specification, ISpecificationEvaluator evaluator = null) where TSource : class + { + evaluator = evaluator ?? SpecificationEvaluator.Default; + return evaluator.GetQuery(source, specification); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/IncludeExtensions.cs b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/IncludeExtensions.cs index 471f8554..0c5bb473 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/IncludeExtensions.cs +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/IncludeExtensions.cs @@ -7,59 +7,59 @@ namespace Ardalis.Specification.EntityFramework6 { - public static class IncludeExtensions + public static class IncludeExtensions + { + public static IQueryable Include(this IQueryable source, IncludeExpressionInfo info) { - public static IQueryable Include(this IQueryable source, IncludeExpressionInfo info) - { - _ = info ?? throw new ArgumentNullException(nameof(info)); - var propertyName = GetPropertyName(info.LambdaExpression); + _ = info ?? throw new ArgumentNullException(nameof(info)); + var propertyName = GetPropertyName(info.LambdaExpression); - return QueryableExtensions.Include(source, propertyName); - } + return QueryableExtensions.Include(source, propertyName); + } - public static IQueryable ThenInclude(this IQueryable source, IncludeExpressionInfo info) - { - _ = info ?? throw new ArgumentNullException(nameof(info)); - _ = info.PreviousPropertyType ?? throw new ArgumentNullException(nameof(info.PreviousPropertyType)); + public static IQueryable ThenInclude(this IQueryable source, IncludeExpressionInfo info) + { + _ = info ?? throw new ArgumentNullException(nameof(info)); + _ = info.PreviousPropertyType ?? throw new ArgumentNullException(nameof(info.PreviousPropertyType)); - var exp = source.Expression as MethodCallExpression; - var arg = exp.Arguments[0] as ConstantExpression; + var exp = source.Expression as MethodCallExpression; + var arg = exp.Arguments[0] as ConstantExpression; - string previousPropertyName; - if (arg.Value is string) - { - previousPropertyName = arg.Value.ToString(); - } - else - { - // System.Data.Entity.Core.Objects.Span is an internal class, so here's some reflection to get to the previous property. + string previousPropertyName; + if (arg.Value is string) + { + previousPropertyName = arg.Value.ToString(); + } + else + { + // System.Data.Entity.Core.Objects.Span is an internal class, so here's some reflection to get to the previous property. - var propertyInfo = arg.Value.GetType().GetProperty("SpanList", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - var spanList = propertyInfo.GetValue(arg.Value); + var propertyInfo = arg.Value.GetType().GetProperty("SpanList", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + var spanList = propertyInfo.GetValue(arg.Value); - // Get the first item of the span list - propertyInfo = propertyInfo.PropertyType.GetProperty("Item"); - var spanPath = propertyInfo.GetValue(spanList, new object[] { 0 }); + // Get the first item of the span list + propertyInfo = propertyInfo.PropertyType.GetProperty("Item"); + var spanPath = propertyInfo.GetValue(spanList, new object[] { 0 }); - var fieldInfo = spanPath.GetType().GetField("Navigations", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - var navigations = fieldInfo.GetValue(spanPath) as List; - previousPropertyName = string.Join(".", navigations); - } - - var propertyName = GetPropertyName(info.LambdaExpression); + var fieldInfo = spanPath.GetType().GetField("Navigations", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + var navigations = fieldInfo.GetValue(spanPath) as List; + previousPropertyName = string.Join(".", navigations); + } - return QueryableExtensions.Include(source, $"{previousPropertyName}.{propertyName}"); - } + var propertyName = GetPropertyName(info.LambdaExpression); - private static string GetPropertyName(this Expression propertySelector, char delimiter = '.', char endTrim = ')') - { + return QueryableExtensions.Include(source, $"{previousPropertyName}.{propertyName}"); + } + + private static string GetPropertyName(this Expression propertySelector, char delimiter = '.', char endTrim = ')') + { - var asString = propertySelector.ToString(); - var firstDelim = asString.IndexOf(delimiter); + var asString = propertySelector.ToString(); + var firstDelim = asString.IndexOf(delimiter); - return firstDelim < 0 - ? asString - : asString.Substring(firstDelim + 1).TrimEnd(endTrim); - } + return firstDelim < 0 + ? asString + : asString.Substring(firstDelim + 1).TrimEnd(endTrim); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/ParameterReplacerVisitor.cs b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/ParameterReplacerVisitor.cs index adac86ff..942d25f1 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/ParameterReplacerVisitor.cs +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/ParameterReplacerVisitor.cs @@ -2,32 +2,32 @@ namespace Ardalis.Specification.EntityFramework6 { - internal class ParameterReplacerVisitor : ExpressionVisitor - { - private readonly Expression newExpression; - private readonly ParameterExpression oldParameter; + internal class ParameterReplacerVisitor : ExpressionVisitor + { + private readonly Expression newExpression; + private readonly ParameterExpression oldParameter; - private ParameterReplacerVisitor(ParameterExpression oldParameter, Expression newExpression) - { - this.oldParameter = oldParameter; - this.newExpression = newExpression; - } + private ParameterReplacerVisitor(ParameterExpression oldParameter, Expression newExpression) + { + this.oldParameter = oldParameter; + this.newExpression = newExpression; + } - internal static Expression Replace(Expression expression, ParameterExpression oldParameter, Expression newExpression) - { - return new ParameterReplacerVisitor(oldParameter, newExpression).Visit(expression); - } + internal static Expression Replace(Expression expression, ParameterExpression oldParameter, Expression newExpression) + { + return new ParameterReplacerVisitor(oldParameter, newExpression).Visit(expression); + } - protected override Expression VisitParameter(ParameterExpression p) - { - if (p == oldParameter) - { - return newExpression; - } - else - { - return p; - } - } + protected override Expression VisitParameter(ParameterExpression p) + { + if (p == oldParameter) + { + return newExpression; + } + else + { + return p; + } } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/SearchExtension.cs b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/SearchExtension.cs index ea9bca0f..8cffe870 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/SearchExtension.cs +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/Extensions/SearchExtension.cs @@ -6,49 +6,49 @@ namespace Ardalis.Specification.EntityFramework6 { - public static class SearchExtension + public static class SearchExtension + { + /// + /// Filters by applying an 'SQL LIKE' operation to it. + /// + /// The type being queried against. + /// The sequence of + /// + /// + /// Selector, the property to apply the SQL LIKE against. + /// SearchTerm, the value to use for the SQL LIKE. + /// + /// + /// + public static IQueryable Search(this IQueryable source, IEnumerable> criterias) { - /// - /// Filters by applying an 'SQL LIKE' operation to it. - /// - /// The type being queried against. - /// The sequence of - /// - /// - /// Selector, the property to apply the SQL LIKE against. - /// SearchTerm, the value to use for the SQL LIKE. - /// - /// - /// - public static IQueryable Search(this IQueryable source, IEnumerable> criterias) - { - Expression expr = null; - var parameter = Expression.Parameter(typeof(T), "x"); + Expression expr = null; + var parameter = Expression.Parameter(typeof(T), "x"); - foreach (var criteria in criterias) - { - var (selector, searchTerm) = (criteria.Selector, criteria.SearchTerm); - if (string.IsNullOrEmpty(criteria.SearchTerm)) - { - continue; - } + foreach (var criteria in criterias) + { + var (selector, searchTerm) = (criteria.Selector, criteria.SearchTerm); + if (string.IsNullOrEmpty(criteria.SearchTerm)) + { + continue; + } - var like = typeof(DbFunctions).GetMethod(nameof(DbFunctions.Like), new Type[] { typeof(string), typeof(string) }); + var like = typeof(DbFunctions).GetMethod(nameof(DbFunctions.Like), new Type[] { typeof(string), typeof(string) }); - var propertySelector = ParameterReplacerVisitor.Replace(selector, selector.Parameters[0], parameter); + var propertySelector = ParameterReplacerVisitor.Replace(selector, selector.Parameters[0], parameter); - var likeExpression = Expression.Call( - null, - like, - (propertySelector as LambdaExpression)?.Body, - Expression.Constant(searchTerm)); + var likeExpression = Expression.Call( + null, + like, + (propertySelector as LambdaExpression)?.Body, + Expression.Constant(searchTerm)); - expr = expr == null ? (Expression)likeExpression : Expression.OrElse(expr, likeExpression); - } + expr = expr == null ? (Expression)likeExpression : Expression.OrElse(expr, likeExpression); + } - return expr == null - ? source - : source.Where(Expression.Lambda>(expr, parameter)); - } + return expr == null + ? source + : source.Where(Expression.Lambda>(expr, parameter)); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/RepositoryBaseOfT.cs b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/RepositoryBaseOfT.cs index 337ed8b1..727a6404 100644 --- a/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/RepositoryBaseOfT.cs +++ b/Specification.EntityFramework6/src/Ardalis.Specification.EntityFramework6/RepositoryBaseOfT.cs @@ -7,143 +7,143 @@ namespace Ardalis.Specification.EntityFramework6 { + /// + public abstract class RepositoryBase : IRepositoryBase where T : class + { + private readonly DbContext dbContext; + private readonly ISpecificationEvaluator specificationEvaluator; + + public RepositoryBase(DbContext dbContext) + : this(dbContext, SpecificationEvaluator.Default) + { + } + + /// + public RepositoryBase(DbContext dbContext, ISpecificationEvaluator specificationEvaluator) + { + this.dbContext = dbContext; + this.specificationEvaluator = specificationEvaluator; + } + + /// + public virtual async Task AddAsync(T entity, CancellationToken cancellationToken = default) + { + dbContext.Set().Add(entity); + + await SaveChangesAsync(cancellationToken); + + return entity; + } /// - public abstract class RepositoryBase : IRepositoryBase where T : class - { - private readonly DbContext dbContext; - private readonly ISpecificationEvaluator specificationEvaluator; - - public RepositoryBase(DbContext dbContext) - : this(dbContext, SpecificationEvaluator.Default) - { - } - - /// - public RepositoryBase(DbContext dbContext, ISpecificationEvaluator specificationEvaluator) - { - this.dbContext = dbContext; - this.specificationEvaluator = specificationEvaluator; - } - - /// - public virtual async Task AddAsync(T entity, CancellationToken cancellationToken = default) - { - dbContext.Set().Add(entity); - - await SaveChangesAsync(cancellationToken); - - return entity; - } - /// - public virtual async Task UpdateAsync(T entity, CancellationToken cancellationToken = default) - { - dbContext.Entry(entity).State = EntityState.Modified; - - await SaveChangesAsync(cancellationToken); - } - /// - public virtual async Task DeleteAsync(T entity, CancellationToken cancellationToken = default) - { - dbContext.Set().Remove(entity); - - await SaveChangesAsync(cancellationToken); - } - /// - public virtual async Task DeleteRangeAsync(IEnumerable entities, CancellationToken cancellationToken = default) - { - dbContext.Set().RemoveRange(entities); - - await SaveChangesAsync(cancellationToken); - } - /// - public virtual async Task SaveChangesAsync(CancellationToken cancellationToken = default) - { - return await dbContext.SaveChangesAsync(cancellationToken); - } - - /// - public virtual async Task GetByIdAsync(TId id, CancellationToken cancellationToken = default) - { - return await dbContext.Set().FindAsync(cancellationToken: cancellationToken, new object[] { id }); - } - /// - public virtual async Task GetBySpecAsync(Spec specification, CancellationToken cancellationToken = default) where Spec : ISpecification, ISingleResultSpecification - { - return await ApplySpecification(specification).FirstOrDefaultAsync(cancellationToken); - } - /// - public virtual async Task GetBySpecAsync(ISpecification specification, CancellationToken cancellationToken = default) - { - return await ApplySpecification(specification).FirstOrDefaultAsync(cancellationToken); - } - - /// - public virtual async Task> ListAsync(CancellationToken cancellationToken = default) - { - return await dbContext.Set().ToListAsync(cancellationToken); - } - /// - public virtual async Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default) - { - var queryResult = await ApplySpecification(specification).ToListAsync(cancellationToken); - - return specification.PostProcessingAction == null ? queryResult : specification.PostProcessingAction(queryResult).ToList(); - } - /// - public virtual async Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default) - { - var queryResult = await ApplySpecification(specification).ToListAsync(cancellationToken); - - return specification.PostProcessingAction == null ? queryResult : specification.PostProcessingAction(queryResult).ToList(); - } - - /// - public virtual async Task CountAsync(ISpecification specification, CancellationToken cancellationToken = default) - { - return await ApplySpecification(specification, true).CountAsync(cancellationToken); - } - - /// - public virtual async Task CountAsync(CancellationToken cancellationToken = default) - { - return await dbContext.Set().CountAsync(cancellationToken); - } - - /// - public virtual async Task AnyAsync(ISpecification specification, CancellationToken cancellationToken = default) - { - return await ApplySpecification(specification, true).AnyAsync(cancellationToken); - } - - /// - public virtual async Task AnyAsync(CancellationToken cancellationToken = default) - { - return await dbContext.Set().AnyAsync(cancellationToken); - } - - /// - /// Filters the entities of , to those that match the encapsulated query logic of the - /// . - /// - /// The encapsulated query logic. - /// The filtered entities as an . - protected virtual IQueryable ApplySpecification(ISpecification specification, bool evaluateCriteriaOnly = false) - { - return specificationEvaluator.GetQuery(dbContext.Set().AsQueryable(), specification, evaluateCriteriaOnly); - } - /// - /// Filters all entities of , that matches the encapsulated query logic of the - /// , from the database. - /// - /// Projects each entity into a new form, being . - /// - /// - /// The type of the value returned by the projection. - /// The encapsulated query logic. - /// The filtered projected entities as an . - protected virtual IQueryable ApplySpecification(ISpecification specification) - { - return specificationEvaluator.GetQuery(dbContext.Set().AsQueryable(), specification); - } - } -} \ No newline at end of file + public virtual async Task UpdateAsync(T entity, CancellationToken cancellationToken = default) + { + dbContext.Entry(entity).State = EntityState.Modified; + + await SaveChangesAsync(cancellationToken); + } + /// + public virtual async Task DeleteAsync(T entity, CancellationToken cancellationToken = default) + { + dbContext.Set().Remove(entity); + + await SaveChangesAsync(cancellationToken); + } + /// + public virtual async Task DeleteRangeAsync(IEnumerable entities, CancellationToken cancellationToken = default) + { + dbContext.Set().RemoveRange(entities); + + await SaveChangesAsync(cancellationToken); + } + /// + public virtual async Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + return await dbContext.SaveChangesAsync(cancellationToken); + } + + /// + public virtual async Task GetByIdAsync(TId id, CancellationToken cancellationToken = default) + { + return await dbContext.Set().FindAsync(cancellationToken: cancellationToken, new object[] { id }); + } + /// + public virtual async Task GetBySpecAsync(Spec specification, CancellationToken cancellationToken = default) where Spec : ISpecification, ISingleResultSpecification + { + return await ApplySpecification(specification).FirstOrDefaultAsync(cancellationToken); + } + /// + public virtual async Task GetBySpecAsync(ISpecification specification, CancellationToken cancellationToken = default) + { + return await ApplySpecification(specification).FirstOrDefaultAsync(cancellationToken); + } + + /// + public virtual async Task> ListAsync(CancellationToken cancellationToken = default) + { + return await dbContext.Set().ToListAsync(cancellationToken); + } + /// + public virtual async Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default) + { + var queryResult = await ApplySpecification(specification).ToListAsync(cancellationToken); + + return specification.PostProcessingAction == null ? queryResult : specification.PostProcessingAction(queryResult).ToList(); + } + /// + public virtual async Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default) + { + var queryResult = await ApplySpecification(specification).ToListAsync(cancellationToken); + + return specification.PostProcessingAction == null ? queryResult : specification.PostProcessingAction(queryResult).ToList(); + } + + /// + public virtual async Task CountAsync(ISpecification specification, CancellationToken cancellationToken = default) + { + return await ApplySpecification(specification, true).CountAsync(cancellationToken); + } + + /// + public virtual async Task CountAsync(CancellationToken cancellationToken = default) + { + return await dbContext.Set().CountAsync(cancellationToken); + } + + /// + public virtual async Task AnyAsync(ISpecification specification, CancellationToken cancellationToken = default) + { + return await ApplySpecification(specification, true).AnyAsync(cancellationToken); + } + + /// + public virtual async Task AnyAsync(CancellationToken cancellationToken = default) + { + return await dbContext.Set().AnyAsync(cancellationToken); + } + + /// + /// Filters the entities of , to those that match the encapsulated query logic of the + /// . + /// + /// The encapsulated query logic. + /// The filtered entities as an . + protected virtual IQueryable ApplySpecification(ISpecification specification, bool evaluateCriteriaOnly = false) + { + return specificationEvaluator.GetQuery(dbContext.Set().AsQueryable(), specification, evaluateCriteriaOnly); + } + /// + /// Filters all entities of , that matches the encapsulated query logic of the + /// , from the database. + /// + /// Projects each entity into a new form, being . + /// + /// + /// The type of the value returned by the projection. + /// The encapsulated query logic. + /// The filtered projected entities as an . + protected virtual IQueryable ApplySpecification(ISpecification specification) + { + return specificationEvaluator.GetQuery(dbContext.Set().AsQueryable(), specification); + } + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/AddressConfiguration.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/AddressConfiguration.cs index f8031efd..40deed39 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/AddressConfiguration.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/AddressConfiguration.cs @@ -1,14 +1,14 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System.Data.Entity.ModelConfiguration; +using System.Data.Entity.ModelConfiguration; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture.Configurations { - public class AddressConfiguration : EntityTypeConfiguration
+ public class AddressConfiguration : EntityTypeConfiguration
+ { + public AddressConfiguration() { - public AddressConfiguration() - { - ToTable("Address"); - HasKey(c => c.Id); - } + ToTable("Address"); + HasKey(c => c.Id); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/CompanyConfiguration.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/CompanyConfiguration.cs index 6bd726d2..8954b787 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/CompanyConfiguration.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/CompanyConfiguration.cs @@ -1,20 +1,20 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System.Data.Entity.ModelConfiguration; +using System.Data.Entity.ModelConfiguration; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture.Configurations { - public class CompanyConfiguration : EntityTypeConfiguration + public class CompanyConfiguration : EntityTypeConfiguration + { + public CompanyConfiguration() { - public CompanyConfiguration() - { - ToTable("Company"); - HasKey(c => c.Id); + ToTable("Company"); + HasKey(c => c.Id); - Property(c => c.Id) - .HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None); - - //HasMany(c => c.Stores) - // .WithRequired(s => s.Company); - } + Property(c => c.Id) + .HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None); + + //HasMany(c => c.Stores) + // .WithRequired(s => s.Company); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/CountryConfiguration.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/CountryConfiguration.cs index cbab135f..ae0c2dfa 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/CountryConfiguration.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/CountryConfiguration.cs @@ -1,14 +1,14 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System.Data.Entity.ModelConfiguration; +using System.Data.Entity.ModelConfiguration; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture.Configurations { - public class CountryConfiguration : EntityTypeConfiguration + public class CountryConfiguration : EntityTypeConfiguration + { + public CountryConfiguration() { - public CountryConfiguration() - { - ToTable("Country"); - HasKey(c => c.Id); - } + ToTable("Country"); + HasKey(c => c.Id); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/ProductConfiguration.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/ProductConfiguration.cs index 2b5d04c8..e1190982 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/ProductConfiguration.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/ProductConfiguration.cs @@ -1,14 +1,14 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System.Data.Entity.ModelConfiguration; +using System.Data.Entity.ModelConfiguration; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture.Configurations { - public class ProductConfiguration : EntityTypeConfiguration + public class ProductConfiguration : EntityTypeConfiguration + { + public ProductConfiguration() { - public ProductConfiguration() - { - ToTable("Product"); - HasKey(c => c.Id); - } + ToTable("Product"); + HasKey(c => c.Id); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/StoreConfiguration.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/StoreConfiguration.cs index 479865a0..3557f726 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/StoreConfiguration.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/Configurations/StoreConfiguration.cs @@ -1,17 +1,17 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System.Data.Entity.ModelConfiguration; +using System.Data.Entity.ModelConfiguration; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture.Configurations { - public class StoreConfiguration : EntityTypeConfiguration + public class StoreConfiguration : EntityTypeConfiguration + { + public StoreConfiguration() { - public StoreConfiguration() - { - ToTable("Store"); - HasKey(c => c.Id); + ToTable("Store"); + HasKey(c => c.Id); - HasOptional(s => s.Address) - .WithRequired(x => x.Store); - } + HasOptional(s => s.Address) + .WithRequired(x => x.Store); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/DbInitializer.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/DbInitializer.cs index 9ea7de67..421db014 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/DbInitializer.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/DbInitializer.cs @@ -1,23 +1,23 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; -using System.Data.Entity; +using System.Data.Entity; +using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; namespace Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture { - public class DbInitializer : CreateDatabaseIfNotExists + public class DbInitializer : CreateDatabaseIfNotExists + { + protected override void Seed(TestDbContext context) { - protected override void Seed(TestDbContext context) - { - base.Seed(context); + base.Seed(context); - var companies = CompanySeed.Get(); - - context.Addresses.AddRange(AddressSeed.Get()); - context.Countries.AddRange(CountrySeed.Get()); - context.Companies.AddRange(CompanySeed.Get()); - context.Products.AddRange(ProductSeed.Get()); - context.Stores.AddRange(StoreSeed.Get()); + var companies = CompanySeed.Get(); - context.SaveChanges(); - } + context.Addresses.AddRange(AddressSeed.Get()); + context.Countries.AddRange(CountrySeed.Get()); + context.Companies.AddRange(CompanySeed.Get()); + context.Products.AddRange(ProductSeed.Get()); + context.Stores.AddRange(StoreSeed.Get()); + + context.SaveChanges(); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/IntegrationTestBase.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/IntegrationTestBase.cs index 8b7434a5..d9dd00b0 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/IntegrationTestBase.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/IntegrationTestBase.cs @@ -3,18 +3,18 @@ namespace Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture { - public class IntegrationTestBase : IClassFixture - { - protected TestDbContext dbContext; - protected Repository companyRepository; - protected Repository storeRepository; + public class IntegrationTestBase : IClassFixture + { + protected TestDbContext dbContext; + protected Repository companyRepository; + protected Repository storeRepository; - public IntegrationTestBase(SharedDatabaseFixture fixture) - { - dbContext = fixture.CreateContext(); + public IntegrationTestBase(SharedDatabaseFixture fixture) + { + dbContext = fixture.CreateContext(); - companyRepository = new Repository(dbContext); - storeRepository = new Repository(dbContext); - } + companyRepository = new Repository(dbContext); + storeRepository = new Repository(dbContext); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/RepositoryOfT.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/RepositoryOfT.cs index 88323e46..4f838788 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/RepositoryOfT.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/RepositoryOfT.cs @@ -1,13 +1,13 @@ namespace Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture { - /// - public class Repository : RepositoryBase where T : class - { - protected readonly TestDbContext dbContext; + /// + public class Repository : RepositoryBase where T : class + { + protected readonly TestDbContext dbContext; - public Repository(TestDbContext dbContext) : base(dbContext) - { - this.dbContext = dbContext; - } + public Repository(TestDbContext dbContext) : base(dbContext) + { + this.dbContext = dbContext; } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/SharedDatabaseFixture.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/SharedDatabaseFixture.cs index b7e28931..1470a4a4 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/SharedDatabaseFixture.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/SharedDatabaseFixture.cs @@ -1,47 +1,47 @@ -using MartinCostello.SqlLocalDb; -using System; +using System; using System.Data.Common; using System.Data.SqlClient; +using MartinCostello.SqlLocalDb; namespace Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture { - public class SharedDatabaseFixture : IDisposable - { - // (docker) - public const string ConnectionStringDocker = "Data Source=databaseEF6;Initial Catalog=SpecificationEF6TestsDB;PersistSecurityInfo=True;User ID=sa;Password=P@ssW0rd!"; - - // (localdb) - public const string ConnectionStringLocalDb = "Server=(localdb)\\mssqllocaldb;Integrated Security=SSPI;Initial Catalog=SpecificationEF6TestsDB;ConnectRetryCount=0"; + public class SharedDatabaseFixture : IDisposable + { + // (docker) + public const string ConnectionStringDocker = "Data Source=databaseEF6;Initial Catalog=SpecificationEF6TestsDB;PersistSecurityInfo=True;User ID=sa;Password=P@ssW0rd!"; + // (localdb) + public const string ConnectionStringLocalDb = "Server=(localdb)\\mssqllocaldb;Integrated Security=SSPI;Initial Catalog=SpecificationEF6TestsDB;ConnectRetryCount=0"; - public SharedDatabaseFixture() - { - var isLocalDBInstalled = false; - using (var localDB = new SqlLocalDbApi()) - { - isLocalDBInstalled = localDB.IsLocalDBInstalled(); - } + public SharedDatabaseFixture() + { + var isLocalDBInstalled = false; - Connection = isLocalDBInstalled - ? new SqlConnection(ConnectionStringLocalDb) - : new SqlConnection(ConnectionStringDocker); - } + using (var localDB = new SqlLocalDbApi()) + { + isLocalDBInstalled = localDB.IsLocalDBInstalled(); + } - public DbConnection Connection { get; } + Connection = isLocalDBInstalled + ? new SqlConnection(ConnectionStringLocalDb) + : new SqlConnection(ConnectionStringDocker); + } - public TestDbContext CreateContext(DbTransaction transaction = null) - { - var context = new TestDbContext(Connection); + public DbConnection Connection { get; } - if (transaction != null) - { - context.Database.UseTransaction(transaction); - } + public TestDbContext CreateContext(DbTransaction transaction = null) + { + var context = new TestDbContext(Connection); - return context; - } + if (transaction != null) + { + context.Database.UseTransaction(transaction); + } - public void Dispose() => Connection.Dispose(); + return context; } -} \ No newline at end of file + + public void Dispose() => Connection.Dispose(); + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/TestDbContext.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/TestDbContext.cs index a3b19420..2683f3db 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/TestDbContext.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/Fixture/TestDbContext.cs @@ -1,39 +1,39 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Reflection; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture { - public class TestDbContext : DbContext + public class TestDbContext : DbContext + { + public TestDbContext(DbConnection connection) : base(connection, false) { - public TestDbContext(DbConnection connection) : base(connection, false) - { - Database.SetInitializer(new DbInitializer()); - } + Database.SetInitializer(new DbInitializer()); + } - public virtual DbSet Countries { get; set; } - public virtual DbSet Companies { get; set; } - public virtual DbSet Stores { get; set; } - public virtual DbSet
Addresses { get; set; } - public virtual DbSet Products { get; set; } + public virtual DbSet Countries { get; set; } + public virtual DbSet Companies { get; set; } + public virtual DbSet Stores { get; set; } + public virtual DbSet
Addresses { get; set; } + public virtual DbSet Products { get; set; } - protected override void OnModelCreating(DbModelBuilder modelBuilder) - { - var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() - .Where(type => !string.IsNullOrEmpty(type.Namespace)) - .Where(type => type.BaseType != null && type.BaseType.IsGenericType - && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)); - foreach (var type in typesToRegister) - { - dynamic configurationInstance = Activator.CreateInstance(type); - modelBuilder.Configurations.Add(configurationInstance); - } + protected override void OnModelCreating(DbModelBuilder modelBuilder) + { + var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() + .Where(type => !string.IsNullOrEmpty(type.Namespace)) + .Where(type => type.BaseType != null && type.BaseType.IsGenericType + && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)); + foreach (var type in typesToRegister) + { + dynamic configurationInstance = Activator.CreateInstance(type); + modelBuilder.Configurations.Add(configurationInstance); + } - base.OnModelCreating(modelBuilder); - } + base.OnModelCreating(modelBuilder); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_AnyAsync.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_AnyAsync.cs index a38a6371..a2e73918 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_AnyAsync.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_AnyAsync.cs @@ -1,38 +1,38 @@ -using Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture; +using System.Threading.Tasks; +using Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture; using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; using Ardalis.Specification.UnitTests.Fixture.Specs; using FluentAssertions; -using System.Threading.Tasks; using Xunit; namespace Ardalis.Specification.EntityFramework6.IntegrationTests { - public class RepositoryOfT_AnyAsync : IntegrationTestBase - { - public RepositoryOfT_AnyAsync(SharedDatabaseFixture fixture) : base(fixture) { } + public class RepositoryOfT_AnyAsync : IntegrationTestBase + { + public RepositoryOfT_AnyAsync(SharedDatabaseFixture fixture) : base(fixture) { } - [Fact] - public async Task ReturnsTrueOnStoresRecords_WithoutSpec() - { - var result = await storeRepository.AnyAsync(); + [Fact] + public async Task ReturnsTrueOnStoresRecords_WithoutSpec() + { + var result = await storeRepository.AnyAsync(); - result.Should().BeTrue(); - } + result.Should().BeTrue(); + } - [Fact] - public async Task ReturnsTrue_GivenStoreByIdSpecWithValidStore() - { - var result = await storeRepository.AnyAsync(new StoreByIdSpec(StoreSeed.VALID_STORE_ID)); + [Fact] + public async Task ReturnsTrue_GivenStoreByIdSpecWithValidStore() + { + var result = await storeRepository.AnyAsync(new StoreByIdSpec(StoreSeed.VALID_STORE_ID)); - result.Should().BeTrue(); - } + result.Should().BeTrue(); + } - [Fact] - public async Task ReturnsTrue_GivenStoreByIdSpecWithInvalidStore() - { - var result = await storeRepository.AnyAsync(new StoreByIdSpec(0)); + [Fact] + public async Task ReturnsTrue_GivenStoreByIdSpecWithInvalidStore() + { + var result = await storeRepository.AnyAsync(new StoreByIdSpec(0)); - result.Should().BeFalse(); - } + result.Should().BeFalse(); } + } } diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_GetById.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_GetById.cs index 7cf6f2ee..d6667e7b 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_GetById.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_GetById.cs @@ -1,31 +1,31 @@ -using FluentAssertions; +using System.Threading.Tasks; using Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture; using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; -using System.Threading.Tasks; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.EntityFramework6.IntegrationTests { - public class RepositoryOfT_GetById : IntegrationTestBase - { - public RepositoryOfT_GetById(SharedDatabaseFixture fixture) : base(fixture) { } + public class RepositoryOfT_GetById : IntegrationTestBase + { + public RepositoryOfT_GetById(SharedDatabaseFixture fixture) : base(fixture) { } - [Fact] - public async Task ReturnsStore_GivenId() - { - var result = await storeRepository.GetByIdAsync(StoreSeed.VALID_STORE_ID); + [Fact] + public async Task ReturnsStore_GivenId() + { + var result = await storeRepository.GetByIdAsync(StoreSeed.VALID_STORE_ID); - result.Should().NotBeNull(); - result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - } + result.Should().NotBeNull(); + result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + } - [Fact] - public async Task ReturnsStore_GivenGenericId() - { - var result = await storeRepository.GetByIdAsync(StoreSeed.VALID_STORE_ID); + [Fact] + public async Task ReturnsStore_GivenGenericId() + { + var result = await storeRepository.GetByIdAsync(StoreSeed.VALID_STORE_ID); - result.Should().NotBeNull(); - result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - } + result.Should().NotBeNull(); + result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_GetBySpec.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_GetBySpec.cs index 3cccf5c6..a9d610af 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_GetBySpec.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_GetBySpec.cs @@ -1,104 +1,104 @@ -using FluentAssertions; -using Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture; -using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; +using System.Data.Entity; using System.Linq; using System.Threading.Tasks; -using Xunit; +using Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture; +using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; using Ardalis.Specification.UnitTests.Fixture.Specs; -using System.Data.Entity; +using FluentAssertions; +using Xunit; namespace Ardalis.Specification.EntityFramework6.IntegrationTests { - public class RepositoryOfT_GetBySpec : IntegrationTestBase + public class RepositoryOfT_GetBySpec : IntegrationTestBase + { + public RepositoryOfT_GetBySpec(SharedDatabaseFixture fixture) : base(fixture) { } + + [Fact] + public async Task ReturnsStoreWithProducts_GivenStoreByIdIncludeProductsSpec() + { + var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeProductsSpec(StoreSeed.VALID_STORE_ID)); + + result.Should().NotBeNull(); + result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + result.Products.Count.Should().BeGreaterThan(1); + } + + [Fact] + public async Task ReturnsStoreWithAddress_GivenStoreByIdIncludeAddressSpec() + { + var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeAddressSpec(StoreSeed.VALID_STORE_ID)); + + result.Should().NotBeNull(); + result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + result.Address?.Street.Should().Be(AddressSeed.VALID_STREET_FOR_STOREID1); + } + + [Fact] + public async Task ReturnsStoreWithAddressAndProduct_GivenStoreByIdIncludeAddressAndProductsSpec() + { + var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeAddressAndProductsSpec(StoreSeed.VALID_STORE_ID)); + + result.Should().NotBeNull(); + result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + result.Products.Count.Should().BeGreaterThan(1); + result.Address?.Street.Should().Be(AddressSeed.VALID_STREET_FOR_STOREID1); + } + + [Fact] + public async Task ReturnsStoreWithProducts_GivenStoreByIdIncludeProductsUsingStringSpec() + { + var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeProductsUsingStringSpec(StoreSeed.VALID_STORE_ID)); + + result.Should().NotBeNull(); + result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + result.Products.Count.Should().BeGreaterThan(1); + } + + [Fact] + public async Task ReturnsCompanyWithStoresAndAddress_GivenCompanyByIdIncludeStoresThenIncludeAddressSpec() + { + var result = await companyRepository.GetBySpecAsync(new CompanyByIdIncludeStoresThenIncludeAddressSpec(CompanySeed.VALID_COMPANY_ID)); + + result.Should().NotBeNull(); + result.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); + result.Stores.Count.Should().BeGreaterThan(49); + result.Stores.Select(x => x.Address).Count().Should().BeGreaterThan(0); + } + + [Fact] + public async Task ReturnsCompanyWithStoresAndProducts_GivenCompanyByIdIncludeStoresThenIncludeProductsSpec() + { + var result = await companyRepository.GetBySpecAsync(new CompanyByIdIncludeStoresThenIncludeProductsSpec(CompanySeed.VALID_COMPANY_ID)); + + result.Should().NotBeNull(); + result.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); + result.Stores.Count.Should().BeGreaterThan(49); + result.Stores.Select(x => x.Products).Count().Should().BeGreaterThan(1); + } + + [Fact] + public async Task ReturnsUntrackedCompany_GivenCompanyByIdAsUntrackedSpec() + { + //dbContext.ChangeTracker.Clear(); + + var result = await companyRepository.GetBySpecAsync(new CompanyByIdAsUntrackedSpec(CompanySeed.VALID_COMPANY_ID)); + + result.Should().NotBeNull(); + result?.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); + dbContext.Entry(result).State.Should().Be(EntityState.Detached); + } + + [Fact] + public async Task ReturnsStoreWithCompanyAndCountryAndStoresForCompany_GivenStoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec() { - public RepositoryOfT_GetBySpec(SharedDatabaseFixture fixture) : base(fixture) { } - - [Fact] - public async Task ReturnsStoreWithProducts_GivenStoreByIdIncludeProductsSpec() - { - var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeProductsSpec(StoreSeed.VALID_STORE_ID)); - - result.Should().NotBeNull(); - result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - result.Products.Count.Should().BeGreaterThan(1); - } - - [Fact] - public async Task ReturnsStoreWithAddress_GivenStoreByIdIncludeAddressSpec() - { - var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeAddressSpec(StoreSeed.VALID_STORE_ID)); - - result.Should().NotBeNull(); - result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - result.Address?.Street.Should().Be(AddressSeed.VALID_STREET_FOR_STOREID1); - } - - [Fact] - public async Task ReturnsStoreWithAddressAndProduct_GivenStoreByIdIncludeAddressAndProductsSpec() - { - var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeAddressAndProductsSpec(StoreSeed.VALID_STORE_ID)); - - result.Should().NotBeNull(); - result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - result.Products.Count.Should().BeGreaterThan(1); - result.Address?.Street.Should().Be(AddressSeed.VALID_STREET_FOR_STOREID1); - } - - [Fact] - public async Task ReturnsStoreWithProducts_GivenStoreByIdIncludeProductsUsingStringSpec() - { - var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeProductsUsingStringSpec(StoreSeed.VALID_STORE_ID)); - - result.Should().NotBeNull(); - result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - result.Products.Count.Should().BeGreaterThan(1); - } - - [Fact] - public async Task ReturnsCompanyWithStoresAndAddress_GivenCompanyByIdIncludeStoresThenIncludeAddressSpec() - { - var result = await companyRepository.GetBySpecAsync(new CompanyByIdIncludeStoresThenIncludeAddressSpec(CompanySeed.VALID_COMPANY_ID)); - - result.Should().NotBeNull(); - result.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); - result.Stores.Count.Should().BeGreaterThan(49); - result.Stores.Select(x => x.Address).Count().Should().BeGreaterThan(0); - } - - [Fact] - public async Task ReturnsCompanyWithStoresAndProducts_GivenCompanyByIdIncludeStoresThenIncludeProductsSpec() - { - var result = await companyRepository.GetBySpecAsync(new CompanyByIdIncludeStoresThenIncludeProductsSpec(CompanySeed.VALID_COMPANY_ID)); - - result.Should().NotBeNull(); - result.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); - result.Stores.Count.Should().BeGreaterThan(49); - result.Stores.Select(x => x.Products).Count().Should().BeGreaterThan(1); - } - - [Fact] - public async Task ReturnsUntrackedCompany_GivenCompanyByIdAsUntrackedSpec() - { - //dbContext.ChangeTracker.Clear(); - - var result = await companyRepository.GetBySpecAsync(new CompanyByIdAsUntrackedSpec(CompanySeed.VALID_COMPANY_ID)); - - result.Should().NotBeNull(); - result?.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); - dbContext.Entry(result).State.Should().Be(EntityState.Detached); - } - - [Fact] - public async Task ReturnsStoreWithCompanyAndCountryAndStoresForCompany_GivenStoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec() - { - var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec(StoreSeed.VALID_STORE_ID)); - - result.Should().NotBeNull(); - result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - result.Company.Should().NotBeNull(); - result.Company?.Country.Should().NotBeNull(); - result.Company?.Stores.Should().HaveCountGreaterOrEqualTo(2); - result.Company?.Stores?.Should().Match(x => x.Any(z => z.Products.Count > 0)); - } + var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec(StoreSeed.VALID_STORE_ID)); + + result.Should().NotBeNull(); + result.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + result.Company.Should().NotBeNull(); + result.Company?.Country.Should().NotBeNull(); + result.Company?.Stores.Should().HaveCountGreaterOrEqualTo(2); + result.Company?.Stores?.Should().Match(x => x.Any(z => z.Products.Count > 0)); } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_ListAsync.cs b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_ListAsync.cs index 3b3c9f6b..57e56443 100644 --- a/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_ListAsync.cs +++ b/Specification.EntityFramework6/tests/Ardalis.Specification.EntityFramework6.IntegrationTests/RepositoryOfT_ListAsync.cs @@ -1,174 +1,174 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; -using System.Linq; +using System.Linq; using System.Threading.Tasks; -using Xunit; using Ardalis.Specification.EntityFramework6.IntegrationTests.Fixture; +using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; +using Xunit; namespace Ardalis.Specification.EntityFramework6.IntegrationTests { - public class RepositoryOfT_ListAsync : IntegrationTestBase + public class RepositoryOfT_ListAsync : IntegrationTestBase + { + public RepositoryOfT_ListAsync(SharedDatabaseFixture fixture) : base(fixture) { } + + [Fact] + public async Task ReturnsStoreWithProducts_GivenStoreIncludeProductsSpec() + { + var result = await storeRepository.ListAsync(new StoreIncludeProductsSpec()); + + result.Should().NotBeNull(); + result.Should().NotBeEmpty(); + result[0].Products.Should().NotBeEmpty(); + } + + [Fact] + public async Task ReturnsStoreWithAddress_GivenStoreIncludeAddressSpec() { - public RepositoryOfT_ListAsync(SharedDatabaseFixture fixture) : base(fixture) { } - - [Fact] - public async Task ReturnsStoreWithProducts_GivenStoreIncludeProductsSpec() - { - var result = await storeRepository.ListAsync(new StoreIncludeProductsSpec()); + var result = await storeRepository.ListAsync(new StoreIncludeAddressSpec()); - result.Should().NotBeNull(); - result.Should().NotBeEmpty(); - result[0].Products.Should().NotBeEmpty(); - } - - [Fact] - public async Task ReturnsStoreWithAddress_GivenStoreIncludeAddressSpec() - { - var result = await storeRepository.ListAsync(new StoreIncludeAddressSpec()); - - result.Should().NotBeNull(); - result.Should().NotBeEmpty(); - result[0].Address.Should().NotBeNull(); - } + result.Should().NotBeNull(); + result.Should().NotBeEmpty(); + result[0].Address.Should().NotBeNull(); + } - [Fact] - public async Task ReturnsStoreWithAddressAndProduct_GivenStoreIncludeAddressAndProductsSpec() - { - var result = await storeRepository.ListAsync(new StoreIncludeAddressAndProductsSpec()); + [Fact] + public async Task ReturnsStoreWithAddressAndProduct_GivenStoreIncludeAddressAndProductsSpec() + { + var result = await storeRepository.ListAsync(new StoreIncludeAddressAndProductsSpec()); - result.Should().NotBeNull(); - result.Should().NotBeEmpty(); - result[0].Address.Should().NotBeNull(); - result[0].Products.Should().NotBeEmpty(); - } + result.Should().NotBeNull(); + result.Should().NotBeEmpty(); + result[0].Address.Should().NotBeNull(); + result[0].Products.Should().NotBeEmpty(); + } - [Fact] - public async Task ReturnsStoreWithIdFrom15To30_GivenStoresByIdListSpec() - { - var ids = Enumerable.Range(15, 16); - var spec = new StoresByIdListSpec(ids); + [Fact] + public async Task ReturnsStoreWithIdFrom15To30_GivenStoresByIdListSpec() + { + var ids = Enumerable.Range(15, 16); + var spec = new StoresByIdListSpec(ids); - var stores = await storeRepository.ListAsync(spec); + var stores = await storeRepository.ListAsync(spec); - stores.Count.Should().Be(16); - stores.OrderBy(x => x.Id).First().Id.Should().Be(15); - stores.OrderBy(x => x.Id).Last().Id.Should().Be(30); - } + stores.Count.Should().Be(16); + stores.OrderBy(x => x.Id).First().Id.Should().Be(15); + stores.OrderBy(x => x.Id).Last().Id.Should().Be(30); + } - [Fact] - public async Task ReturnsSecondPageOfStoreNames_GivenStoreNamesPaginatedSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 + [Fact] + public async Task ReturnsSecondPageOfStoreNames_GivenStoreNamesPaginatedSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 - var spec = new StoreNamesPaginatedSpec(skip, take); + var spec = new StoreNamesPaginatedSpec(skip, take); - var storeNames = await storeRepository.ListAsync(spec); + var storeNames = await storeRepository.ListAsync(spec); - storeNames.Count.Should().Be(take); - storeNames.First().Should().Be("Store 11"); - storeNames.Last().Should().Be("Store 20"); - } - - [Fact] - public async Task ReturnsSecondPageOfStores_GivenStoresPaginatedSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 - - var spec = new StoresPaginatedSpec(skip, take); - - var stores = await storeRepository.ListAsync(spec); - - stores.Count.Should().Be(take); - stores.OrderBy(x => x.Id).First().Id.Should().Be(11); - stores.OrderBy(x => x.Id).Last().Id.Should().Be(20); - } - - [Fact] - public async Task ReturnsOrderStoresByNameDescForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameSpec() - { - var spec = new StoresByCompanyOrderedDescByNameSpec(2); - - var stores = await storeRepository.ListAsync(spec); - - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_LAST_ID); - } - - [Fact] - public async Task ReturnsOrderStoresByNameDescThenByIdForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameThenByIdSpec() - { - var spec = new StoresByCompanyOrderedDescByNameThenByIdSpec(2); - - var stores = await storeRepository.ListAsync(spec); - - stores.First().Id.Should().Be(99); - stores.Last().Id.Should().Be(98); - } - - [Fact] - public async Task ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedOrderedDescByNameSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 - - var spec = new StoresByCompanyPaginatedOrderedDescByNameSpec(2, skip, take); + storeNames.Count.Should().Be(take); + storeNames.First().Should().Be("Store 11"); + storeNames.Last().Should().Be("Store 20"); + } - var stores = await storeRepository.ListAsync(spec); - - stores.Count.Should().Be(take); - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_LAST_ID); - } - - [Fact] - public async Task ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 + [Fact] + public async Task ReturnsSecondPageOfStores_GivenStoresPaginatedSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 - var spec = new StoresByCompanyPaginatedSpec(2, skip, take); + var spec = new StoresPaginatedSpec(skip, take); - var stores = await storeRepository.ListAsync(spec); + var stores = await storeRepository.ListAsync(spec); - stores.Count.Should().Be(take); - stores.OrderBy(x => x.Id).First().Id.Should().Be(61); - stores.OrderBy(x => x.Id).Last().Id.Should().Be(70); - } + stores.Count.Should().Be(take); + stores.OrderBy(x => x.Id).First().Id.Should().Be(11); + stores.OrderBy(x => x.Id).Last().Id.Should().Be(20); + } - [Fact] - public async Task ReturnsOrderedStores_GivenStoresOrderedSpecByName() - { - var spec = new StoresOrderedSpecByName(); + [Fact] + public async Task ReturnsOrderStoresByNameDescForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameSpec() + { + var spec = new StoresByCompanyOrderedDescByNameSpec(2); - var stores = await storeRepository.ListAsync(spec); + var stores = await storeRepository.ListAsync(spec); - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_LAST_ID); - } + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_LAST_ID); + } - [Fact] - public async Task ReturnsOrderedStores_GivenStoresOrderedDescendingByNameSpec() - { - var spec = new StoresOrderedDescendingByNameSpec(); + [Fact] + public async Task ReturnsOrderStoresByNameDescThenByIdForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameThenByIdSpec() + { + var spec = new StoresByCompanyOrderedDescByNameThenByIdSpec(2); - var stores = await storeRepository.ListAsync(spec); + var stores = await storeRepository.ListAsync(spec); - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_LAST_ID); - } + stores.First().Id.Should().Be(99); + stores.Last().Id.Should().Be(98); + } - [Fact] - public async Task ReturnsStoreContainingCity1_GivenStoreIncludeProductsSpec() - { - var result = await storeRepository.ListAsync(new StoreSearchByNameOrCitySpec(StoreSeed.VALID_Search_City_Key)); + [Fact] + public async Task ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedOrderedDescByNameSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 + + var spec = new StoresByCompanyPaginatedOrderedDescByNameSpec(2, skip, take); + + var stores = await storeRepository.ListAsync(spec); + + stores.Count.Should().Be(take); + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_LAST_ID); + } + + [Fact] + public async Task ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 + + var spec = new StoresByCompanyPaginatedSpec(2, skip, take); + + var stores = await storeRepository.ListAsync(spec); + + stores.Count.Should().Be(take); + stores.OrderBy(x => x.Id).First().Id.Should().Be(61); + stores.OrderBy(x => x.Id).Last().Id.Should().Be(70); + } + + [Fact] + public async Task ReturnsOrderedStores_GivenStoresOrderedSpecByName() + { + var spec = new StoresOrderedSpecByName(); + + var stores = await storeRepository.ListAsync(spec); + + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_LAST_ID); + } + + [Fact] + public async Task ReturnsOrderedStores_GivenStoresOrderedDescendingByNameSpec() + { + var spec = new StoresOrderedDescendingByNameSpec(); + + var stores = await storeRepository.ListAsync(spec); + + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_LAST_ID); + } + + [Fact] + public async Task ReturnsStoreContainingCity1_GivenStoreIncludeProductsSpec() + { + var result = await storeRepository.ListAsync(new StoreSearchByNameOrCitySpec(StoreSeed.VALID_Search_City_Key)); - result.Should().NotBeNull(); - result.Should().ContainSingle(); - result[0].Id.Should().Be(StoreSeed.VALID_Search_ID); - result[0].City.Should().Contain(StoreSeed.VALID_Search_City_Key); - } + result.Should().NotBeNull(); + result.Should().ContainSingle(); + result[0].Id.Should().Be(StoreSeed.VALID_Search_ID); + result[0].City.Should().Contain(StoreSeed.VALID_Search_City_Key); } + } } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Ardalis.Specification.EntityFrameworkCore.csproj b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Ardalis.Specification.EntityFrameworkCore.csproj index 205c3821..db756660 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Ardalis.Specification.EntityFrameworkCore.csproj +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Ardalis.Specification.EntityFrameworkCore.csproj @@ -23,6 +23,7 @@ $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb 9.0 enable + bin\$(Configuration)\Ardalis.Specification.EntityFrameworkCore.xml diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/CachedReadConcurrentDictionary.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/CachedReadConcurrentDictionary.cs index 5ee0096d..5245dfce 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/CachedReadConcurrentDictionary.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/CachedReadConcurrentDictionary.cs @@ -8,226 +8,226 @@ namespace Ardalis.Specification.EntityFrameworkCore { + /// + /// A thread-safe dictionary for read-heavy workloads. + /// + /// The key type. + /// The value type. + internal class CachedReadConcurrentDictionary : IDictionary where TKey : notnull + { /// - /// A thread-safe dictionary for read-heavy workloads. + /// The number of cache misses which are tolerated before the cache is regenerated. /// - /// The key type. - /// The value type. - internal class CachedReadConcurrentDictionary : IDictionary where TKey : notnull + private const int CacheMissesBeforeCaching = 10; + private readonly ConcurrentDictionary dictionary; + private readonly IEqualityComparer? comparer; + + /// + /// Approximate number of reads which did not hit the cache since it was last invalidated. + /// This is used as a heuristic that the dictionary is not being modified frequently with respect to the read volume. + /// + private int cacheMissReads; + + /// + /// Cached version of . + /// + private Dictionary? readCache; + + /// + /// Initializes a new instance of the class. + /// + public CachedReadConcurrentDictionary() { - /// - /// The number of cache misses which are tolerated before the cache is regenerated. - /// - private const int CacheMissesBeforeCaching = 10; - private readonly ConcurrentDictionary dictionary; - private readonly IEqualityComparer? comparer; - - /// - /// Approximate number of reads which did not hit the cache since it was last invalidated. - /// This is used as a heuristic that the dictionary is not being modified frequently with respect to the read volume. - /// - private int cacheMissReads; - - /// - /// Cached version of . - /// - private Dictionary? readCache; - - /// - /// Initializes a new instance of the class. - /// - public CachedReadConcurrentDictionary() - { - this.dictionary = new ConcurrentDictionary(); - } - - /// - /// Initializes a new instance of the class - /// that contains elements copied from the specified collection. - /// - /// - /// The whose elements are copied to the new instance. - /// - public CachedReadConcurrentDictionary(IEnumerable> collection) - { - this.dictionary = new ConcurrentDictionary(collection); - } - - /// - /// Initializes a new instance of the class - /// that contains elements copied from the specified collection and uses the specified - /// . - /// - /// - /// The implementation to use when comparing keys. - /// - public CachedReadConcurrentDictionary(IEqualityComparer comparer) - { - this.comparer = comparer; - this.dictionary = new ConcurrentDictionary(comparer); - } - - /// - /// Initializes a new instance of the - /// class that contains elements copied from the specified collection and uses the specified - /// . - /// - /// - /// The whose elements are copied to the new instance. - /// - /// - /// The implementation to use when comparing keys. - /// - public CachedReadConcurrentDictionary(IEnumerable> collection, IEqualityComparer comparer) - { - this.comparer = comparer; - this.dictionary = new ConcurrentDictionary(collection, comparer); - } + this.dictionary = new ConcurrentDictionary(); + } - /// - IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); + /// + /// Initializes a new instance of the class + /// that contains elements copied from the specified collection. + /// + /// + /// The whose elements are copied to the new instance. + /// + public CachedReadConcurrentDictionary(IEnumerable> collection) + { + this.dictionary = new ConcurrentDictionary(collection); + } - /// - public IEnumerator> GetEnumerator() => this.GetReadDictionary().GetEnumerator(); + /// + /// Initializes a new instance of the class + /// that contains elements copied from the specified collection and uses the specified + /// . + /// + /// + /// The implementation to use when comparing keys. + /// + public CachedReadConcurrentDictionary(IEqualityComparer comparer) + { + this.comparer = comparer; + this.dictionary = new ConcurrentDictionary(comparer); + } - /// - public void Add(KeyValuePair item) - { - ((IDictionary)this.dictionary).Add(item); - this.InvalidateCache(); - } + /// + /// Initializes a new instance of the + /// class that contains elements copied from the specified collection and uses the specified + /// . + /// + /// + /// The whose elements are copied to the new instance. + /// + /// + /// The implementation to use when comparing keys. + /// + public CachedReadConcurrentDictionary(IEnumerable> collection, IEqualityComparer comparer) + { + this.comparer = comparer; + this.dictionary = new ConcurrentDictionary(collection, comparer); + } - /// - public void Clear() - { - this.dictionary.Clear(); - this.InvalidateCache(); - } + /// + IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); - /// - public bool Contains(KeyValuePair item) => this.GetReadDictionary().Contains(item); + /// + public IEnumerator> GetEnumerator() => this.GetReadDictionary().GetEnumerator(); - /// - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { - this.GetReadDictionary().CopyTo(array, arrayIndex); - } + /// + public void Add(KeyValuePair item) + { + ((IDictionary)this.dictionary).Add(item); + this.InvalidateCache(); + } - /// - public bool Remove(KeyValuePair item) - { - var result = ((IDictionary)this.dictionary).Remove(item); - if (result) this.InvalidateCache(); - return result; - } + /// + public void Clear() + { + this.dictionary.Clear(); + this.InvalidateCache(); + } - /// - public int Count => this.GetReadDictionary().Count; + /// + public bool Contains(KeyValuePair item) => this.GetReadDictionary().Contains(item); - /// - public bool IsReadOnly => false; + /// + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + this.GetReadDictionary().CopyTo(array, arrayIndex); + } - /// - public void Add(TKey key, TValue value) - { - ((IDictionary)this.dictionary).Add(key, value); - this.InvalidateCache(); - } - - /// - /// Adds a key/value pair to the if the key does not exist. - /// - /// The key of the element to add. - /// The function used to generate a value for the key - /// The value for the key. This will be either the existing value for the key if the key is already in the dictionary, or the new value if the key was not in the dictionary. - public TValue GetOrAdd(TKey key, Func valueFactory) - { - if (this.GetReadDictionary().TryGetValue(key, out var value)) - { - return value; - } - - value = this.dictionary.GetOrAdd(key, valueFactory); - InvalidateCache(); - - return value; - } - - /// - /// Attempts to add the specified key and value. - /// - /// The key of the element to add. - /// The value of the element to add. The value can be a null reference (Nothing - /// in Visual Basic) for reference types. - /// true if the key/value pair was added successfully; otherwise, false. - public bool TryAdd(TKey key, TValue value) - { - if (this.dictionary.TryAdd(key, value)) - { - this.InvalidateCache(); - return true; - } - - return false; - } + /// + public bool Remove(KeyValuePair item) + { + var result = ((IDictionary)this.dictionary).Remove(item); + if (result) this.InvalidateCache(); + return result; + } - /// - public bool ContainsKey(TKey key) => this.GetReadDictionary().ContainsKey(key); + /// + public int Count => this.GetReadDictionary().Count; - /// - public bool Remove(TKey key) - { - var result = ((IDictionary)this.dictionary).Remove(key); - if (result) this.InvalidateCache(); - return result; - } + /// + public bool IsReadOnly => false; + + /// + public void Add(TKey key, TValue value) + { + ((IDictionary)this.dictionary).Add(key, value); + this.InvalidateCache(); + } + + /// + /// Adds a key/value pair to the if the key does not exist. + /// + /// The key of the element to add. + /// The function used to generate a value for the key + /// The value for the key. This will be either the existing value for the key if the key is already in the dictionary, or the new value if the key was not in the dictionary. + public TValue GetOrAdd(TKey key, Func valueFactory) + { + if (this.GetReadDictionary().TryGetValue(key, out var value)) + { + return value; + } + + value = this.dictionary.GetOrAdd(key, valueFactory); + InvalidateCache(); + + return value; + } + + /// + /// Attempts to add the specified key and value. + /// + /// The key of the element to add. + /// The value of the element to add. The value can be a null reference (Nothing + /// in Visual Basic) for reference types. + /// true if the key/value pair was added successfully; otherwise, false. + public bool TryAdd(TKey key, TValue value) + { + if (this.dictionary.TryAdd(key, value)) + { + this.InvalidateCache(); + return true; + } + + return false; + } + + /// + public bool ContainsKey(TKey key) => this.GetReadDictionary().ContainsKey(key); + + /// + public bool Remove(TKey key) + { + var result = ((IDictionary)this.dictionary).Remove(key); + if (result) this.InvalidateCache(); + return result; + } #if NET6_0_OR_GREATER - /// - public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) => this.GetReadDictionary().TryGetValue(key, out value); + /// + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) => this.GetReadDictionary().TryGetValue(key, out value); #else /// public bool TryGetValue(TKey key, out TValue value) => this.GetReadDictionary().TryGetValue(key, out value); #endif - /// - public TValue this[TKey key] - { - get => this.GetReadDictionary()[key]; - set - { - this.dictionary[key] = value; - this.InvalidateCache(); - } - } + /// + public TValue this[TKey key] + { + get => this.GetReadDictionary()[key]; + set + { + this.dictionary[key] = value; + this.InvalidateCache(); + } + } - /// - public ICollection Keys => this.GetReadDictionary().Keys; + /// + public ICollection Keys => this.GetReadDictionary().Keys; - /// - public ICollection Values => this.GetReadDictionary().Values; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private IDictionary GetReadDictionary() => this.readCache ?? this.GetWithoutCache(); - - private IDictionary GetWithoutCache() - { - // If the dictionary was recently modified or the cache is being recomputed, return the dictionary directly. - if (Interlocked.Increment(ref this.cacheMissReads) < CacheMissesBeforeCaching) - { - return this.dictionary; - } - - // Recompute the cache if too many cache misses have occurred. - this.cacheMissReads = 0; - return this.readCache = new Dictionary(this.dictionary, this.comparer); - } - - private void InvalidateCache() - { - this.cacheMissReads = 0; - this.readCache = null; - } + /// + public ICollection Values => this.GetReadDictionary().Values; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private IDictionary GetReadDictionary() => this.readCache ?? this.GetWithoutCache(); + + private IDictionary GetWithoutCache() + { + // If the dictionary was recently modified or the cache is being recomputed, return the dictionary directly. + if (Interlocked.Increment(ref this.cacheMissReads) < CacheMissesBeforeCaching) + { + return this.dictionary; + } + + // Recompute the cache if too many cache misses have occurred. + this.cacheMissReads = 0; + return this.readCache = new Dictionary(this.dictionary, this.comparer); + } + + private void InvalidateCache() + { + this.cacheMissReads = 0; + this.readCache = null; } + } } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsNoTrackingEvaluator.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsNoTrackingEvaluator.cs index b9f8c88b..b2352cd3 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsNoTrackingEvaluator.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsNoTrackingEvaluator.cs @@ -1,26 +1,26 @@ -using Microsoft.EntityFrameworkCore; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Microsoft.EntityFrameworkCore; namespace Ardalis.Specification.EntityFrameworkCore { - public class AsNoTrackingEvaluator : IEvaluator - { - private AsNoTrackingEvaluator() { } - public static AsNoTrackingEvaluator Instance { get; } = new AsNoTrackingEvaluator(); + public class AsNoTrackingEvaluator : IEvaluator + { + private AsNoTrackingEvaluator() { } + public static AsNoTrackingEvaluator Instance { get; } = new AsNoTrackingEvaluator(); - public bool IsCriteriaEvaluator { get; } = true; + public bool IsCriteriaEvaluator { get; } = true; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - if (specification.AsNoTracking) - { - query = query.AsNoTracking(); - } + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + if (specification.AsNoTracking) + { + query = query.AsNoTracking(); + } - return query; - } + return query; } + } } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsNoTrackingWithIdentityResolutionEvaluator.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsNoTrackingWithIdentityResolutionEvaluator.cs index f0dbbdf7..ccf87541 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsNoTrackingWithIdentityResolutionEvaluator.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsNoTrackingWithIdentityResolutionEvaluator.cs @@ -1,28 +1,28 @@ -using Microsoft.EntityFrameworkCore; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Microsoft.EntityFrameworkCore; namespace Ardalis.Specification.EntityFrameworkCore { #if !NETSTANDARD2_0 - public class AsNoTrackingWithIdentityResolutionEvaluator : IEvaluator - { - private AsNoTrackingWithIdentityResolutionEvaluator() { } - public static AsNoTrackingWithIdentityResolutionEvaluator Instance { get; } = new AsNoTrackingWithIdentityResolutionEvaluator(); + public class AsNoTrackingWithIdentityResolutionEvaluator : IEvaluator + { + private AsNoTrackingWithIdentityResolutionEvaluator() { } + public static AsNoTrackingWithIdentityResolutionEvaluator Instance { get; } = new AsNoTrackingWithIdentityResolutionEvaluator(); - public bool IsCriteriaEvaluator { get; } = true; + public bool IsCriteriaEvaluator { get; } = true; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - if (specification.AsNoTrackingWithIdentityResolution) - { - query = query.AsNoTrackingWithIdentityResolution(); - } + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + if (specification.AsNoTrackingWithIdentityResolution) + { + query = query.AsNoTrackingWithIdentityResolution(); + } - return query; - } + return query; } + } #endif } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsSplitQueryEvaluator.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsSplitQueryEvaluator.cs index dc8e4f79..e2ff7e3c 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsSplitQueryEvaluator.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/AsSplitQueryEvaluator.cs @@ -1,28 +1,28 @@ -using Microsoft.EntityFrameworkCore; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Microsoft.EntityFrameworkCore; namespace Ardalis.Specification.EntityFrameworkCore { #if !NETSTANDARD2_0 - public class AsSplitQueryEvaluator : IEvaluator - { - private AsSplitQueryEvaluator() { } - public static AsSplitQueryEvaluator Instance { get; } = new AsSplitQueryEvaluator(); + public class AsSplitQueryEvaluator : IEvaluator + { + private AsSplitQueryEvaluator() { } + public static AsSplitQueryEvaluator Instance { get; } = new AsSplitQueryEvaluator(); - public bool IsCriteriaEvaluator { get; } = true; + public bool IsCriteriaEvaluator { get; } = true; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - if (specification.AsSplitQuery) - { - query = query.AsSplitQuery(); - } + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + if (specification.AsSplitQuery) + { + query = query.AsSplitQuery(); + } - return query; - } + return query; } + } #endif } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/IgnoreQueryFiltersEvaluator.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/IgnoreQueryFiltersEvaluator.cs index f54c59ee..b03b5128 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/IgnoreQueryFiltersEvaluator.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/IgnoreQueryFiltersEvaluator.cs @@ -1,27 +1,27 @@ -using Microsoft.EntityFrameworkCore; -using System.Linq; +using System.Linq; +using Microsoft.EntityFrameworkCore; namespace Ardalis.Specification.EntityFrameworkCore { - /// - /// This evaluator applies EF Core's IgnoreQueryFilters feature to a given query - /// See: https://docs.microsoft.com/en-us/ef/core/querying/filters - /// - public class IgnoreQueryFiltersEvaluator : IEvaluator - { - private IgnoreQueryFiltersEvaluator() { } - public static IgnoreQueryFiltersEvaluator Instance { get; } = new IgnoreQueryFiltersEvaluator(); + /// + /// This evaluator applies EF Core's IgnoreQueryFilters feature to a given query + /// See: https://docs.microsoft.com/en-us/ef/core/querying/filters + /// + public class IgnoreQueryFiltersEvaluator : IEvaluator + { + private IgnoreQueryFiltersEvaluator() { } + public static IgnoreQueryFiltersEvaluator Instance { get; } = new IgnoreQueryFiltersEvaluator(); - public bool IsCriteriaEvaluator { get; } = true; + public bool IsCriteriaEvaluator { get; } = true; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - if (specification.IgnoreQueryFilters) - { - query = query.IgnoreQueryFilters(); - } + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + if (specification.IgnoreQueryFilters) + { + query = query.IgnoreQueryFilters(); + } - return query; - } + return query; } + } } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/IncludeEvaluator.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/IncludeEvaluator.cs index 24f5214f..e63a0bd3 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/IncludeEvaluator.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/IncludeEvaluator.cs @@ -8,186 +8,186 @@ namespace Ardalis.Specification.EntityFrameworkCore { - public class IncludeEvaluator : IEvaluator - { - private static readonly MethodInfo IncludeMethodInfo = typeof(EntityFrameworkQueryableExtensions) - .GetTypeInfo().GetDeclaredMethods(nameof(EntityFrameworkQueryableExtensions.Include)) - .Single(mi => mi.GetGenericArguments().Length == 2 - && mi.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(IQueryable<>) + public class IncludeEvaluator : IEvaluator + { + private static readonly MethodInfo IncludeMethodInfo = typeof(EntityFrameworkQueryableExtensions) + .GetTypeInfo().GetDeclaredMethods(nameof(EntityFrameworkQueryableExtensions.Include)) + .Single(mi => mi.GetGenericArguments().Length == 2 + && mi.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(IQueryable<>) + && mi.GetParameters()[1].ParameterType.GetGenericTypeDefinition() == typeof(Expression<>)); + + private static readonly MethodInfo ThenIncludeAfterReferenceMethodInfo + = typeof(EntityFrameworkQueryableExtensions) + .GetTypeInfo().GetDeclaredMethods(nameof(EntityFrameworkQueryableExtensions.ThenInclude)) + .Single(mi => mi.GetGenericArguments().Length == 3 + && mi.GetParameters()[0].ParameterType.GenericTypeArguments[1].IsGenericParameter + && mi.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(IIncludableQueryable<,>) && mi.GetParameters()[1].ParameterType.GetGenericTypeDefinition() == typeof(Expression<>)); - private static readonly MethodInfo ThenIncludeAfterReferenceMethodInfo - = typeof(EntityFrameworkQueryableExtensions) - .GetTypeInfo().GetDeclaredMethods(nameof(EntityFrameworkQueryableExtensions.ThenInclude)) - .Single(mi => mi.GetGenericArguments().Length == 3 - && mi.GetParameters()[0].ParameterType.GenericTypeArguments[1].IsGenericParameter - && mi.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(IIncludableQueryable<,>) - && mi.GetParameters()[1].ParameterType.GetGenericTypeDefinition() == typeof(Expression<>)); - - private static readonly MethodInfo ThenIncludeAfterEnumerableMethodInfo - = typeof(EntityFrameworkQueryableExtensions) - .GetTypeInfo().GetDeclaredMethods(nameof(EntityFrameworkQueryableExtensions.ThenInclude)) - .Where(mi => mi.GetGenericArguments().Length == 3) - .Single( - mi => - { - var typeInfo = mi.GetParameters()[0].ParameterType.GenericTypeArguments[1]; - - return typeInfo.IsGenericType - && typeInfo.GetGenericTypeDefinition() == typeof(IEnumerable<>) - && mi.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(IIncludableQueryable<,>) - && mi.GetParameters()[1].ParameterType.GetGenericTypeDefinition() == typeof(Expression<>); - }); - - private static readonly CachedReadConcurrentDictionary<(Type EntityType, Type PropertyType, Type? PreviousPropertyType), Lazy>> DelegatesCache = - new CachedReadConcurrentDictionary<(Type EntityType, Type PropertyType, Type? PreviousPropertyType), Lazy>>(); - - private readonly bool cacheEnabled; - - private IncludeEvaluator(bool cacheEnabled) - { - this.cacheEnabled = cacheEnabled; - } + private static readonly MethodInfo ThenIncludeAfterEnumerableMethodInfo + = typeof(EntityFrameworkQueryableExtensions) + .GetTypeInfo().GetDeclaredMethods(nameof(EntityFrameworkQueryableExtensions.ThenInclude)) + .Where(mi => mi.GetGenericArguments().Length == 3) + .Single( + mi => + { + var typeInfo = mi.GetParameters()[0].ParameterType.GenericTypeArguments[1]; - /// - /// instance without any additional features. - /// - public static IncludeEvaluator Default { get; } = new IncludeEvaluator(false); + return typeInfo.IsGenericType + && typeInfo.GetGenericTypeDefinition() == typeof(IEnumerable<>) + && mi.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(IIncludableQueryable<,>) + && mi.GetParameters()[1].ParameterType.GetGenericTypeDefinition() == typeof(Expression<>); + }); - /// - /// instance with caching to provide better performance. - /// - public static IncludeEvaluator Cached { get; } = new IncludeEvaluator(true); + private static readonly CachedReadConcurrentDictionary<(Type EntityType, Type PropertyType, Type? PreviousPropertyType), Lazy>> DelegatesCache = + new CachedReadConcurrentDictionary<(Type EntityType, Type PropertyType, Type? PreviousPropertyType), Lazy>>(); - public bool IsCriteriaEvaluator => false; + private readonly bool cacheEnabled; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - foreach (var includeString in specification.IncludeStrings) - { - query = query.Include(includeString); - } - - foreach (var includeInfo in specification.IncludeExpressions) - { - if (includeInfo.Type == IncludeTypeEnum.Include) - { - query = this.BuildInclude(query, includeInfo); - } - else if (includeInfo.Type == IncludeTypeEnum.ThenInclude) - { - query = this.BuildThenInclude(query, includeInfo); - } - } + private IncludeEvaluator(bool cacheEnabled) + { + this.cacheEnabled = cacheEnabled; + } - return query; - } + /// + /// instance without any additional features. + /// + public static IncludeEvaluator Default { get; } = new IncludeEvaluator(false); + + /// + /// instance with caching to provide better performance. + /// + public static IncludeEvaluator Cached { get; } = new IncludeEvaluator(true); - private IQueryable BuildInclude(IQueryable query, IncludeExpressionInfo includeInfo) + public bool IsCriteriaEvaluator => false; + + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + foreach (var includeString in specification.IncludeStrings) + { + query = query.Include(includeString); + } + + foreach (var includeInfo in specification.IncludeExpressions) + { + if (includeInfo.Type == IncludeTypeEnum.Include) { - _ = includeInfo ?? throw new ArgumentNullException(nameof(includeInfo)); + query = this.BuildInclude(query, includeInfo); + } + else if (includeInfo.Type == IncludeTypeEnum.ThenInclude) + { + query = this.BuildThenInclude(query, includeInfo); + } + } - if (!this.cacheEnabled) - { - var result = IncludeMethodInfo.MakeGenericMethod(includeInfo.EntityType, includeInfo.PropertyType).Invoke(null, new object[] { query, includeInfo.LambdaExpression }); + return query; + } - _ = result ?? throw new TargetException(); + private IQueryable BuildInclude(IQueryable query, IncludeExpressionInfo includeInfo) + { + _ = includeInfo ?? throw new ArgumentNullException(nameof(includeInfo)); - return (IQueryable)result; - } + if (!this.cacheEnabled) + { + var result = IncludeMethodInfo.MakeGenericMethod(includeInfo.EntityType, includeInfo.PropertyType).Invoke(null, new object[] { query, includeInfo.LambdaExpression }); - var include = DelegatesCache.GetOrAdd((includeInfo.EntityType, includeInfo.PropertyType, null), CreateIncludeDelegate).Value; + _ = result ?? throw new TargetException(); - return (IQueryable)include(query, includeInfo.LambdaExpression); - } + return (IQueryable)result; + } - private IQueryable BuildThenInclude(IQueryable query, IncludeExpressionInfo includeInfo) - { - _ = includeInfo ?? throw new ArgumentNullException(nameof(includeInfo)); - _ = includeInfo.PreviousPropertyType ?? throw new ArgumentNullException(nameof(includeInfo.PreviousPropertyType)); + var include = DelegatesCache.GetOrAdd((includeInfo.EntityType, includeInfo.PropertyType, null), CreateIncludeDelegate).Value; + + return (IQueryable)include(query, includeInfo.LambdaExpression); + } - if (!this.cacheEnabled) - { - var result = (IsGenericEnumerable(includeInfo.PreviousPropertyType, out var previousPropertyType) - ? ThenIncludeAfterEnumerableMethodInfo - : ThenIncludeAfterReferenceMethodInfo).MakeGenericMethod(includeInfo.EntityType, previousPropertyType, includeInfo.PropertyType) - .Invoke(null, new object[] { query, includeInfo.LambdaExpression, }); + private IQueryable BuildThenInclude(IQueryable query, IncludeExpressionInfo includeInfo) + { + _ = includeInfo ?? throw new ArgumentNullException(nameof(includeInfo)); + _ = includeInfo.PreviousPropertyType ?? throw new ArgumentNullException(nameof(includeInfo.PreviousPropertyType)); - _ = result ?? throw new TargetException(); + if (!this.cacheEnabled) + { + var result = (IsGenericEnumerable(includeInfo.PreviousPropertyType, out var previousPropertyType) + ? ThenIncludeAfterEnumerableMethodInfo + : ThenIncludeAfterReferenceMethodInfo).MakeGenericMethod(includeInfo.EntityType, previousPropertyType, includeInfo.PropertyType) + .Invoke(null, new object[] { query, includeInfo.LambdaExpression, }); - return (IQueryable)result; - } + _ = result ?? throw new TargetException(); - var thenInclude = DelegatesCache.GetOrAdd((includeInfo.EntityType, includeInfo.PropertyType, includeInfo.PreviousPropertyType), CreateThenIncludeDelegate).Value; + return (IQueryable)result; + } - return (IQueryable)thenInclude(query, includeInfo.LambdaExpression); - } + var thenInclude = DelegatesCache.GetOrAdd((includeInfo.EntityType, includeInfo.PropertyType, includeInfo.PreviousPropertyType), CreateThenIncludeDelegate).Value; - // (source, selector) => EntityFrameworkQueryableExtensions.Include((IQueryable)source, (Expression>)selector); - private static Lazy> CreateIncludeDelegate((Type EntityType, Type PropertyType, Type? PreviousPropertyType) cacheKey) - => new Lazy>(() => - { - var concreteInclude = IncludeMethodInfo.MakeGenericMethod(cacheKey.EntityType, cacheKey.PropertyType); - var sourceParameter = Expression.Parameter(typeof(IQueryable)); - var selectorParameter = Expression.Parameter(typeof(LambdaExpression)); - - var call = Expression.Call( - concreteInclude, - Expression.Convert(sourceParameter, typeof(IQueryable<>).MakeGenericType(cacheKey.EntityType)), - Expression.Convert(selectorParameter, typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(cacheKey.EntityType, cacheKey.PropertyType)))); - - var lambda = Expression.Lambda>(call, sourceParameter, selectorParameter); - - return lambda.Compile(); - }); - - // ((source, selector) => - // EntityFrameworkQueryableExtensions.ThenInclude( - // (IIncludableQueryable)source, - // (Expression>)selector); - // (source, selector) => - // EntityFrameworkQueryableExtensions.ThenInclude( - // (IIncludableQueryable>)source, - // (Expression>)selector); - private static Lazy> CreateThenIncludeDelegate((Type EntityType, Type PropertyType, Type? PreviousPropertyType) cacheKey) - => new Lazy>(() => - { - _ = cacheKey.PreviousPropertyType ?? throw new ArgumentNullException(nameof(cacheKey.PreviousPropertyType)); - - MethodInfo thenIncludeInfo = ThenIncludeAfterReferenceMethodInfo; - if (IsGenericEnumerable(cacheKey.PreviousPropertyType, out var previousPropertyType)) - { - thenIncludeInfo = ThenIncludeAfterEnumerableMethodInfo; - } + return (IQueryable)thenInclude(query, includeInfo.LambdaExpression); + } - var concreteThenInclude = thenIncludeInfo.MakeGenericMethod(cacheKey.EntityType, previousPropertyType, cacheKey.PropertyType); - var sourceParameter = Expression.Parameter(typeof(IQueryable)); - var selectorParameter = Expression.Parameter(typeof(LambdaExpression)); + // (source, selector) => EntityFrameworkQueryableExtensions.Include((IQueryable)source, (Expression>)selector); + private static Lazy> CreateIncludeDelegate((Type EntityType, Type PropertyType, Type? PreviousPropertyType) cacheKey) + => new Lazy>(() => + { + var concreteInclude = IncludeMethodInfo.MakeGenericMethod(cacheKey.EntityType, cacheKey.PropertyType); + var sourceParameter = Expression.Parameter(typeof(IQueryable)); + var selectorParameter = Expression.Parameter(typeof(LambdaExpression)); + + var call = Expression.Call( + concreteInclude, + Expression.Convert(sourceParameter, typeof(IQueryable<>).MakeGenericType(cacheKey.EntityType)), + Expression.Convert(selectorParameter, typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(cacheKey.EntityType, cacheKey.PropertyType)))); + + var lambda = Expression.Lambda>(call, sourceParameter, selectorParameter); + + return lambda.Compile(); + }); + + // ((source, selector) => + // EntityFrameworkQueryableExtensions.ThenInclude( + // (IIncludableQueryable)source, + // (Expression>)selector); + // (source, selector) => + // EntityFrameworkQueryableExtensions.ThenInclude( + // (IIncludableQueryable>)source, + // (Expression>)selector); + private static Lazy> CreateThenIncludeDelegate((Type EntityType, Type PropertyType, Type? PreviousPropertyType) cacheKey) + => new Lazy>(() => + { + _ = cacheKey.PreviousPropertyType ?? throw new ArgumentNullException(nameof(cacheKey.PreviousPropertyType)); - var call = Expression.Call( - concreteThenInclude, - Expression.Convert( - sourceParameter, - typeof(IIncludableQueryable<,>).MakeGenericType(cacheKey.EntityType, cacheKey.PreviousPropertyType)), // cacheKey.PreviousPropertyType must be exact type, not generic type argument - Expression.Convert(selectorParameter, typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(previousPropertyType, cacheKey.PropertyType)))); + MethodInfo thenIncludeInfo = ThenIncludeAfterReferenceMethodInfo; + if (IsGenericEnumerable(cacheKey.PreviousPropertyType, out var previousPropertyType)) + { + thenIncludeInfo = ThenIncludeAfterEnumerableMethodInfo; + } - var lambda = Expression.Lambda>(call, sourceParameter, selectorParameter); + var concreteThenInclude = thenIncludeInfo.MakeGenericMethod(cacheKey.EntityType, previousPropertyType, cacheKey.PropertyType); + var sourceParameter = Expression.Parameter(typeof(IQueryable)); + var selectorParameter = Expression.Parameter(typeof(LambdaExpression)); - return lambda.Compile(); - }); + var call = Expression.Call( + concreteThenInclude, + Expression.Convert( + sourceParameter, + typeof(IIncludableQueryable<,>).MakeGenericType(cacheKey.EntityType, cacheKey.PreviousPropertyType)), // cacheKey.PreviousPropertyType must be exact type, not generic type argument + Expression.Convert(selectorParameter, typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(previousPropertyType, cacheKey.PropertyType)))); - private static bool IsGenericEnumerable(Type type, out Type propertyType) - { - if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) - { - propertyType = type.GenericTypeArguments[0]; + var lambda = Expression.Lambda>(call, sourceParameter, selectorParameter); - return true; - } + return lambda.Compile(); + }); - propertyType = type; + private static bool IsGenericEnumerable(Type type, out Type propertyType) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + { + propertyType = type.GenericTypeArguments[0]; - return false; - } + return true; + } + + propertyType = type; + + return false; } + } } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/SearchEvaluator.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/SearchEvaluator.cs index 42f697a9..121d4319 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/SearchEvaluator.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/SearchEvaluator.cs @@ -2,21 +2,21 @@ namespace Ardalis.Specification.EntityFrameworkCore { - public class SearchEvaluator : IEvaluator - { - private SearchEvaluator() { } - public static SearchEvaluator Instance { get; } = new SearchEvaluator(); + public class SearchEvaluator : IEvaluator + { + private SearchEvaluator() { } + public static SearchEvaluator Instance { get; } = new SearchEvaluator(); - public bool IsCriteriaEvaluator { get; } = true; + public bool IsCriteriaEvaluator { get; } = true; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - foreach (var searchCriteria in specification.SearchCriterias.GroupBy(x => x.SearchGroup)) - { - query = query.Search(searchCriteria); - } + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + foreach (var searchCriteria in specification.SearchCriterias.GroupBy(x => x.SearchGroup)) + { + query = query.Search(searchCriteria); + } - return query; - } + return query; } + } } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/SpecificationEvaluator.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/SpecificationEvaluator.cs index b362aed5..95bb74ee 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/SpecificationEvaluator.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Evaluators/SpecificationEvaluator.cs @@ -4,26 +4,26 @@ namespace Ardalis.Specification.EntityFrameworkCore { - /// - public class SpecificationEvaluator : ISpecificationEvaluator - { - // Will use singleton for default configuration. Yet, it can be instantiated if necessary, with default or provided evaluators. - /// - /// instance with default evaluators and without any additional features enabled. - /// - public static SpecificationEvaluator Default { get; } = new SpecificationEvaluator(); + /// + public class SpecificationEvaluator : ISpecificationEvaluator + { + // Will use singleton for default configuration. Yet, it can be instantiated if necessary, with default or provided evaluators. + /// + /// instance with default evaluators and without any additional features enabled. + /// + public static SpecificationEvaluator Default { get; } = new SpecificationEvaluator(); - /// - /// instance with default evaluators and enabled caching. - /// - public static SpecificationEvaluator Cached { get; } = new SpecificationEvaluator(true); + /// + /// instance with default evaluators and enabled caching. + /// + public static SpecificationEvaluator Cached { get; } = new SpecificationEvaluator(true); - private readonly List evaluators = new List(); + private readonly List evaluators = new List(); - public SpecificationEvaluator(bool cacheEnabled = false) - { - this.evaluators.AddRange(new IEvaluator[] - { + public SpecificationEvaluator(bool cacheEnabled = false) + { + this.evaluators.AddRange(new IEvaluator[] + { WhereEvaluator.Instance, SearchEvaluator.Instance, cacheEnabled ? IncludeEvaluator.Cached : IncludeEvaluator.Default, @@ -35,38 +35,38 @@ public SpecificationEvaluator(bool cacheEnabled = false) AsSplitQueryEvaluator.Instance, AsNoTrackingWithIdentityResolutionEvaluator.Instance #endif - }); - } + }); + } - public SpecificationEvaluator(IEnumerable evaluators) - { - this.evaluators.AddRange(evaluators); - } + public SpecificationEvaluator(IEnumerable evaluators) + { + this.evaluators.AddRange(evaluators); + } - /// - public virtual IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - if (specification is null) throw new ArgumentNullException("Specification is required"); - if (specification.Selector is null) throw new SelectorNotFoundException(); + /// + public virtual IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + if (specification is null) throw new ArgumentNullException("Specification is required"); + if (specification.Selector is null) throw new SelectorNotFoundException(); - query = GetQuery(query, (ISpecification)specification); + query = GetQuery(query, (ISpecification)specification); - return query.Select(specification.Selector); - } + return query.Select(specification.Selector); + } - /// - public virtual IQueryable GetQuery(IQueryable query, ISpecification specification, bool evaluateCriteriaOnly = false) where T : class - { - if (specification is null) throw new ArgumentNullException("Specification is required"); + /// + public virtual IQueryable GetQuery(IQueryable query, ISpecification specification, bool evaluateCriteriaOnly = false) where T : class + { + if (specification is null) throw new ArgumentNullException("Specification is required"); - var evaluators = evaluateCriteriaOnly ? this.evaluators.Where(x => x.IsCriteriaEvaluator) : this.evaluators; + var evaluators = evaluateCriteriaOnly ? this.evaluators.Where(x => x.IsCriteriaEvaluator) : this.evaluators; - foreach (var evaluator in evaluators) - { - query = evaluator.GetQuery(query, specification); - } + foreach (var evaluator in evaluators) + { + query = evaluator.GetQuery(query, specification); + } - return query; - } + return query; } + } } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/DbSetExtensions.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/DbSetExtensions.cs index a4529751..c27133f4 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/DbSetExtensions.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/DbSetExtensions.cs @@ -1,35 +1,35 @@ -using Microsoft.EntityFrameworkCore; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; namespace Ardalis.Specification.EntityFrameworkCore { - public static class DbSetExtensions + public static class DbSetExtensions + { + public static async Task> ToListAsync(this DbSet source, ISpecification specification, CancellationToken cancellationToken = default) where TSource : class { - public static async Task> ToListAsync(this DbSet source, ISpecification specification, CancellationToken cancellationToken = default) where TSource : class - { - var result = await SpecificationEvaluator.Default.GetQuery(source, specification).ToListAsync(cancellationToken); + var result = await SpecificationEvaluator.Default.GetQuery(source, specification).ToListAsync(cancellationToken); - return specification.PostProcessingAction == null - ? result - : specification.PostProcessingAction(result).ToList(); - } + return specification.PostProcessingAction == null + ? result + : specification.PostProcessingAction(result).ToList(); + } - public static async Task> ToEnumerableAsync(this DbSet source, ISpecification specification, CancellationToken cancellationToken = default) where TSource : class - { - var result = await SpecificationEvaluator.Default.GetQuery(source, specification).ToListAsync(cancellationToken); + public static async Task> ToEnumerableAsync(this DbSet source, ISpecification specification, CancellationToken cancellationToken = default) where TSource : class + { + var result = await SpecificationEvaluator.Default.GetQuery(source, specification).ToListAsync(cancellationToken); - return specification.PostProcessingAction == null - ? result - : specification.PostProcessingAction(result); - } + return specification.PostProcessingAction == null + ? result + : specification.PostProcessingAction(result); + } - public static IQueryable WithSpecification(this IQueryable source, ISpecification specification, ISpecificationEvaluator? evaluator = null) where TSource : class - { - evaluator = evaluator ?? SpecificationEvaluator.Default; - return evaluator.GetQuery(source, specification); - } + public static IQueryable WithSpecification(this IQueryable source, ISpecification specification, ISpecificationEvaluator? evaluator = null) where TSource : class + { + evaluator = evaluator ?? SpecificationEvaluator.Default; + return evaluator.GetQuery(source, specification); } + } } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/ParameterReplacerVisitor.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/ParameterReplacerVisitor.cs index cd2fbb83..9c2e7b09 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/ParameterReplacerVisitor.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/ParameterReplacerVisitor.cs @@ -2,32 +2,32 @@ namespace Ardalis.Specification.EntityFrameworkCore { - internal class ParameterReplacerVisitor : ExpressionVisitor - { - private readonly Expression newExpression; - private readonly ParameterExpression oldParameter; + internal class ParameterReplacerVisitor : ExpressionVisitor + { + private readonly Expression newExpression; + private readonly ParameterExpression oldParameter; - private ParameterReplacerVisitor(ParameterExpression oldParameter, Expression newExpression) - { - this.oldParameter = oldParameter; - this.newExpression = newExpression; - } + private ParameterReplacerVisitor(ParameterExpression oldParameter, Expression newExpression) + { + this.oldParameter = oldParameter; + this.newExpression = newExpression; + } - internal static Expression Replace(Expression expression, ParameterExpression oldParameter, Expression newExpression) - { - return new ParameterReplacerVisitor(oldParameter, newExpression).Visit(expression); - } + internal static Expression Replace(Expression expression, ParameterExpression oldParameter, Expression newExpression) + { + return new ParameterReplacerVisitor(oldParameter, newExpression).Visit(expression); + } - protected override Expression VisitParameter(ParameterExpression p) - { - if (p == oldParameter) - { - return newExpression; - } - else - { - return p; - } - } + protected override Expression VisitParameter(ParameterExpression p) + { + if (p == oldParameter) + { + return newExpression; + } + else + { + return p; + } } -} \ No newline at end of file + } +} diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/SearchExtension.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/SearchExtension.cs index 4d6c2ede..bd83aea6 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/SearchExtension.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/Extensions/SearchExtension.cs @@ -8,53 +8,53 @@ namespace Ardalis.Specification.EntityFrameworkCore { - public static class SearchExtension + public static class SearchExtension + { + private static readonly MethodInfo LikeMethodInfo = typeof(DbFunctionsExtensions) + .GetMethod(nameof(DbFunctionsExtensions.Like), new Type[] { typeof(DbFunctions), typeof(string), typeof(string) }) + ?? throw new TargetException("The EF.Functions.Like not found"); + + private static readonly MemberExpression Functions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions)) + ?? throw new TargetException("The EF.Functions not found!")); + + /// + /// Filters by applying an 'SQL LIKE' operation to it. + /// + /// The type being queried against. + /// The sequence of + /// + /// + /// Selector, the property to apply the SQL LIKE against. + /// SearchTerm, the value to use for the SQL LIKE. + /// + /// + /// + public static IQueryable Search(this IQueryable source, IEnumerable> criterias) { - private static readonly MethodInfo LikeMethodInfo = typeof(DbFunctionsExtensions) - .GetMethod(nameof(DbFunctionsExtensions.Like), new Type[] { typeof(DbFunctions), typeof(string), typeof(string) }) - ?? throw new TargetException("The EF.Functions.Like not found"); - - private static readonly MemberExpression Functions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions)) - ?? throw new TargetException("The EF.Functions not found!")); - - /// - /// Filters by applying an 'SQL LIKE' operation to it. - /// - /// The type being queried against. - /// The sequence of - /// - /// - /// Selector, the property to apply the SQL LIKE against. - /// SearchTerm, the value to use for the SQL LIKE. - /// - /// - /// - public static IQueryable Search(this IQueryable source, IEnumerable> criterias) - { - Expression? expr = null; - var parameter = Expression.Parameter(typeof(T), "x"); - - foreach (var criteria in criterias) - { - if (string.IsNullOrEmpty(criteria.SearchTerm)) - continue; - - var propertySelector = ParameterReplacerVisitor.Replace(criteria.Selector, criteria.Selector.Parameters[0], parameter) as LambdaExpression; - _ = propertySelector ?? throw new InvalidExpressionException(); - - var likeExpression = Expression.Call( - null, - LikeMethodInfo, - Functions, - propertySelector.Body, - Expression.Constant(criteria.SearchTerm)); - - expr = expr == null ? (Expression)likeExpression : Expression.OrElse(expr, likeExpression); - } - - return expr == null - ? source - : source.Where(Expression.Lambda>(expr, parameter)); - } + Expression? expr = null; + var parameter = Expression.Parameter(typeof(T), "x"); + + foreach (var criteria in criterias) + { + if (string.IsNullOrEmpty(criteria.SearchTerm)) + continue; + + var propertySelector = ParameterReplacerVisitor.Replace(criteria.Selector, criteria.Selector.Parameters[0], parameter) as LambdaExpression; + _ = propertySelector ?? throw new InvalidExpressionException(); + + var likeExpression = Expression.Call( + null, + LikeMethodInfo, + Functions, + propertySelector.Body, + Expression.Constant(criteria.SearchTerm)); + + expr = expr == null ? (Expression)likeExpression : Expression.OrElse(expr, likeExpression); + } + + return expr == null + ? source + : source.Where(Expression.Lambda>(expr, parameter)); } + } } diff --git a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/RepositoryBaseOfT.cs b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/RepositoryBaseOfT.cs index d2c32187..82f7be8a 100644 --- a/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/RepositoryBaseOfT.cs +++ b/Specification.EntityFrameworkCore/src/Ardalis.Specification.EntityFrameworkCore/RepositoryBaseOfT.cs @@ -7,143 +7,143 @@ namespace Ardalis.Specification.EntityFrameworkCore { + /// + public abstract class RepositoryBase : IRepositoryBase where T : class + { + private readonly DbContext dbContext; + private readonly ISpecificationEvaluator specificationEvaluator; + + public RepositoryBase(DbContext dbContext) + : this(dbContext, SpecificationEvaluator.Default) + { + } + + /// + public RepositoryBase(DbContext dbContext, ISpecificationEvaluator specificationEvaluator) + { + this.dbContext = dbContext; + this.specificationEvaluator = specificationEvaluator; + } + + /// + public virtual async Task AddAsync(T entity, CancellationToken cancellationToken = default) + { + dbContext.Set().Add(entity); + + await SaveChangesAsync(cancellationToken); + + return entity; + } /// - public abstract class RepositoryBase : IRepositoryBase where T : class - { - private readonly DbContext dbContext; - private readonly ISpecificationEvaluator specificationEvaluator; - - public RepositoryBase(DbContext dbContext) - : this(dbContext, SpecificationEvaluator.Default) - { - } - - /// - public RepositoryBase(DbContext dbContext, ISpecificationEvaluator specificationEvaluator) - { - this.dbContext = dbContext; - this.specificationEvaluator = specificationEvaluator; - } - - /// - public virtual async Task AddAsync(T entity, CancellationToken cancellationToken = default) - { - dbContext.Set().Add(entity); - - await SaveChangesAsync(cancellationToken); - - return entity; - } - /// - public virtual async Task UpdateAsync(T entity, CancellationToken cancellationToken = default) - { - dbContext.Set().Update(entity); - - await SaveChangesAsync(cancellationToken); - } - /// - public virtual async Task DeleteAsync(T entity, CancellationToken cancellationToken = default) - { - dbContext.Set().Remove(entity); - - await SaveChangesAsync(cancellationToken); - } - /// - public virtual async Task DeleteRangeAsync(IEnumerable entities, CancellationToken cancellationToken = default) - { - dbContext.Set().RemoveRange(entities); - - await SaveChangesAsync(cancellationToken); - } - /// - public virtual async Task SaveChangesAsync(CancellationToken cancellationToken = default) - { - return await dbContext.SaveChangesAsync(cancellationToken); - } - - /// - public virtual async Task GetByIdAsync(TId id, CancellationToken cancellationToken = default) where TId : notnull - { - return await dbContext.Set().FindAsync(new object[] { id }, cancellationToken: cancellationToken); - } - /// - public virtual async Task GetBySpecAsync(Spec specification, CancellationToken cancellationToken = default) where Spec : ISpecification, ISingleResultSpecification - { - return await ApplySpecification(specification).FirstOrDefaultAsync(cancellationToken); - } - /// - public virtual async Task GetBySpecAsync(ISpecification specification, CancellationToken cancellationToken = default) - { - return await ApplySpecification(specification).FirstOrDefaultAsync(cancellationToken); - } - - /// - public virtual async Task> ListAsync(CancellationToken cancellationToken = default) - { - return await dbContext.Set().ToListAsync(cancellationToken); - } - /// - public virtual async Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default) - { - var queryResult = await ApplySpecification(specification).ToListAsync(cancellationToken); - - return specification.PostProcessingAction == null ? queryResult : specification.PostProcessingAction(queryResult).ToList(); - } - /// - public virtual async Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default) - { - var queryResult = await ApplySpecification(specification).ToListAsync(cancellationToken); - - return specification.PostProcessingAction == null ? queryResult : specification.PostProcessingAction(queryResult).ToList(); - } - - /// - public virtual async Task CountAsync(ISpecification specification, CancellationToken cancellationToken = default) - { - return await ApplySpecification(specification, true).CountAsync(cancellationToken); - } - - /// - public virtual async Task CountAsync(CancellationToken cancellationToken = default) - { - return await dbContext.Set().CountAsync(cancellationToken); - } - - /// - public virtual async Task AnyAsync(ISpecification specification, CancellationToken cancellationToken = default) - { - return await ApplySpecification(specification, true).AnyAsync(cancellationToken); - } - - /// - public virtual async Task AnyAsync(CancellationToken cancellationToken = default) - { - return await dbContext.Set().AnyAsync(cancellationToken); - } - - /// - /// Filters the entities of , to those that match the encapsulated query logic of the - /// . - /// - /// The encapsulated query logic. - /// The filtered entities as an . - protected virtual IQueryable ApplySpecification(ISpecification specification, bool evaluateCriteriaOnly = false) - { - return specificationEvaluator.GetQuery(dbContext.Set().AsQueryable(), specification, evaluateCriteriaOnly); - } - /// - /// Filters all entities of , that matches the encapsulated query logic of the - /// , from the database. - /// - /// Projects each entity into a new form, being . - /// - /// - /// The type of the value returned by the projection. - /// The encapsulated query logic. - /// The filtered projected entities as an . - protected virtual IQueryable ApplySpecification(ISpecification specification) - { - return specificationEvaluator.GetQuery(dbContext.Set().AsQueryable(), specification); - } - } -} \ No newline at end of file + public virtual async Task UpdateAsync(T entity, CancellationToken cancellationToken = default) + { + dbContext.Set().Update(entity); + + await SaveChangesAsync(cancellationToken); + } + /// + public virtual async Task DeleteAsync(T entity, CancellationToken cancellationToken = default) + { + dbContext.Set().Remove(entity); + + await SaveChangesAsync(cancellationToken); + } + /// + public virtual async Task DeleteRangeAsync(IEnumerable entities, CancellationToken cancellationToken = default) + { + dbContext.Set().RemoveRange(entities); + + await SaveChangesAsync(cancellationToken); + } + /// + public virtual async Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + return await dbContext.SaveChangesAsync(cancellationToken); + } + + /// + public virtual async Task GetByIdAsync(TId id, CancellationToken cancellationToken = default) where TId : notnull + { + return await dbContext.Set().FindAsync(new object[] { id }, cancellationToken: cancellationToken); + } + /// + public virtual async Task GetBySpecAsync(Spec specification, CancellationToken cancellationToken = default) where Spec : ISpecification, ISingleResultSpecification + { + return await ApplySpecification(specification).FirstOrDefaultAsync(cancellationToken); + } + /// + public virtual async Task GetBySpecAsync(ISpecification specification, CancellationToken cancellationToken = default) + { + return await ApplySpecification(specification).FirstOrDefaultAsync(cancellationToken); + } + + /// + public virtual async Task> ListAsync(CancellationToken cancellationToken = default) + { + return await dbContext.Set().ToListAsync(cancellationToken); + } + /// + public virtual async Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default) + { + var queryResult = await ApplySpecification(specification).ToListAsync(cancellationToken); + + return specification.PostProcessingAction == null ? queryResult : specification.PostProcessingAction(queryResult).ToList(); + } + /// + public virtual async Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default) + { + var queryResult = await ApplySpecification(specification).ToListAsync(cancellationToken); + + return specification.PostProcessingAction == null ? queryResult : specification.PostProcessingAction(queryResult).ToList(); + } + + /// + public virtual async Task CountAsync(ISpecification specification, CancellationToken cancellationToken = default) + { + return await ApplySpecification(specification, true).CountAsync(cancellationToken); + } + + /// + public virtual async Task CountAsync(CancellationToken cancellationToken = default) + { + return await dbContext.Set().CountAsync(cancellationToken); + } + + /// + public virtual async Task AnyAsync(ISpecification specification, CancellationToken cancellationToken = default) + { + return await ApplySpecification(specification, true).AnyAsync(cancellationToken); + } + + /// + public virtual async Task AnyAsync(CancellationToken cancellationToken = default) + { + return await dbContext.Set().AnyAsync(cancellationToken); + } + + /// + /// Filters the entities of , to those that match the encapsulated query logic of the + /// . + /// + /// The encapsulated query logic. + /// The filtered entities as an . + protected virtual IQueryable ApplySpecification(ISpecification specification, bool evaluateCriteriaOnly = false) + { + return specificationEvaluator.GetQuery(dbContext.Set().AsQueryable(), specification, evaluateCriteriaOnly); + } + /// + /// Filters all entities of , that matches the encapsulated query logic of the + /// , from the database. + /// + /// Projects each entity into a new form, being . + /// + /// + /// The type of the value returned by the projection. + /// The encapsulated query logic. + /// The filtered projected entities as an . + protected virtual IQueryable ApplySpecification(ISpecification specification) + { + return specificationEvaluator.GetQuery(dbContext.Set().AsQueryable(), specification); + } + } +} diff --git a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/IntegrationTestBase.cs b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/IntegrationTestBase.cs index 292be7e2..51fca8c0 100644 --- a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/IntegrationTestBase.cs +++ b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/IntegrationTestBase.cs @@ -3,18 +3,18 @@ namespace Ardalis.Specification.EntityFrameworkCore.IntegrationTests.Fixture { - public abstract class IntegrationTestBase : IClassFixture + public abstract class IntegrationTestBase : IClassFixture + { + protected TestDbContext dbContext; + protected Repository companyRepository; + protected Repository storeRepository; + + protected IntegrationTestBase(SharedDatabaseFixture fixture, ISpecificationEvaluator specificationEvaluator) { - protected TestDbContext dbContext; - protected Repository companyRepository; - protected Repository storeRepository; + dbContext = fixture.CreateContext(); - protected IntegrationTestBase(SharedDatabaseFixture fixture, ISpecificationEvaluator specificationEvaluator) - { - dbContext = fixture.CreateContext(); - - companyRepository = new Repository(dbContext, specificationEvaluator); - storeRepository = new Repository(dbContext, specificationEvaluator); - } + companyRepository = new Repository(dbContext, specificationEvaluator); + storeRepository = new Repository(dbContext, specificationEvaluator); } + } } diff --git a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/LoggerFactoryProvider.cs b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/LoggerFactoryProvider.cs index 82f8872c..42a357c8 100644 --- a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/LoggerFactoryProvider.cs +++ b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/LoggerFactoryProvider.cs @@ -1,16 +1,16 @@ -using Microsoft.Extensions.Logging; -using System; +using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Logging; namespace Ardalis.Specification.EntityFrameworkCore.IntegrationTests.Fixture { - public class LoggerFactoryProvider + public class LoggerFactoryProvider + { + public static readonly ILoggerFactory LoggerFactoryInstance = Microsoft.Extensions.Logging.LoggerFactory.Create(builder => { - public static readonly ILoggerFactory LoggerFactoryInstance = Microsoft.Extensions.Logging.LoggerFactory.Create(builder => - { - builder.AddFilter("Ardalis.Specification.EF", LogLevel.Debug); - builder.AddConsole(); - }); - } + builder.AddFilter("Ardalis.Specification.EF", LogLevel.Debug); + builder.AddConsole(); + }); + } } diff --git a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/RepositoryOfT.cs b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/RepositoryOfT.cs index a9286c77..191ad62c 100644 --- a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/RepositoryOfT.cs +++ b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/RepositoryOfT.cs @@ -1,13 +1,13 @@ namespace Ardalis.Specification.EntityFrameworkCore.IntegrationTests.Fixture { - /// - public class Repository : RepositoryBase where T : class - { - protected readonly TestDbContext dbContext; + /// + public class Repository : RepositoryBase where T : class + { + protected readonly TestDbContext dbContext; - public Repository(TestDbContext dbContext, ISpecificationEvaluator specificationEvaluator) : base(dbContext, specificationEvaluator) - { - this.dbContext = dbContext; - } + public Repository(TestDbContext dbContext, ISpecificationEvaluator specificationEvaluator) : base(dbContext, specificationEvaluator) + { + this.dbContext = dbContext; } + } } diff --git a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/SharedDatabaseFixture.cs b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/SharedDatabaseFixture.cs index 7669908e..92eb4bb6 100644 --- a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/SharedDatabaseFixture.cs +++ b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/SharedDatabaseFixture.cs @@ -1,94 +1,94 @@ -using Microsoft.Data.SqlClient; -using Microsoft.EntityFrameworkCore; -using System; +using System; using System.Collections.Generic; using System.Data.Common; using System.Text; using MartinCostello.SqlLocalDb; +using Microsoft.Data.SqlClient; +using Microsoft.EntityFrameworkCore; namespace Ardalis.Specification.EntityFrameworkCore.IntegrationTests.Fixture { - public class SharedDatabaseFixture : IDisposable - { - // Docker - public const string ConnectionStringDocker = "Data Source=databaseEFCore;Initial Catalog=SpecificationEFCoreTestsDB;PersistSecurityInfo=True;User ID=sa;Password=P@ssW0rd!"; + public class SharedDatabaseFixture : IDisposable + { + // Docker + public const string ConnectionStringDocker = "Data Source=databaseEFCore;Initial Catalog=SpecificationEFCoreTestsDB;PersistSecurityInfo=True;User ID=sa;Password=P@ssW0rd!"; - // (localdb) - public const string ConnectionStringLocalDb = "Server=(localdb)\\mssqllocaldb;Integrated Security=SSPI;Initial Catalog=SpecificationEFTestsDB;ConnectRetryCount=0"; + // (localdb) + public const string ConnectionStringLocalDb = "Server=(localdb)\\mssqllocaldb;Integrated Security=SSPI;Initial Catalog=SpecificationEFTestsDB;ConnectRetryCount=0"; - private static readonly object _lock = new object(); - private static bool _databaseInitialized; + private static readonly object _lock = new object(); + private static bool _databaseInitialized; - public SharedDatabaseFixture() - { - var isLocalDBInstalled = false; + public SharedDatabaseFixture() + { + var isLocalDBInstalled = false; - using (var localDB = new SqlLocalDbApi()) - { - isLocalDBInstalled = localDB.IsLocalDBInstalled(); - } + using (var localDB = new SqlLocalDbApi()) + { + isLocalDBInstalled = localDB.IsLocalDBInstalled(); + } - Connection = isLocalDBInstalled - ? new SqlConnection(ConnectionStringLocalDb) - : new SqlConnection(ConnectionStringDocker); + Connection = isLocalDBInstalled + ? new SqlConnection(ConnectionStringLocalDb) + : new SqlConnection(ConnectionStringDocker); - Seed(); + Seed(); - Connection.Open(); - } + Connection.Open(); + } - // This would work only if the DB already exists, otherwise obviously won't be able to open a connection. - // Therefore, in the ctor we're using a Nuget package for this check, it's more robust. - private bool IsLocalDbAvailable1() + // This would work only if the DB already exists, otherwise obviously won't be able to open a connection. + // Therefore, in the ctor we're using a Nuget package for this check, it's more robust. + private bool IsLocalDbAvailable1() + { + try + { + using (var connection = new SqlConnection(ConnectionStringLocalDb)) { - try - { - using (var connection = new SqlConnection(ConnectionStringLocalDb)) - { - connection.Open(); - connection.Close(); - } - - return true; - } - catch (Exception) - { - return false; - } + connection.Open(); + connection.Close(); } - public DbConnection Connection { get; } + return true; + } + catch (Exception) + { + return false; + } + } + + public DbConnection Connection { get; } - public TestDbContext CreateContext(DbTransaction? transaction = null) - { - var context = new TestDbContext(new DbContextOptionsBuilder().UseSqlServer(Connection).Options); + public TestDbContext CreateContext(DbTransaction? transaction = null) + { + var context = new TestDbContext(new DbContextOptionsBuilder().UseSqlServer(Connection).Options); - if (transaction != null) - { - context.Database.UseTransaction(transaction); - } + if (transaction != null) + { + context.Database.UseTransaction(transaction); + } - return context; - } + return context; + } - private void Seed() + private void Seed() + { + lock (_lock) + { + if (!_databaseInitialized) { - lock (_lock) - { - if (!_databaseInitialized) - { - using (var context = CreateContext()) - { - context.Database.EnsureDeleted(); - context.Database.EnsureCreated(); - } - - _databaseInitialized = true; - } - } - } + using (var context = CreateContext()) + { + context.Database.EnsureDeleted(); + context.Database.EnsureCreated(); + } - public void Dispose() => Connection.Dispose(); + _databaseInitialized = true; + } + } } + + public void Dispose() => Connection.Dispose(); + } } diff --git a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/TestDbContext.cs b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/TestDbContext.cs index 864650f0..80edee5d 100644 --- a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/TestDbContext.cs +++ b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/Fixture/TestDbContext.cs @@ -1,41 +1,41 @@ -using Microsoft.EntityFrameworkCore; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; +using Microsoft.EntityFrameworkCore; namespace Ardalis.Specification.EntityFrameworkCore.IntegrationTests.Fixture { - public class TestDbContext : DbContext - { - public DbSet? Countries { get; set; } - public DbSet? Companies { get; set; } - public DbSet? Stores { get; set; } - public DbSet
? Addresses { get; set; } - public DbSet? Products { get; set; } + public class TestDbContext : DbContext + { + public DbSet? Countries { get; set; } + public DbSet? Companies { get; set; } + public DbSet? Stores { get; set; } + public DbSet
? Addresses { get; set; } + public DbSet? Products { get; set; } - public TestDbContext(DbContextOptions options) : base(options) - { - } + public TestDbContext(DbContextOptions options) : base(options) + { + } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseLoggerFactory(LoggerFactoryProvider.LoggerFactoryInstance); - base.OnConfiguring(optionsBuilder); - } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseLoggerFactory(LoggerFactoryProvider.LoggerFactoryInstance); + base.OnConfiguring(optionsBuilder); + } - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - base.OnModelCreating(modelBuilder); + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); - modelBuilder.Entity().HasOne(x => x.Address).WithOne(x => x!.Store!).HasForeignKey
(x => x.StoreId); + modelBuilder.Entity().HasOne(x => x.Address).WithOne(x => x!.Store!).HasForeignKey
(x => x.StoreId); - modelBuilder.Entity().HasData(CountrySeed.Get()); - modelBuilder.Entity().HasData(CompanySeed.Get()); - modelBuilder.Entity
().HasData(AddressSeed.Get()); - modelBuilder.Entity().HasData(StoreSeed.Get()); - modelBuilder.Entity().HasData(ProductSeed.Get()); - } + modelBuilder.Entity().HasData(CountrySeed.Get()); + modelBuilder.Entity().HasData(CompanySeed.Get()); + modelBuilder.Entity
().HasData(AddressSeed.Get()); + modelBuilder.Entity().HasData(StoreSeed.Get()); + modelBuilder.Entity().HasData(ProductSeed.Get()); } + } } diff --git a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_AnyAsync.cs b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_AnyAsync.cs index bd2039b1..69d69918 100644 --- a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_AnyAsync.cs +++ b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_AnyAsync.cs @@ -7,46 +7,46 @@ namespace Ardalis.Specification.EntityFrameworkCore.IntegrationTests { - public class RepositoryOfT_AnyAsync : RepositoryOfT_AnyAsync_TestKit + public class RepositoryOfT_AnyAsync : RepositoryOfT_AnyAsync_TestKit + { + public RepositoryOfT_AnyAsync(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Default) { - public RepositoryOfT_AnyAsync(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Default) - { - } } + } - public class RepositoryOfT_AnyAsync_Cached : RepositoryOfT_AnyAsync_TestKit + public class RepositoryOfT_AnyAsync_Cached : RepositoryOfT_AnyAsync_TestKit + { + public RepositoryOfT_AnyAsync_Cached(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Cached) { - public RepositoryOfT_AnyAsync_Cached(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Cached) - { - } } + } - public abstract class RepositoryOfT_AnyAsync_TestKit : IntegrationTestBase - { - protected RepositoryOfT_AnyAsync_TestKit(SharedDatabaseFixture fixture, ISpecificationEvaluator specificationEvaluator) : base(fixture, specificationEvaluator) { } + public abstract class RepositoryOfT_AnyAsync_TestKit : IntegrationTestBase + { + protected RepositoryOfT_AnyAsync_TestKit(SharedDatabaseFixture fixture, ISpecificationEvaluator specificationEvaluator) : base(fixture, specificationEvaluator) { } - [Fact] - public virtual async Task ReturnsTrueOnStoresRecords_WithoutSpec() - { - var result = await storeRepository.AnyAsync(); + [Fact] + public virtual async Task ReturnsTrueOnStoresRecords_WithoutSpec() + { + var result = await storeRepository.AnyAsync(); - result.Should().BeTrue(); - } + result.Should().BeTrue(); + } - [Fact] - public virtual async Task ReturnsTrue_GivenStoreByIdSpecWithValidStore() - { - var result = await storeRepository.AnyAsync(new StoreByIdSpec(StoreSeed.VALID_STORE_ID)); + [Fact] + public virtual async Task ReturnsTrue_GivenStoreByIdSpecWithValidStore() + { + var result = await storeRepository.AnyAsync(new StoreByIdSpec(StoreSeed.VALID_STORE_ID)); - result.Should().BeTrue(); - } + result.Should().BeTrue(); + } - [Fact] - public virtual async Task ReturnsTrue_GivenStoreByIdSpecWithInvalidStore() - { - var result = await storeRepository.AnyAsync(new StoreByIdSpec(0)); + [Fact] + public virtual async Task ReturnsTrue_GivenStoreByIdSpecWithInvalidStore() + { + var result = await storeRepository.AnyAsync(new StoreByIdSpec(0)); - result.Should().BeFalse(); - } + result.Should().BeFalse(); } + } } diff --git a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_GetById.cs b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_GetById.cs index 90fa5c45..95b6bba0 100644 --- a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_GetById.cs +++ b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_GetById.cs @@ -6,40 +6,40 @@ namespace Ardalis.Specification.EntityFrameworkCore.IntegrationTests { - public class RepositoryOfT_GetById : RepositoryOfT_GetById_TestKit + public class RepositoryOfT_GetById : RepositoryOfT_GetById_TestKit + { + public RepositoryOfT_GetById(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Default) { - public RepositoryOfT_GetById(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Default) - { - } } + } - public class RepositoryOfT_GetById_Cached : RepositoryOfT_GetById_TestKit + public class RepositoryOfT_GetById_Cached : RepositoryOfT_GetById_TestKit + { + public RepositoryOfT_GetById_Cached(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Cached) { - public RepositoryOfT_GetById_Cached(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Cached) - { - } } + } - public abstract class RepositoryOfT_GetById_TestKit : IntegrationTestBase - { - protected RepositoryOfT_GetById_TestKit(SharedDatabaseFixture fixture, ISpecificationEvaluator specificationEvaluator) : base(fixture, specificationEvaluator) { } + public abstract class RepositoryOfT_GetById_TestKit : IntegrationTestBase + { + protected RepositoryOfT_GetById_TestKit(SharedDatabaseFixture fixture, ISpecificationEvaluator specificationEvaluator) : base(fixture, specificationEvaluator) { } - [Fact] - public virtual async Task ReturnsStore_GivenId() - { - var result = await storeRepository.GetByIdAsync(StoreSeed.VALID_STORE_ID); + [Fact] + public virtual async Task ReturnsStore_GivenId() + { + var result = await storeRepository.GetByIdAsync(StoreSeed.VALID_STORE_ID); - result.Should().NotBeNull(); - result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - } + result.Should().NotBeNull(); + result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + } - [Fact] - public virtual async Task ReturnsStore_GivenGenericId() - { - var result = await storeRepository.GetByIdAsync(StoreSeed.VALID_STORE_ID); + [Fact] + public virtual async Task ReturnsStore_GivenGenericId() + { + var result = await storeRepository.GetByIdAsync(StoreSeed.VALID_STORE_ID); - result.Should().NotBeNull(); - result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - } + result.Should().NotBeNull(); + result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); } + } } diff --git a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_GetBySpec.cs b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_GetBySpec.cs index 1c248602..7804728b 100644 --- a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_GetBySpec.cs +++ b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_GetBySpec.cs @@ -8,110 +8,110 @@ namespace Ardalis.Specification.EntityFrameworkCore.IntegrationTests { - public class RepositoryOfT_GetBySpec : RepositoryOfT_GetBySpec_TestKit + public class RepositoryOfT_GetBySpec : RepositoryOfT_GetBySpec_TestKit + { + public RepositoryOfT_GetBySpec(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Default) { - public RepositoryOfT_GetBySpec(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Default) - { - } } + } - public class RepositoryOfT_GetBySpec_Cached : RepositoryOfT_GetBySpec_TestKit + public class RepositoryOfT_GetBySpec_Cached : RepositoryOfT_GetBySpec_TestKit + { + public RepositoryOfT_GetBySpec_Cached(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Cached) { - public RepositoryOfT_GetBySpec_Cached(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Cached) - { - } } + } - public abstract class RepositoryOfT_GetBySpec_TestKit : IntegrationTestBase + public abstract class RepositoryOfT_GetBySpec_TestKit : IntegrationTestBase + { + protected RepositoryOfT_GetBySpec_TestKit(SharedDatabaseFixture fixture, ISpecificationEvaluator specificationEvaluator) : base(fixture, specificationEvaluator) { } + + [Fact] + public virtual async Task ReturnsStoreWithProducts_GivenStoreByIdIncludeProductsSpec() + { + var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeProductsSpec(StoreSeed.VALID_STORE_ID)); + + result.Should().NotBeNull(); + result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + result.Products.Count.Should().BeGreaterThan(1); + } + + [Fact] + public virtual async Task ReturnsStoreWithAddress_GivenStoreByIdIncludeAddressSpec() + { + var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeAddressSpec(StoreSeed.VALID_STORE_ID)); + + result.Should().NotBeNull(); + result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + result.Address?.Street.Should().Be(AddressSeed.VALID_STREET_FOR_STOREID1); + } + + [Fact] + public virtual async Task ReturnsStoreWithAddressAndProduct_GivenStoreByIdIncludeAddressAndProductsSpec() + { + var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeAddressAndProductsSpec(StoreSeed.VALID_STORE_ID)); + + result.Should().NotBeNull(); + result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + result.Products.Count.Should().BeGreaterThan(1); + result.Address?.Street.Should().Be(AddressSeed.VALID_STREET_FOR_STOREID1); + } + + [Fact] + public virtual async Task ReturnsStoreWithProducts_GivenStoreByIdIncludeProductsUsingStringSpec() + { + var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeProductsUsingStringSpec(StoreSeed.VALID_STORE_ID)); + + result.Should().NotBeNull(); + result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + result.Products.Count.Should().BeGreaterThan(1); + } + + [Fact] + public virtual async Task ReturnsCompanyWithStoresAndAddress_GivenCompanyByIdIncludeStoresThenIncludeAddressSpec() + { + var result = await companyRepository.GetBySpecAsync(new CompanyByIdIncludeStoresThenIncludeAddressSpec(CompanySeed.VALID_COMPANY_ID)); + + result.Should().NotBeNull(); + result!.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); + result.Stores.Count.Should().BeGreaterThan(49); + result.Stores.Select(x => x.Address).Count().Should().BeGreaterThan(0); + } + + [Fact] + public virtual async Task ReturnsCompanyWithStoresAndProducts_GivenCompanyByIdIncludeStoresThenIncludeProductsSpec() + { + var result = await companyRepository.GetBySpecAsync(new CompanyByIdIncludeStoresThenIncludeProductsSpec(CompanySeed.VALID_COMPANY_ID)); + + result.Should().NotBeNull(); + result!.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); + result.Stores.Count.Should().BeGreaterThan(49); + result.Stores.Select(x => x.Products).Count().Should().BeGreaterThan(1); + } + + [Fact] + public virtual async Task ReturnsUntrackedCompany_GivenCompanyByIdAsUntrackedSpec() + { + dbContext.ChangeTracker.Clear(); + + var result = await companyRepository.GetBySpecAsync(new CompanyByIdAsUntrackedSpec(CompanySeed.VALID_COMPANY_ID)); + + result.Should().NotBeNull(); + result?.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); + dbContext.Entry(result!).State.Should().Be(Microsoft.EntityFrameworkCore.EntityState.Detached); + } + + [Fact] + public virtual async Task ReturnsStoreWithCompanyAndCountryAndStoresForCompany_GivenStoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec() { - protected RepositoryOfT_GetBySpec_TestKit(SharedDatabaseFixture fixture, ISpecificationEvaluator specificationEvaluator ) : base(fixture, specificationEvaluator) { } - - [Fact] - public virtual async Task ReturnsStoreWithProducts_GivenStoreByIdIncludeProductsSpec() - { - var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeProductsSpec(StoreSeed.VALID_STORE_ID)); - - result.Should().NotBeNull(); - result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - result.Products.Count.Should().BeGreaterThan(1); - } - - [Fact] - public virtual async Task ReturnsStoreWithAddress_GivenStoreByIdIncludeAddressSpec() - { - var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeAddressSpec(StoreSeed.VALID_STORE_ID)); - - result.Should().NotBeNull(); - result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - result.Address?.Street.Should().Be(AddressSeed.VALID_STREET_FOR_STOREID1); - } - - [Fact] - public virtual async Task ReturnsStoreWithAddressAndProduct_GivenStoreByIdIncludeAddressAndProductsSpec() - { - var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeAddressAndProductsSpec(StoreSeed.VALID_STORE_ID)); - - result.Should().NotBeNull(); - result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - result.Products.Count.Should().BeGreaterThan(1); - result.Address?.Street.Should().Be(AddressSeed.VALID_STREET_FOR_STOREID1); - } - - [Fact] - public virtual async Task ReturnsStoreWithProducts_GivenStoreByIdIncludeProductsUsingStringSpec() - { - var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeProductsUsingStringSpec(StoreSeed.VALID_STORE_ID)); - - result.Should().NotBeNull(); - result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - result.Products.Count.Should().BeGreaterThan(1); - } - - [Fact] - public virtual async Task ReturnsCompanyWithStoresAndAddress_GivenCompanyByIdIncludeStoresThenIncludeAddressSpec() - { - var result = await companyRepository.GetBySpecAsync(new CompanyByIdIncludeStoresThenIncludeAddressSpec(CompanySeed.VALID_COMPANY_ID)); - - result.Should().NotBeNull(); - result!.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); - result.Stores.Count.Should().BeGreaterThan(49); - result.Stores.Select(x => x.Address).Count().Should().BeGreaterThan(0); - } - - [Fact] - public virtual async Task ReturnsCompanyWithStoresAndProducts_GivenCompanyByIdIncludeStoresThenIncludeProductsSpec() - { - var result = await companyRepository.GetBySpecAsync(new CompanyByIdIncludeStoresThenIncludeProductsSpec(CompanySeed.VALID_COMPANY_ID)); - - result.Should().NotBeNull(); - result!.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); - result.Stores.Count.Should().BeGreaterThan(49); - result.Stores.Select(x => x.Products).Count().Should().BeGreaterThan(1); - } - - [Fact] - public virtual async Task ReturnsUntrackedCompany_GivenCompanyByIdAsUntrackedSpec() - { - dbContext.ChangeTracker.Clear(); - - var result = await companyRepository.GetBySpecAsync(new CompanyByIdAsUntrackedSpec(CompanySeed.VALID_COMPANY_ID)); - - result.Should().NotBeNull(); - result?.Name.Should().Be(CompanySeed.VALID_COMPANY_NAME); - dbContext.Entry(result!).State.Should().Be(Microsoft.EntityFrameworkCore.EntityState.Detached); - } - - [Fact] - public virtual async Task ReturnsStoreWithCompanyAndCountryAndStoresForCompany_GivenStoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec() - { - var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec(StoreSeed.VALID_STORE_ID)); - - result.Should().NotBeNull(); - result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); - result.Company.Should().NotBeNull(); - result.Company!.Country.Should().NotBeNull(); - result.Company!.Stores.Should().HaveCountGreaterOrEqualTo(2); - result.Company?.Stores?.Should().Match(x => x.Any(z => z.Products.Count > 0)); - } + var result = await storeRepository.GetBySpecAsync(new StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec(StoreSeed.VALID_STORE_ID)); + + result.Should().NotBeNull(); + result!.Name.Should().Be(StoreSeed.VALID_STORE_NAME); + result.Company.Should().NotBeNull(); + result.Company!.Country.Should().NotBeNull(); + result.Company!.Stores.Should().HaveCountGreaterOrEqualTo(2); + result.Company?.Stores?.Should().Match(x => x.Any(z => z.Products.Count > 0)); } + } } diff --git a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_ListAsync.cs b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_ListAsync.cs index cbd9b453..2abf1058 100644 --- a/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_ListAsync.cs +++ b/Specification.EntityFrameworkCore/tests/Ardalis.Specification.EntityFrameworkCore.IntegrationTests/RepositoryOfT_ListAsync.cs @@ -8,193 +8,193 @@ namespace Ardalis.Specification.EntityFrameworkCore.IntegrationTests { - public class RepositoryOfT_ListAsync : RepositoryOfT_ListAsync_TestKit + public class RepositoryOfT_ListAsync : RepositoryOfT_ListAsync_TestKit + { + public RepositoryOfT_ListAsync(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Default) { - public RepositoryOfT_ListAsync(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Default) - { - } } + } - public class RepositoryOfT_ListAsync_Cached : RepositoryOfT_ListAsync_TestKit + public class RepositoryOfT_ListAsync_Cached : RepositoryOfT_ListAsync_TestKit + { + public RepositoryOfT_ListAsync_Cached(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Cached) { - public RepositoryOfT_ListAsync_Cached(SharedDatabaseFixture fixture) : base(fixture, SpecificationEvaluator.Cached) - { - } } + } - public abstract class RepositoryOfT_ListAsync_TestKit : IntegrationTestBase + public abstract class RepositoryOfT_ListAsync_TestKit : IntegrationTestBase + { + protected RepositoryOfT_ListAsync_TestKit(SharedDatabaseFixture fixture, ISpecificationEvaluator specificationEvaluator) : base(fixture, specificationEvaluator) { } + + [Fact] + public virtual async Task ReturnsStoreWithProducts_GivenStoreIncludeProductsSpec() { - protected RepositoryOfT_ListAsync_TestKit(SharedDatabaseFixture fixture, ISpecificationEvaluator specificationEvaluator) : base(fixture, specificationEvaluator) { } + var result = await storeRepository.ListAsync(new StoreIncludeProductsSpec()); - [Fact] - public virtual async Task ReturnsStoreWithProducts_GivenStoreIncludeProductsSpec() - { - var result = await storeRepository.ListAsync(new StoreIncludeProductsSpec()); + result.Should().NotBeNull(); + result.Should().NotBeEmpty(); + result[0].Products.Should().NotBeEmpty(); + } - result.Should().NotBeNull(); - result.Should().NotBeEmpty(); - result[0].Products.Should().NotBeEmpty(); - } + [Fact] + public virtual async Task ReturnsStoreWithAddress_GivenStoreIncludeAddressSpec() + { + var result = await storeRepository.ListAsync(new StoreIncludeAddressSpec()); - [Fact] - public virtual async Task ReturnsStoreWithAddress_GivenStoreIncludeAddressSpec() - { - var result = await storeRepository.ListAsync(new StoreIncludeAddressSpec()); + result.Should().NotBeNull(); + result.Should().NotBeEmpty(); + result[0].Address.Should().NotBeNull(); + } - result.Should().NotBeNull(); - result.Should().NotBeEmpty(); - result[0].Address.Should().NotBeNull(); - } + [Fact] + public virtual async Task ReturnsStoreWithAddressAndProduct_GivenStoreIncludeAddressAndProductsSpec() + { + var result = await storeRepository.ListAsync(new StoreIncludeAddressAndProductsSpec()); - [Fact] - public virtual async Task ReturnsStoreWithAddressAndProduct_GivenStoreIncludeAddressAndProductsSpec() - { - var result = await storeRepository.ListAsync(new StoreIncludeAddressAndProductsSpec()); + result.Should().NotBeNull(); + result.Should().NotBeEmpty(); + result[0].Address.Should().NotBeNull(); + result[0].Products.Should().NotBeEmpty(); + } - result.Should().NotBeNull(); - result.Should().NotBeEmpty(); - result[0].Address.Should().NotBeNull(); - result[0].Products.Should().NotBeEmpty(); - } + [Fact] + public virtual async Task ReturnsCompanyWithStoreWithIdOne_GivenCompanyIncludeFilteredStoresSpec() + { + var result = await companyRepository.ListAsync(new CompanyIncludeFilteredStoresSpec(1)); - [Fact] - public virtual async Task ReturnsCompanyWithStoreWithIdOne_GivenCompanyIncludeFilteredStoresSpec() - { - var result = await companyRepository.ListAsync(new CompanyIncludeFilteredStoresSpec(1)); + result.Should().NotBeNull(); + result.Should().NotBeEmpty(); + result[0].Stores.Should().NotBeEmpty(); + result[0].Stores.Should().HaveCount(1); + result[0].Stores.First().Id.Should().Be(1); + } - result.Should().NotBeNull(); - result.Should().NotBeEmpty(); - result[0].Stores.Should().NotBeEmpty(); - result[0].Stores.Should().HaveCount(1); - result[0].Stores.First().Id.Should().Be(1); - } + [Fact] + public virtual async Task ReturnsStoreWithIdFrom15To30_GivenStoresByIdListSpec() + { + var ids = Enumerable.Range(15, 16); + var spec = new StoresByIdListSpec(ids); + + var stores = await storeRepository.ListAsync(spec); - [Fact] - public virtual async Task ReturnsStoreWithIdFrom15To30_GivenStoresByIdListSpec() - { - var ids = Enumerable.Range(15, 16); - var spec = new StoresByIdListSpec(ids); + stores.Count.Should().Be(16); + stores.OrderBy(x => x.Id).First().Id.Should().Be(15); + stores.OrderBy(x => x.Id).Last().Id.Should().Be(30); + } - var stores = await storeRepository.ListAsync(spec); + [Fact] + public virtual async Task ReturnsSecondPageOfStoreNames_GivenStoreNamesPaginatedSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 - stores.Count.Should().Be(16); - stores.OrderBy(x => x.Id).First().Id.Should().Be(15); - stores.OrderBy(x => x.Id).Last().Id.Should().Be(30); - } + var spec = new StoreNamesPaginatedSpec(skip, take); + + var storeNames = await storeRepository.ListAsync(spec); + + storeNames.Count.Should().Be(take); + storeNames.First().Should().Be("Store 11"); + storeNames.Last().Should().Be("Store 20"); + } - [Fact] - public virtual async Task ReturnsSecondPageOfStoreNames_GivenStoreNamesPaginatedSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 + [Fact] + public virtual async Task ReturnsSecondPageOfStores_GivenStoresPaginatedSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 - var spec = new StoreNamesPaginatedSpec(skip, take); + var spec = new StoresPaginatedSpec(skip, take); - var storeNames = await storeRepository.ListAsync(spec); + var stores = await storeRepository.ListAsync(spec); - storeNames.Count.Should().Be(take); - storeNames.First().Should().Be("Store 11"); - storeNames.Last().Should().Be("Store 20"); - } + stores.Count.Should().Be(take); + stores.OrderBy(x => x.Id).First().Id.Should().Be(11); + stores.OrderBy(x => x.Id).Last().Id.Should().Be(20); + } - [Fact] - public virtual async Task ReturnsSecondPageOfStores_GivenStoresPaginatedSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 + [Fact] + public virtual async Task ReturnsOrderStoresByNameDescForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameSpec() + { + var spec = new StoresByCompanyOrderedDescByNameSpec(2); - var spec = new StoresPaginatedSpec(skip, take); + var stores = await storeRepository.ListAsync(spec); - var stores = await storeRepository.ListAsync(spec); + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_LAST_ID); + } - stores.Count.Should().Be(take); - stores.OrderBy(x => x.Id).First().Id.Should().Be(11); - stores.OrderBy(x => x.Id).Last().Id.Should().Be(20); - } + [Fact] + public virtual async Task ReturnsOrderStoresByNameDescThenByIdForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameThenByIdSpec() + { + var spec = new StoresByCompanyOrderedDescByNameThenByIdSpec(2); - [Fact] - public virtual async Task ReturnsOrderStoresByNameDescForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameSpec() - { - var spec = new StoresByCompanyOrderedDescByNameSpec(2); + var stores = await storeRepository.ListAsync(spec); - var stores = await storeRepository.ListAsync(spec); + stores.First().Id.Should().Be(99); + stores.Last().Id.Should().Be(98); + } - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_LAST_ID); - } + [Fact] + public virtual async Task ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedOrderedDescByNameSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 - [Fact] - public virtual async Task ReturnsOrderStoresByNameDescThenByIdForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameThenByIdSpec() - { - var spec = new StoresByCompanyOrderedDescByNameThenByIdSpec(2); - - var stores = await storeRepository.ListAsync(spec); - - stores.First().Id.Should().Be(99); - stores.Last().Id.Should().Be(98); - } - - [Fact] - public virtual async Task ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedOrderedDescByNameSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 + var spec = new StoresByCompanyPaginatedOrderedDescByNameSpec(2, skip, take); - var spec = new StoresByCompanyPaginatedOrderedDescByNameSpec(2, skip, take); - - var stores = await storeRepository.ListAsync(spec); + var stores = await storeRepository.ListAsync(spec); - stores.Count.Should().Be(take); - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_LAST_ID); - } + stores.Count.Should().Be(take); + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_LAST_ID); + } - [Fact] - public virtual async Task ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 + [Fact] + public virtual async Task ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 - var spec = new StoresByCompanyPaginatedSpec(2, skip, take); + var spec = new StoresByCompanyPaginatedSpec(2, skip, take); - var stores = await storeRepository.ListAsync(spec); + var stores = await storeRepository.ListAsync(spec); - stores.Count.Should().Be(take); - stores.OrderBy(x => x.Id).First().Id.Should().Be(61); - stores.OrderBy(x => x.Id).Last().Id.Should().Be(70); - } + stores.Count.Should().Be(take); + stores.OrderBy(x => x.Id).First().Id.Should().Be(61); + stores.OrderBy(x => x.Id).Last().Id.Should().Be(70); + } - [Fact] - public virtual async Task ReturnsOrderedStores_GivenStoresOrderedSpecByName() - { - var spec = new StoresOrderedSpecByName(); + [Fact] + public virtual async Task ReturnsOrderedStores_GivenStoresOrderedSpecByName() + { + var spec = new StoresOrderedSpecByName(); - var stores = await storeRepository.ListAsync(spec); + var stores = await storeRepository.ListAsync(spec); - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_LAST_ID); - } + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_LAST_ID); + } - [Fact] - public virtual async Task ReturnsOrderedStores_GivenStoresOrderedDescendingByNameSpec() - { - var spec = new StoresOrderedDescendingByNameSpec(); + [Fact] + public virtual async Task ReturnsOrderedStores_GivenStoresOrderedDescendingByNameSpec() + { + var spec = new StoresOrderedDescendingByNameSpec(); - var stores = await storeRepository.ListAsync(spec); + var stores = await storeRepository.ListAsync(spec); - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_LAST_ID); - } + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_LAST_ID); + } - [Fact] - public virtual async Task ReturnsStoreContainingCity1_GivenStoreIncludeProductsSpec() - { - var result = await storeRepository.ListAsync(new StoreSearchByNameOrCitySpec(StoreSeed.VALID_Search_City_Key)); + [Fact] + public virtual async Task ReturnsStoreContainingCity1_GivenStoreIncludeProductsSpec() + { + var result = await storeRepository.ListAsync(new StoreSearchByNameOrCitySpec(StoreSeed.VALID_Search_City_Key)); - result.Should().NotBeNull(); - result.Should().ContainSingle(); - result[0].Id.Should().Be(StoreSeed.VALID_Search_ID); - result[0].City.Should().Contain(StoreSeed.VALID_Search_City_Key); - } + result.Should().NotBeNull(); + result.Should().ContainSingle(); + result[0].Id.Should().Be(StoreSeed.VALID_Search_ID); + result[0].City.Should().Contain(StoreSeed.VALID_Search_City_Key); } + } } diff --git a/Specification/src/Ardalis.Specification/Ardalis.Specification.csproj b/Specification/src/Ardalis.Specification/Ardalis.Specification.csproj index 5d1b3e05..2b8418a0 100644 --- a/Specification/src/Ardalis.Specification/Ardalis.Specification.csproj +++ b/Specification/src/Ardalis.Specification/Ardalis.Specification.csproj @@ -35,6 +35,7 @@ $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb 9.0 enable + bin\$(Configuration)\Ardalis.Specification.EntityFrameworkCore.xml diff --git a/Specification/src/Ardalis.Specification/Builder/CacheSpecificationBuilder.cs b/Specification/src/Ardalis.Specification/Builder/CacheSpecificationBuilder.cs index a783a8f7..5378f093 100644 --- a/Specification/src/Ardalis.Specification/Builder/CacheSpecificationBuilder.cs +++ b/Specification/src/Ardalis.Specification/Builder/CacheSpecificationBuilder.cs @@ -1,19 +1,19 @@ namespace Ardalis.Specification { - public class CacheSpecificationBuilder : ICacheSpecificationBuilder where T : class - { - public Specification Specification { get; } - public bool IsChainDiscarded { get; set; } + public class CacheSpecificationBuilder : ICacheSpecificationBuilder where T : class + { + public Specification Specification { get; } + public bool IsChainDiscarded { get; set; } - public CacheSpecificationBuilder(Specification specification) - :this(specification, false) - { - } + public CacheSpecificationBuilder(Specification specification) + : this(specification, false) + { + } - public CacheSpecificationBuilder(Specification specification, bool isChainDiscarded) - { - this.Specification = specification; - this.IsChainDiscarded = isChainDiscarded; - } + public CacheSpecificationBuilder(Specification specification, bool isChainDiscarded) + { + this.Specification = specification; + this.IsChainDiscarded = isChainDiscarded; } + } } diff --git a/Specification/src/Ardalis.Specification/Builder/ICacheSpecificationBuilder.cs b/Specification/src/Ardalis.Specification/Builder/ICacheSpecificationBuilder.cs index 9240e91a..422528e5 100644 --- a/Specification/src/Ardalis.Specification/Builder/ICacheSpecificationBuilder.cs +++ b/Specification/src/Ardalis.Specification/Builder/ICacheSpecificationBuilder.cs @@ -1,7 +1,7 @@ namespace Ardalis.Specification { - public interface ICacheSpecificationBuilder : ISpecificationBuilder where T : class - { - bool IsChainDiscarded { get; set; } - } + public interface ICacheSpecificationBuilder : ISpecificationBuilder where T : class + { + bool IsChainDiscarded { get; set; } + } } diff --git a/Specification/src/Ardalis.Specification/Builder/IIncludableSpecificationBuilder.cs b/Specification/src/Ardalis.Specification/Builder/IIncludableSpecificationBuilder.cs index 3e232245..ce7d7bef 100644 --- a/Specification/src/Ardalis.Specification/Builder/IIncludableSpecificationBuilder.cs +++ b/Specification/src/Ardalis.Specification/Builder/IIncludableSpecificationBuilder.cs @@ -4,8 +4,8 @@ namespace Ardalis.Specification { - public interface IIncludableSpecificationBuilder : ISpecificationBuilder where T : class - { - bool IsChainDiscarded { get; set; } - } + public interface IIncludableSpecificationBuilder : ISpecificationBuilder where T : class + { + bool IsChainDiscarded { get; set; } + } } diff --git a/Specification/src/Ardalis.Specification/Builder/IOrderedSpecificationBuilder.cs b/Specification/src/Ardalis.Specification/Builder/IOrderedSpecificationBuilder.cs index 967ffbdb..d2bbf175 100644 --- a/Specification/src/Ardalis.Specification/Builder/IOrderedSpecificationBuilder.cs +++ b/Specification/src/Ardalis.Specification/Builder/IOrderedSpecificationBuilder.cs @@ -5,8 +5,8 @@ namespace Ardalis.Specification { - public interface IOrderedSpecificationBuilder : ISpecificationBuilder - { - bool IsChainDiscarded { get; set; } - } + public interface IOrderedSpecificationBuilder : ISpecificationBuilder + { + bool IsChainDiscarded { get; set; } + } } diff --git a/Specification/src/Ardalis.Specification/Builder/ISpecificationBuilder.cs b/Specification/src/Ardalis.Specification/Builder/ISpecificationBuilder.cs index 6fe59d59..2a5e6b90 100644 --- a/Specification/src/Ardalis.Specification/Builder/ISpecificationBuilder.cs +++ b/Specification/src/Ardalis.Specification/Builder/ISpecificationBuilder.cs @@ -5,13 +5,13 @@ namespace Ardalis.Specification { - public interface ISpecificationBuilder : ISpecificationBuilder - { - new Specification Specification { get; } - } + public interface ISpecificationBuilder : ISpecificationBuilder + { + new Specification Specification { get; } + } - public interface ISpecificationBuilder - { - Specification Specification { get; } - } + public interface ISpecificationBuilder + { + Specification Specification { get; } + } } diff --git a/Specification/src/Ardalis.Specification/Builder/IncludableBuilderExtensions.cs b/Specification/src/Ardalis.Specification/Builder/IncludableBuilderExtensions.cs index 1a2f9bbf..7fce9a0d 100644 --- a/Specification/src/Ardalis.Specification/Builder/IncludableBuilderExtensions.cs +++ b/Specification/src/Ardalis.Specification/Builder/IncludableBuilderExtensions.cs @@ -4,54 +4,54 @@ namespace Ardalis.Specification { - public static class IncludableBuilderExtensions + public static class IncludableBuilderExtensions + { + public static IIncludableSpecificationBuilder ThenInclude( + this IIncludableSpecificationBuilder previousBuilder, + Expression> thenIncludeExpression) + where TEntity : class + => ThenInclude(previousBuilder, thenIncludeExpression, true); + + public static IIncludableSpecificationBuilder ThenInclude( + this IIncludableSpecificationBuilder previousBuilder, + Expression> thenIncludeExpression, + bool condition) + where TEntity : class { - public static IIncludableSpecificationBuilder ThenInclude( - this IIncludableSpecificationBuilder previousBuilder, - Expression> thenIncludeExpression) - where TEntity : class - => ThenInclude(previousBuilder, thenIncludeExpression, true); - - public static IIncludableSpecificationBuilder ThenInclude( - this IIncludableSpecificationBuilder previousBuilder, - Expression> thenIncludeExpression, - bool condition) - where TEntity : class - { - if (condition && !previousBuilder.IsChainDiscarded) - { - var info = new IncludeExpressionInfo(thenIncludeExpression, typeof(TEntity), typeof(TProperty), typeof(TPreviousProperty)); - - ((List)previousBuilder.Specification.IncludeExpressions).Add(info); - } - - var includeBuilder = new IncludableSpecificationBuilder(previousBuilder.Specification, !condition || previousBuilder.IsChainDiscarded); - - return includeBuilder; - } - - public static IIncludableSpecificationBuilder ThenInclude( - this IIncludableSpecificationBuilder> previousBuilder, - Expression> thenIncludeExpression) - where TEntity : class - => ThenInclude(previousBuilder, thenIncludeExpression, true); - - public static IIncludableSpecificationBuilder ThenInclude( - this IIncludableSpecificationBuilder> previousBuilder, - Expression> thenIncludeExpression, - bool condition) - where TEntity : class - { - if (condition && !previousBuilder.IsChainDiscarded) - { - var info = new IncludeExpressionInfo(thenIncludeExpression, typeof(TEntity), typeof(TProperty), typeof(IEnumerable)); - - ((List)previousBuilder.Specification.IncludeExpressions).Add(info); - } - - var includeBuilder = new IncludableSpecificationBuilder(previousBuilder.Specification, !condition || previousBuilder.IsChainDiscarded); - - return includeBuilder; - } + if (condition && !previousBuilder.IsChainDiscarded) + { + var info = new IncludeExpressionInfo(thenIncludeExpression, typeof(TEntity), typeof(TProperty), typeof(TPreviousProperty)); + + ((List)previousBuilder.Specification.IncludeExpressions).Add(info); + } + + var includeBuilder = new IncludableSpecificationBuilder(previousBuilder.Specification, !condition || previousBuilder.IsChainDiscarded); + + return includeBuilder; + } + + public static IIncludableSpecificationBuilder ThenInclude( + this IIncludableSpecificationBuilder> previousBuilder, + Expression> thenIncludeExpression) + where TEntity : class + => ThenInclude(previousBuilder, thenIncludeExpression, true); + + public static IIncludableSpecificationBuilder ThenInclude( + this IIncludableSpecificationBuilder> previousBuilder, + Expression> thenIncludeExpression, + bool condition) + where TEntity : class + { + if (condition && !previousBuilder.IsChainDiscarded) + { + var info = new IncludeExpressionInfo(thenIncludeExpression, typeof(TEntity), typeof(TProperty), typeof(IEnumerable)); + + ((List)previousBuilder.Specification.IncludeExpressions).Add(info); + } + + var includeBuilder = new IncludableSpecificationBuilder(previousBuilder.Specification, !condition || previousBuilder.IsChainDiscarded); + + return includeBuilder; } + } } diff --git a/Specification/src/Ardalis.Specification/Builder/IncludableSpecificationBuilder.cs b/Specification/src/Ardalis.Specification/Builder/IncludableSpecificationBuilder.cs index 806ef8e0..18a5999a 100644 --- a/Specification/src/Ardalis.Specification/Builder/IncludableSpecificationBuilder.cs +++ b/Specification/src/Ardalis.Specification/Builder/IncludableSpecificationBuilder.cs @@ -4,20 +4,20 @@ namespace Ardalis.Specification { - public class IncludableSpecificationBuilder : IIncludableSpecificationBuilder where T : class - { - public Specification Specification { get; } - public bool IsChainDiscarded { get; set; } + public class IncludableSpecificationBuilder : IIncludableSpecificationBuilder where T : class + { + public Specification Specification { get; } + public bool IsChainDiscarded { get; set; } - public IncludableSpecificationBuilder(Specification specification) - :this(specification, false) - { - } + public IncludableSpecificationBuilder(Specification specification) + : this(specification, false) + { + } - public IncludableSpecificationBuilder(Specification specification, bool isChainDiscarded) - { - this.Specification = specification; - this.IsChainDiscarded = isChainDiscarded; - } + public IncludableSpecificationBuilder(Specification specification, bool isChainDiscarded) + { + this.Specification = specification; + this.IsChainDiscarded = isChainDiscarded; } + } } diff --git a/Specification/src/Ardalis.Specification/Builder/OrderedBuilderExtensions.cs b/Specification/src/Ardalis.Specification/Builder/OrderedBuilderExtensions.cs index c05659d8..62232372 100644 --- a/Specification/src/Ardalis.Specification/Builder/OrderedBuilderExtensions.cs +++ b/Specification/src/Ardalis.Specification/Builder/OrderedBuilderExtensions.cs @@ -5,50 +5,50 @@ namespace Ardalis.Specification { - public static class OrderedBuilderExtensions - { - public static IOrderedSpecificationBuilder ThenBy( - this IOrderedSpecificationBuilder orderedBuilder, - Expression> orderExpression) - => ThenBy(orderedBuilder, orderExpression, true); + public static class OrderedBuilderExtensions + { + public static IOrderedSpecificationBuilder ThenBy( + this IOrderedSpecificationBuilder orderedBuilder, + Expression> orderExpression) + => ThenBy(orderedBuilder, orderExpression, true); - public static IOrderedSpecificationBuilder ThenBy( - this IOrderedSpecificationBuilder orderedBuilder, - Expression> orderExpression, - bool condition) - { - if (condition && !orderedBuilder.IsChainDiscarded) - { - ((List>)orderedBuilder.Specification.OrderExpressions).Add(new OrderExpressionInfo(orderExpression, OrderTypeEnum.ThenBy)); - } - else - { - orderedBuilder.IsChainDiscarded = true; - } + public static IOrderedSpecificationBuilder ThenBy( + this IOrderedSpecificationBuilder orderedBuilder, + Expression> orderExpression, + bool condition) + { + if (condition && !orderedBuilder.IsChainDiscarded) + { + ((List>)orderedBuilder.Specification.OrderExpressions).Add(new OrderExpressionInfo(orderExpression, OrderTypeEnum.ThenBy)); + } + else + { + orderedBuilder.IsChainDiscarded = true; + } - return orderedBuilder; - } + return orderedBuilder; + } - public static IOrderedSpecificationBuilder ThenByDescending( - this IOrderedSpecificationBuilder orderedBuilder, - Expression> orderExpression) - => ThenByDescending(orderedBuilder, orderExpression, true); + public static IOrderedSpecificationBuilder ThenByDescending( + this IOrderedSpecificationBuilder orderedBuilder, + Expression> orderExpression) + => ThenByDescending(orderedBuilder, orderExpression, true); - public static IOrderedSpecificationBuilder ThenByDescending( - this IOrderedSpecificationBuilder orderedBuilder, - Expression> orderExpression, - bool condition) - { - if (condition && !orderedBuilder.IsChainDiscarded) - { - ((List>)orderedBuilder.Specification.OrderExpressions).Add(new OrderExpressionInfo(orderExpression, OrderTypeEnum.ThenByDescending)); - } - else - { - orderedBuilder.IsChainDiscarded = true; - } + public static IOrderedSpecificationBuilder ThenByDescending( + this IOrderedSpecificationBuilder orderedBuilder, + Expression> orderExpression, + bool condition) + { + if (condition && !orderedBuilder.IsChainDiscarded) + { + ((List>)orderedBuilder.Specification.OrderExpressions).Add(new OrderExpressionInfo(orderExpression, OrderTypeEnum.ThenByDescending)); + } + else + { + orderedBuilder.IsChainDiscarded = true; + } - return orderedBuilder; - } + return orderedBuilder; } + } } diff --git a/Specification/src/Ardalis.Specification/Builder/OrderedSpecificationBuilder.cs b/Specification/src/Ardalis.Specification/Builder/OrderedSpecificationBuilder.cs index 3c633cc7..22e935ec 100644 --- a/Specification/src/Ardalis.Specification/Builder/OrderedSpecificationBuilder.cs +++ b/Specification/src/Ardalis.Specification/Builder/OrderedSpecificationBuilder.cs @@ -5,20 +5,20 @@ namespace Ardalis.Specification { - public class OrderedSpecificationBuilder : IOrderedSpecificationBuilder - { - public Specification Specification { get; } - public bool IsChainDiscarded { get; set; } + public class OrderedSpecificationBuilder : IOrderedSpecificationBuilder + { + public Specification Specification { get; } + public bool IsChainDiscarded { get; set; } - public OrderedSpecificationBuilder(Specification specification) - :this(specification, false) - { - } + public OrderedSpecificationBuilder(Specification specification) + : this(specification, false) + { + } - public OrderedSpecificationBuilder(Specification specification, bool isChainDiscarded) - { - this.Specification = specification; - this.IsChainDiscarded = isChainDiscarded; - } + public OrderedSpecificationBuilder(Specification specification, bool isChainDiscarded) + { + this.Specification = specification; + this.IsChainDiscarded = isChainDiscarded; } + } } diff --git a/Specification/src/Ardalis.Specification/Builder/SpecificationBuilder.cs b/Specification/src/Ardalis.Specification/Builder/SpecificationBuilder.cs index 658774dd..a149aa13 100644 --- a/Specification/src/Ardalis.Specification/Builder/SpecificationBuilder.cs +++ b/Specification/src/Ardalis.Specification/Builder/SpecificationBuilder.cs @@ -5,24 +5,24 @@ namespace Ardalis.Specification { - public class SpecificationBuilder : SpecificationBuilder, ISpecificationBuilder - { - public new Specification Specification { get; } + public class SpecificationBuilder : SpecificationBuilder, ISpecificationBuilder + { + public new Specification Specification { get; } - public SpecificationBuilder(Specification specification) - : base(specification) - { - this.Specification = specification; - } + public SpecificationBuilder(Specification specification) + : base(specification) + { + this.Specification = specification; } + } - public class SpecificationBuilder : ISpecificationBuilder - { - public Specification Specification { get; } + public class SpecificationBuilder : ISpecificationBuilder + { + public Specification Specification { get; } - public SpecificationBuilder(Specification specification) - { - this.Specification = specification; - } + public SpecificationBuilder(Specification specification) + { + this.Specification = specification; } + } } diff --git a/Specification/src/Ardalis.Specification/Builder/SpecificationBuilderExtensions.cs b/Specification/src/Ardalis.Specification/Builder/SpecificationBuilderExtensions.cs index 451df2b8..9b07123b 100644 --- a/Specification/src/Ardalis.Specification/Builder/SpecificationBuilderExtensions.cs +++ b/Specification/src/Ardalis.Specification/Builder/SpecificationBuilderExtensions.cs @@ -4,489 +4,489 @@ namespace Ardalis.Specification { - public static class SpecificationBuilderExtensions + public static class SpecificationBuilderExtensions + { + /// + /// Specify a predicate that will be applied to the query + /// + /// + /// + /// + public static ISpecificationBuilder Where( + this ISpecificationBuilder specificationBuilder, + Expression> criteria) + => Where(specificationBuilder, criteria, true); + + /// + /// Specify a predicate that will be applied to the query + /// + /// + /// + /// + /// If false, the criteria won't be added. + public static ISpecificationBuilder Where( + this ISpecificationBuilder specificationBuilder, + Expression> criteria, + bool condition) { - /// - /// Specify a predicate that will be applied to the query - /// - /// - /// - /// - public static ISpecificationBuilder Where( - this ISpecificationBuilder specificationBuilder, - Expression> criteria) - => Where(specificationBuilder, criteria, true); - - /// - /// Specify a predicate that will be applied to the query - /// - /// - /// - /// - /// If false, the criteria won't be added. - public static ISpecificationBuilder Where( - this ISpecificationBuilder specificationBuilder, - Expression> criteria, - bool condition) - { - if (condition) - { - ((List>)specificationBuilder.Specification.WhereExpressions).Add(new WhereExpressionInfo(criteria)); - } + if (condition) + { + ((List>)specificationBuilder.Specification.WhereExpressions).Add(new WhereExpressionInfo(criteria)); + } - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// Specify the query result will be ordered by in an ascending order - /// - /// - /// - /// - public static IOrderedSpecificationBuilder OrderBy( - this ISpecificationBuilder specificationBuilder, - Expression> orderExpression) - => OrderBy(specificationBuilder, orderExpression, true); - - /// - /// Specify the query result will be ordered by in an ascending order - /// - /// - /// - /// - /// If false, the expression won't be added. The whole Order chain will be discarded. - public static IOrderedSpecificationBuilder OrderBy( - this ISpecificationBuilder specificationBuilder, - Expression> orderExpression, - bool condition) - { - if (condition) - { - ((List>)specificationBuilder.Specification.OrderExpressions).Add(new OrderExpressionInfo(orderExpression, OrderTypeEnum.OrderBy)); - } + /// + /// Specify the query result will be ordered by in an ascending order + /// + /// + /// + /// + public static IOrderedSpecificationBuilder OrderBy( + this ISpecificationBuilder specificationBuilder, + Expression> orderExpression) + => OrderBy(specificationBuilder, orderExpression, true); + + /// + /// Specify the query result will be ordered by in an ascending order + /// + /// + /// + /// + /// If false, the expression won't be added. The whole Order chain will be discarded. + public static IOrderedSpecificationBuilder OrderBy( + this ISpecificationBuilder specificationBuilder, + Expression> orderExpression, + bool condition) + { + if (condition) + { + ((List>)specificationBuilder.Specification.OrderExpressions).Add(new OrderExpressionInfo(orderExpression, OrderTypeEnum.OrderBy)); + } - var orderedSpecificationBuilder = new OrderedSpecificationBuilder(specificationBuilder.Specification, !condition); + var orderedSpecificationBuilder = new OrderedSpecificationBuilder(specificationBuilder.Specification, !condition); - return orderedSpecificationBuilder; - } + return orderedSpecificationBuilder; + } - /// - /// Specify the query result will be ordered by in a descending order - /// - /// - /// - /// - public static IOrderedSpecificationBuilder OrderByDescending( - this ISpecificationBuilder specificationBuilder, - Expression> orderExpression) - => OrderByDescending(specificationBuilder, orderExpression, true); - - /// - /// Specify the query result will be ordered by in a descending order - /// - /// - /// - /// - /// If false, the expression won't be added. The whole Order chain will be discarded. - public static IOrderedSpecificationBuilder OrderByDescending( - this ISpecificationBuilder specificationBuilder, - Expression> orderExpression, - bool condition) - { - if (condition) - { - ((List>)specificationBuilder.Specification.OrderExpressions).Add(new OrderExpressionInfo(orderExpression, OrderTypeEnum.OrderByDescending)); - } + /// + /// Specify the query result will be ordered by in a descending order + /// + /// + /// + /// + public static IOrderedSpecificationBuilder OrderByDescending( + this ISpecificationBuilder specificationBuilder, + Expression> orderExpression) + => OrderByDescending(specificationBuilder, orderExpression, true); + + /// + /// Specify the query result will be ordered by in a descending order + /// + /// + /// + /// + /// If false, the expression won't be added. The whole Order chain will be discarded. + public static IOrderedSpecificationBuilder OrderByDescending( + this ISpecificationBuilder specificationBuilder, + Expression> orderExpression, + bool condition) + { + if (condition) + { + ((List>)specificationBuilder.Specification.OrderExpressions).Add(new OrderExpressionInfo(orderExpression, OrderTypeEnum.OrderByDescending)); + } - var orderedSpecificationBuilder = new OrderedSpecificationBuilder(specificationBuilder.Specification, !condition); + var orderedSpecificationBuilder = new OrderedSpecificationBuilder(specificationBuilder.Specification, !condition); - return orderedSpecificationBuilder; - } + return orderedSpecificationBuilder; + } - /// - /// Specify an include expression. - /// This information is utilized to build Include function in the query, which ORM tools like Entity Framework use - /// to include related entities (via navigation properties) in the query result. - /// - /// - /// - /// - /// - public static IIncludableSpecificationBuilder Include( - this ISpecificationBuilder specificationBuilder, - Expression> includeExpression) where T : class - => Include(specificationBuilder, includeExpression, true); - - /// - /// Specify an include expression. - /// This information is utilized to build Include function in the query, which ORM tools like Entity Framework use - /// to include related entities (via navigation properties) in the query result. - /// - /// - /// - /// - /// - /// If false, the expression won't be added. The whole Include chain will be discarded. - public static IIncludableSpecificationBuilder Include( - this ISpecificationBuilder specificationBuilder, - Expression> includeExpression, - bool condition) where T : class - { - if (condition) - { - var info = new IncludeExpressionInfo(includeExpression, typeof(T), typeof(TProperty)); + /// + /// Specify an include expression. + /// This information is utilized to build Include function in the query, which ORM tools like Entity Framework use + /// to include related entities (via navigation properties) in the query result. + /// + /// + /// + /// + /// + public static IIncludableSpecificationBuilder Include( + this ISpecificationBuilder specificationBuilder, + Expression> includeExpression) where T : class + => Include(specificationBuilder, includeExpression, true); + + /// + /// Specify an include expression. + /// This information is utilized to build Include function in the query, which ORM tools like Entity Framework use + /// to include related entities (via navigation properties) in the query result. + /// + /// + /// + /// + /// + /// If false, the expression won't be added. The whole Include chain will be discarded. + public static IIncludableSpecificationBuilder Include( + this ISpecificationBuilder specificationBuilder, + Expression> includeExpression, + bool condition) where T : class + { + if (condition) + { + var info = new IncludeExpressionInfo(includeExpression, typeof(T), typeof(TProperty)); - ((List)specificationBuilder.Specification.IncludeExpressions).Add(info); - } + ((List)specificationBuilder.Specification.IncludeExpressions).Add(info); + } - var includeBuilder = new IncludableSpecificationBuilder(specificationBuilder.Specification, !condition); + var includeBuilder = new IncludableSpecificationBuilder(specificationBuilder.Specification, !condition); - return includeBuilder; - } + return includeBuilder; + } - /// - /// Specify a collection of navigation properties, as strings, to include in the query. - /// - /// - /// - /// - public static ISpecificationBuilder Include( - this ISpecificationBuilder specificationBuilder, - string includeString) where T : class - => Include(specificationBuilder, includeString, true); - - /// - /// Specify a collection of navigation properties, as strings, to include in the query. - /// - /// - /// - /// - /// If false, the include expression won't be added. - public static ISpecificationBuilder Include( - this ISpecificationBuilder specificationBuilder, - string includeString, - bool condition) where T : class - { - if (condition) - { - ((List)specificationBuilder.Specification.IncludeStrings).Add(includeString); - } + /// + /// Specify a collection of navigation properties, as strings, to include in the query. + /// + /// + /// + /// + public static ISpecificationBuilder Include( + this ISpecificationBuilder specificationBuilder, + string includeString) where T : class + => Include(specificationBuilder, includeString, true); + + /// + /// Specify a collection of navigation properties, as strings, to include in the query. + /// + /// + /// + /// + /// If false, the include expression won't be added. + public static ISpecificationBuilder Include( + this ISpecificationBuilder specificationBuilder, + string includeString, + bool condition) where T : class + { + if (condition) + { + ((List)specificationBuilder.Specification.IncludeStrings).Add(includeString); + } - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// Specify a 'SQL LIKE' operations for search purposes - /// - /// - /// - /// the property to apply the SQL LIKE against - /// the value to use for the SQL LIKE - /// the index used to group sets of Selectors and SearchTerms together - public static ISpecificationBuilder Search( - this ISpecificationBuilder specificationBuilder, - Expression> selector, - string searchTerm, - int searchGroup = 1) where T : class - => Search(specificationBuilder, selector, searchTerm, true, searchGroup); - - /// - /// Specify a 'SQL LIKE' operations for search purposes - /// - /// - /// - /// the property to apply the SQL LIKE against - /// the value to use for the SQL LIKE - /// If false, the expression won't be added. - /// the index used to group sets of Selectors and SearchTerms together - public static ISpecificationBuilder Search( - this ISpecificationBuilder specificationBuilder, - Expression> selector, - string searchTerm, - bool condition, - int searchGroup = 1) where T : class - { - if (condition) - { - ((List>)specificationBuilder.Specification.SearchCriterias).Add(new SearchExpressionInfo(selector, searchTerm, searchGroup)); - } + /// + /// Specify a 'SQL LIKE' operations for search purposes + /// + /// + /// + /// the property to apply the SQL LIKE against + /// the value to use for the SQL LIKE + /// the index used to group sets of Selectors and SearchTerms together + public static ISpecificationBuilder Search( + this ISpecificationBuilder specificationBuilder, + Expression> selector, + string searchTerm, + int searchGroup = 1) where T : class + => Search(specificationBuilder, selector, searchTerm, true, searchGroup); + + /// + /// Specify a 'SQL LIKE' operations for search purposes + /// + /// + /// + /// the property to apply the SQL LIKE against + /// the value to use for the SQL LIKE + /// If false, the expression won't be added. + /// the index used to group sets of Selectors and SearchTerms together + public static ISpecificationBuilder Search( + this ISpecificationBuilder specificationBuilder, + Expression> selector, + string searchTerm, + bool condition, + int searchGroup = 1) where T : class + { + if (condition) + { + ((List>)specificationBuilder.Specification.SearchCriterias).Add(new SearchExpressionInfo(selector, searchTerm, searchGroup)); + } - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// Specify the number of elements to return. - /// - /// - /// number of elements to take - public static ISpecificationBuilder Take( - this ISpecificationBuilder specificationBuilder, - int take) - => Take(specificationBuilder, take, true); - - /// - /// Specify the number of elements to return. - /// - /// - /// number of elements to take - /// If false, the value will be discarded. - public static ISpecificationBuilder Take( - this ISpecificationBuilder specificationBuilder, - int take, - bool condition) - { - if (condition) - { - if (specificationBuilder.Specification.Take != null) throw new DuplicateTakeException(); + /// + /// Specify the number of elements to return. + /// + /// + /// number of elements to take + public static ISpecificationBuilder Take( + this ISpecificationBuilder specificationBuilder, + int take) + => Take(specificationBuilder, take, true); + + /// + /// Specify the number of elements to return. + /// + /// + /// number of elements to take + /// If false, the value will be discarded. + public static ISpecificationBuilder Take( + this ISpecificationBuilder specificationBuilder, + int take, + bool condition) + { + if (condition) + { + if (specificationBuilder.Specification.Take != null) throw new DuplicateTakeException(); - specificationBuilder.Specification.Take = take; - } + specificationBuilder.Specification.Take = take; + } - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// Specify the number of elements to skip before returning the remaining elements. - /// - /// - /// - /// number of elements to skip - public static ISpecificationBuilder Skip( - this ISpecificationBuilder specificationBuilder, - int skip) - => Skip(specificationBuilder, skip, true); - - /// - /// Specify the number of elements to skip before returning the remaining elements. - /// - /// - /// - /// number of elements to skip - /// If false, the value will be discarded. - public static ISpecificationBuilder Skip( - this ISpecificationBuilder specificationBuilder, - int skip, - bool condition) - { - if (condition) - { - if (specificationBuilder.Specification.Skip != null) throw new DuplicateSkipException(); + /// + /// Specify the number of elements to skip before returning the remaining elements. + /// + /// + /// + /// number of elements to skip + public static ISpecificationBuilder Skip( + this ISpecificationBuilder specificationBuilder, + int skip) + => Skip(specificationBuilder, skip, true); + + /// + /// Specify the number of elements to skip before returning the remaining elements. + /// + /// + /// + /// number of elements to skip + /// If false, the value will be discarded. + public static ISpecificationBuilder Skip( + this ISpecificationBuilder specificationBuilder, + int skip, + bool condition) + { + if (condition) + { + if (specificationBuilder.Specification.Skip != null) throw new DuplicateSkipException(); - specificationBuilder.Specification.Skip = skip; - } + specificationBuilder.Specification.Skip = skip; + } - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// Specify a transform function to apply to the element - /// to produce another element. - /// - public static ISpecificationBuilder Select( - this ISpecificationBuilder specificationBuilder, - Expression> selector) - { - specificationBuilder.Specification.Selector = selector; + /// + /// Specify a transform function to apply to the element + /// to produce another element. + /// + public static ISpecificationBuilder Select( + this ISpecificationBuilder specificationBuilder, + Expression> selector) + { + specificationBuilder.Specification.Selector = selector; - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// Specify a transform function to apply to the result of the query - /// and returns the same type - /// - public static ISpecificationBuilder PostProcessingAction( - this ISpecificationBuilder specificationBuilder, - Func, IEnumerable> predicate) - { - specificationBuilder.Specification.PostProcessingAction = predicate; + /// + /// Specify a transform function to apply to the result of the query + /// and returns the same type + /// + public static ISpecificationBuilder PostProcessingAction( + this ISpecificationBuilder specificationBuilder, + Func, IEnumerable> predicate) + { + specificationBuilder.Specification.PostProcessingAction = predicate; - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// Specify a transform function to apply to the result of the query. - /// and returns another type - /// - public static ISpecificationBuilder PostProcessingAction( - this ISpecificationBuilder specificationBuilder, - Func, IEnumerable> predicate) - { - specificationBuilder.Specification.PostProcessingAction = predicate; + /// + /// Specify a transform function to apply to the result of the query. + /// and returns another type + /// + public static ISpecificationBuilder PostProcessingAction( + this ISpecificationBuilder specificationBuilder, + Func, IEnumerable> predicate) + { + specificationBuilder.Specification.PostProcessingAction = predicate; - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// Must be called after specifying criteria - /// - /// - /// Any arguments used in defining the specification - public static ICacheSpecificationBuilder EnableCache( - this ISpecificationBuilder specificationBuilder, - string specificationName, - params object[] args) where T : class - => EnableCache(specificationBuilder, specificationName, true, args); - - /// - /// Must be called after specifying criteria - /// - /// - /// Any arguments used in defining the specification - /// If false, the caching won't be enabled. - public static ICacheSpecificationBuilder EnableCache( - this ISpecificationBuilder specificationBuilder, - string specificationName, - bool condition, - params object[] args) where T : class + /// + /// Must be called after specifying criteria + /// + /// + /// Any arguments used in defining the specification + public static ICacheSpecificationBuilder EnableCache( + this ISpecificationBuilder specificationBuilder, + string specificationName, + params object[] args) where T : class + => EnableCache(specificationBuilder, specificationName, true, args); + + /// + /// Must be called after specifying criteria + /// + /// + /// Any arguments used in defining the specification + /// If false, the caching won't be enabled. + public static ICacheSpecificationBuilder EnableCache( + this ISpecificationBuilder specificationBuilder, + string specificationName, + bool condition, + params object[] args) where T : class + { + if (condition) + { + if (string.IsNullOrEmpty(specificationName)) { - if (condition) - { - if (string.IsNullOrEmpty(specificationName)) - { - throw new ArgumentException($"Required input {specificationName} was null or empty.", specificationName); - } + throw new ArgumentException($"Required input {specificationName} was null or empty.", specificationName); + } - specificationBuilder.Specification.CacheKey = $"{specificationName}-{string.Join("-", args)}"; + specificationBuilder.Specification.CacheKey = $"{specificationName}-{string.Join("-", args)}"; - specificationBuilder.Specification.CacheEnabled = true; - } + specificationBuilder.Specification.CacheEnabled = true; + } - var cacheBuilder = new CacheSpecificationBuilder(specificationBuilder.Specification, !condition); + var cacheBuilder = new CacheSpecificationBuilder(specificationBuilder.Specification, !condition); - return cacheBuilder; - } + return cacheBuilder; + } - /// - /// If the entity instances are modified, this will not be detected - /// by the change tracker. - /// - /// - public static ISpecificationBuilder AsNoTracking( - this ISpecificationBuilder specificationBuilder) where T : class - => AsNoTracking(specificationBuilder, true); - - /// - /// If the entity instances are modified, this will not be detected - /// by the change tracker. - /// - /// - /// If false, the setting will be discarded. - public static ISpecificationBuilder AsNoTracking( - this ISpecificationBuilder specificationBuilder, - bool condition) where T : class - { - if (condition) - { - specificationBuilder.Specification.AsNoTracking = true; - } + /// + /// If the entity instances are modified, this will not be detected + /// by the change tracker. + /// + /// + public static ISpecificationBuilder AsNoTracking( + this ISpecificationBuilder specificationBuilder) where T : class + => AsNoTracking(specificationBuilder, true); + + /// + /// If the entity instances are modified, this will not be detected + /// by the change tracker. + /// + /// + /// If false, the setting will be discarded. + public static ISpecificationBuilder AsNoTracking( + this ISpecificationBuilder specificationBuilder, + bool condition) where T : class + { + if (condition) + { + specificationBuilder.Specification.AsNoTracking = true; + } - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// The generated sql query will be split into multiple SQL queries - /// - /// - /// This feature was introduced in EF Core 5.0. It only works when using Include - /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/single-split-queries - /// - /// - /// - public static ISpecificationBuilder AsSplitQuery( - this ISpecificationBuilder specificationBuilder) where T : class - => AsSplitQuery(specificationBuilder, true); - - /// - /// The generated sql query will be split into multiple SQL queries - /// - /// - /// This feature was introduced in EF Core 5.0. It only works when using Include - /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/single-split-queries - /// - /// - /// - /// If false, the setting will be discarded. - public static ISpecificationBuilder AsSplitQuery( - this ISpecificationBuilder specificationBuilder, - bool condition) where T : class - { - if (condition) - { - specificationBuilder.Specification.AsSplitQuery = true; - } + /// + /// The generated sql query will be split into multiple SQL queries + /// + /// + /// This feature was introduced in EF Core 5.0. It only works when using Include + /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/single-split-queries + /// + /// + /// + public static ISpecificationBuilder AsSplitQuery( + this ISpecificationBuilder specificationBuilder) where T : class + => AsSplitQuery(specificationBuilder, true); + + /// + /// The generated sql query will be split into multiple SQL queries + /// + /// + /// This feature was introduced in EF Core 5.0. It only works when using Include + /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/single-split-queries + /// + /// + /// + /// If false, the setting will be discarded. + public static ISpecificationBuilder AsSplitQuery( + this ISpecificationBuilder specificationBuilder, + bool condition) where T : class + { + if (condition) + { + specificationBuilder.Specification.AsSplitQuery = true; + } - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// The query will then keep track of returned instances - /// (without tracking them in the normal way) - /// and ensure no duplicates are created in the query results - /// - /// - /// for more info: https://docs.microsoft.com/en-us/ef/core/change-tracking/identity-resolution#identity-resolution-and-queries - /// - /// - /// - public static ISpecificationBuilder AsNoTrackingWithIdentityResolution( - this ISpecificationBuilder specificationBuilder) where T : class - => AsNoTrackingWithIdentityResolution(specificationBuilder, true); - - /// - /// The query will then keep track of returned instances - /// (without tracking them in the normal way) - /// and ensure no duplicates are created in the query results - /// - /// - /// for more info: https://docs.microsoft.com/en-us/ef/core/change-tracking/identity-resolution#identity-resolution-and-queries - /// - /// - /// - /// If false, the setting will be discarded. - public static ISpecificationBuilder AsNoTrackingWithIdentityResolution( - this ISpecificationBuilder specificationBuilder, - bool condition) where T : class - { - if (condition) - { - specificationBuilder.Specification.AsNoTrackingWithIdentityResolution = true; - } + /// + /// The query will then keep track of returned instances + /// (without tracking them in the normal way) + /// and ensure no duplicates are created in the query results + /// + /// + /// for more info: https://docs.microsoft.com/en-us/ef/core/change-tracking/identity-resolution#identity-resolution-and-queries + /// + /// + /// + public static ISpecificationBuilder AsNoTrackingWithIdentityResolution( + this ISpecificationBuilder specificationBuilder) where T : class + => AsNoTrackingWithIdentityResolution(specificationBuilder, true); + + /// + /// The query will then keep track of returned instances + /// (without tracking them in the normal way) + /// and ensure no duplicates are created in the query results + /// + /// + /// for more info: https://docs.microsoft.com/en-us/ef/core/change-tracking/identity-resolution#identity-resolution-and-queries + /// + /// + /// + /// If false, the setting will be discarded. + public static ISpecificationBuilder AsNoTrackingWithIdentityResolution( + this ISpecificationBuilder specificationBuilder, + bool condition) where T : class + { + if (condition) + { + specificationBuilder.Specification.AsNoTrackingWithIdentityResolution = true; + } - return specificationBuilder; - } + return specificationBuilder; + } - /// - /// The query will ignore the defined global query filters - /// - /// - /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/filters - /// - /// - /// - public static ISpecificationBuilder IgnoreQueryFilters( - this ISpecificationBuilder specificationBuilder) where T : class - => IgnoreQueryFilters(specificationBuilder, true); - - /// - /// The query will ignore the defined global query filters - /// - /// - /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/filters - /// - /// - /// - /// If false, the setting will be discarded. - public static ISpecificationBuilder IgnoreQueryFilters( - this ISpecificationBuilder specificationBuilder, - bool condition) where T : class - { - if (condition) - { - specificationBuilder.Specification.IgnoreQueryFilters = true; - } + /// + /// The query will ignore the defined global query filters + /// + /// + /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/filters + /// + /// + /// + public static ISpecificationBuilder IgnoreQueryFilters( + this ISpecificationBuilder specificationBuilder) where T : class + => IgnoreQueryFilters(specificationBuilder, true); + + /// + /// The query will ignore the defined global query filters + /// + /// + /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/filters + /// + /// + /// + /// If false, the setting will be discarded. + public static ISpecificationBuilder IgnoreQueryFilters( + this ISpecificationBuilder specificationBuilder, + bool condition) where T : class + { + if (condition) + { + specificationBuilder.Specification.IgnoreQueryFilters = true; + } - return specificationBuilder; - } + return specificationBuilder; } + } } diff --git a/Specification/src/Ardalis.Specification/Evaluators/IEvaluator.cs b/Specification/src/Ardalis.Specification/Evaluators/IEvaluator.cs index 64c18646..4f4435c0 100644 --- a/Specification/src/Ardalis.Specification/Evaluators/IEvaluator.cs +++ b/Specification/src/Ardalis.Specification/Evaluators/IEvaluator.cs @@ -5,10 +5,10 @@ namespace Ardalis.Specification { - public interface IEvaluator - { - bool IsCriteriaEvaluator { get; } + public interface IEvaluator + { + bool IsCriteriaEvaluator { get; } - IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class; - } + IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class; + } } diff --git a/Specification/src/Ardalis.Specification/Evaluators/IInMemoryEvaluator.cs b/Specification/src/Ardalis.Specification/Evaluators/IInMemoryEvaluator.cs index 0730ea26..5dafa207 100644 --- a/Specification/src/Ardalis.Specification/Evaluators/IInMemoryEvaluator.cs +++ b/Specification/src/Ardalis.Specification/Evaluators/IInMemoryEvaluator.cs @@ -5,8 +5,8 @@ namespace Ardalis.Specification { - public interface IInMemoryEvaluator - { - IEnumerable Evaluate(IEnumerable query, ISpecification specification); - } + public interface IInMemoryEvaluator + { + IEnumerable Evaluate(IEnumerable query, ISpecification specification); + } } diff --git a/Specification/src/Ardalis.Specification/Evaluators/IInMemorySpecificationEvaluator.cs b/Specification/src/Ardalis.Specification/Evaluators/IInMemorySpecificationEvaluator.cs index 73efd19a..b44f2112 100644 --- a/Specification/src/Ardalis.Specification/Evaluators/IInMemorySpecificationEvaluator.cs +++ b/Specification/src/Ardalis.Specification/Evaluators/IInMemorySpecificationEvaluator.cs @@ -5,9 +5,9 @@ namespace Ardalis.Specification { - public interface IInMemorySpecificationEvaluator - { - IEnumerable Evaluate(IEnumerable source, ISpecification specification); - IEnumerable Evaluate(IEnumerable source, ISpecification specification); - } + public interface IInMemorySpecificationEvaluator + { + IEnumerable Evaluate(IEnumerable source, ISpecification specification); + IEnumerable Evaluate(IEnumerable source, ISpecification specification); + } } diff --git a/Specification/src/Ardalis.Specification/Evaluators/ISpecificationEvaluator.cs b/Specification/src/Ardalis.Specification/Evaluators/ISpecificationEvaluator.cs index daf69b6e..824d9f50 100644 --- a/Specification/src/Ardalis.Specification/Evaluators/ISpecificationEvaluator.cs +++ b/Specification/src/Ardalis.Specification/Evaluators/ISpecificationEvaluator.cs @@ -5,26 +5,26 @@ namespace Ardalis.Specification { + /// + /// Evaluates the logic encapsulated by an . + /// + public interface ISpecificationEvaluator + { /// - /// Evaluates the logic encapsulated by an . + /// Applies the logic encapsulated by to given , + /// and projects the result into . /// - public interface ISpecificationEvaluator - { - /// - /// Applies the logic encapsulated by to given , - /// and projects the result into . - /// - /// The type of the result. - /// The sequence of - /// The encapsulated query logic. - /// A filtered sequence of - IQueryable GetQuery(IQueryable inputQuery, ISpecification specification) where T : class; - /// - /// Applies the logic encapsulated by to given . - /// - /// The sequence of - /// The encapsulated query logic. - /// A filtered sequence of - IQueryable GetQuery(IQueryable inputQuery, ISpecification specification, bool evaluateCriteriaOnly = false) where T : class; - } + /// The type of the result. + /// The sequence of + /// The encapsulated query logic. + /// A filtered sequence of + IQueryable GetQuery(IQueryable inputQuery, ISpecification specification) where T : class; + /// + /// Applies the logic encapsulated by to given . + /// + /// The sequence of + /// The encapsulated query logic. + /// A filtered sequence of + IQueryable GetQuery(IQueryable inputQuery, ISpecification specification, bool evaluateCriteriaOnly = false) where T : class; + } } diff --git a/Specification/src/Ardalis.Specification/Evaluators/InMemorySpecificationEvaluator.cs b/Specification/src/Ardalis.Specification/Evaluators/InMemorySpecificationEvaluator.cs index a68f267a..502f89ad 100644 --- a/Specification/src/Ardalis.Specification/Evaluators/InMemorySpecificationEvaluator.cs +++ b/Specification/src/Ardalis.Specification/Evaluators/InMemorySpecificationEvaluator.cs @@ -6,51 +6,51 @@ namespace Ardalis.Specification { - public class InMemorySpecificationEvaluator : IInMemorySpecificationEvaluator - { - // Will use singleton for default configuration. Yet, it can be instantiated if necessary, with default or provided evaluators. - public static InMemorySpecificationEvaluator Default { get; } = new InMemorySpecificationEvaluator(); + public class InMemorySpecificationEvaluator : IInMemorySpecificationEvaluator + { + // Will use singleton for default configuration. Yet, it can be instantiated if necessary, with default or provided evaluators. + public static InMemorySpecificationEvaluator Default { get; } = new InMemorySpecificationEvaluator(); - private readonly List evaluators = new List(); + private readonly List evaluators = new List(); - public InMemorySpecificationEvaluator() - { - this.evaluators.AddRange(new IInMemoryEvaluator[] - { + public InMemorySpecificationEvaluator() + { + this.evaluators.AddRange(new IInMemoryEvaluator[] + { WhereEvaluator.Instance, SearchEvaluator.Instance, OrderEvaluator.Instance, PaginationEvaluator.Instance - }); - } - public InMemorySpecificationEvaluator(IEnumerable evaluators) - { - this.evaluators.AddRange(evaluators); - } - - public virtual IEnumerable Evaluate(IEnumerable source, ISpecification specification) - { - _ = specification.Selector ?? throw new SelectorNotFoundException(); - - var baseQuery = Evaluate(source, (ISpecification)specification); - - var resultQuery = baseQuery.Select(specification.Selector.Compile()); - - return specification.PostProcessingAction == null - ? resultQuery - : specification.PostProcessingAction(resultQuery); - } - - public virtual IEnumerable Evaluate(IEnumerable source, ISpecification specification) - { - foreach (var evaluator in evaluators) - { - source = evaluator.Evaluate(source, specification); - } - - return specification.PostProcessingAction == null - ? source - : specification.PostProcessingAction(source); - } + }); + } + public InMemorySpecificationEvaluator(IEnumerable evaluators) + { + this.evaluators.AddRange(evaluators); + } + + public virtual IEnumerable Evaluate(IEnumerable source, ISpecification specification) + { + _ = specification.Selector ?? throw new SelectorNotFoundException(); + + var baseQuery = Evaluate(source, (ISpecification)specification); + + var resultQuery = baseQuery.Select(specification.Selector.Compile()); + + return specification.PostProcessingAction == null + ? resultQuery + : specification.PostProcessingAction(resultQuery); + } + + public virtual IEnumerable Evaluate(IEnumerable source, ISpecification specification) + { + foreach (var evaluator in evaluators) + { + source = evaluator.Evaluate(source, specification); + } + + return specification.PostProcessingAction == null + ? source + : specification.PostProcessingAction(source); } + } } diff --git a/Specification/src/Ardalis.Specification/Evaluators/OrderEvaluator.cs b/Specification/src/Ardalis.Specification/Evaluators/OrderEvaluator.cs index 67008914..da8e4862 100644 --- a/Specification/src/Ardalis.Specification/Evaluators/OrderEvaluator.cs +++ b/Specification/src/Ardalis.Specification/Evaluators/OrderEvaluator.cs @@ -3,91 +3,91 @@ namespace Ardalis.Specification { - public class OrderEvaluator : IEvaluator, IInMemoryEvaluator - { - private OrderEvaluator() { } - public static OrderEvaluator Instance { get; } = new OrderEvaluator(); + public class OrderEvaluator : IEvaluator, IInMemoryEvaluator + { + private OrderEvaluator() { } + public static OrderEvaluator Instance { get; } = new OrderEvaluator(); - public bool IsCriteriaEvaluator { get; } = false; + public bool IsCriteriaEvaluator { get; } = false; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + if (specification.OrderExpressions != null) + { + if (specification.OrderExpressions.Count(x => x.OrderType == OrderTypeEnum.OrderBy + || x.OrderType == OrderTypeEnum.OrderByDescending) > 1) { - if (specification.OrderExpressions != null) - { - if (specification.OrderExpressions.Count(x => x.OrderType == OrderTypeEnum.OrderBy - || x.OrderType == OrderTypeEnum.OrderByDescending) > 1) - { - throw new DuplicateOrderChainException(); - } - - IOrderedQueryable? orderedQuery = null; - foreach (var orderExpression in specification.OrderExpressions) - { - if (orderExpression.OrderType == OrderTypeEnum.OrderBy) - { - orderedQuery = query.OrderBy(orderExpression.KeySelector); - } - else if (orderExpression.OrderType == OrderTypeEnum.OrderByDescending) - { - orderedQuery = query.OrderByDescending(orderExpression.KeySelector); - } - else if (orderExpression.OrderType == OrderTypeEnum.ThenBy) - { - orderedQuery = orderedQuery.ThenBy(orderExpression.KeySelector); - } - else if (orderExpression.OrderType == OrderTypeEnum.ThenByDescending) - { - orderedQuery = orderedQuery.ThenByDescending(orderExpression.KeySelector); - } - } - - if (orderedQuery != null) - { - query = orderedQuery; - } - } + throw new DuplicateOrderChainException(); + } - return query; + IOrderedQueryable? orderedQuery = null; + foreach (var orderExpression in specification.OrderExpressions) + { + if (orderExpression.OrderType == OrderTypeEnum.OrderBy) + { + orderedQuery = query.OrderBy(orderExpression.KeySelector); + } + else if (orderExpression.OrderType == OrderTypeEnum.OrderByDescending) + { + orderedQuery = query.OrderByDescending(orderExpression.KeySelector); + } + else if (orderExpression.OrderType == OrderTypeEnum.ThenBy) + { + orderedQuery = orderedQuery.ThenBy(orderExpression.KeySelector); + } + else if (orderExpression.OrderType == OrderTypeEnum.ThenByDescending) + { + orderedQuery = orderedQuery.ThenByDescending(orderExpression.KeySelector); + } } - public IEnumerable Evaluate(IEnumerable query, ISpecification specification) + if (orderedQuery != null) { - if (specification.OrderExpressions != null) - { - if (specification.OrderExpressions.Count(x => x.OrderType == OrderTypeEnum.OrderBy - || x.OrderType == OrderTypeEnum.OrderByDescending) > 1) - { - throw new DuplicateOrderChainException(); - } + query = orderedQuery; + } + } + + return query; + } - IOrderedEnumerable? orderedQuery = null; - foreach (var orderExpression in specification.OrderExpressions) - { - if (orderExpression.OrderType == OrderTypeEnum.OrderBy) - { - orderedQuery = query.OrderBy(orderExpression.KeySelectorFunc); - } - else if (orderExpression.OrderType == OrderTypeEnum.OrderByDescending) - { - orderedQuery = query.OrderByDescending(orderExpression.KeySelectorFunc); - } - else if (orderExpression.OrderType == OrderTypeEnum.ThenBy) - { - orderedQuery = orderedQuery.ThenBy(orderExpression.KeySelectorFunc); - } - else if (orderExpression.OrderType == OrderTypeEnum.ThenByDescending) - { - orderedQuery = orderedQuery.ThenByDescending(orderExpression.KeySelectorFunc); - } - } + public IEnumerable Evaluate(IEnumerable query, ISpecification specification) + { + if (specification.OrderExpressions != null) + { + if (specification.OrderExpressions.Count(x => x.OrderType == OrderTypeEnum.OrderBy + || x.OrderType == OrderTypeEnum.OrderByDescending) > 1) + { + throw new DuplicateOrderChainException(); + } - if (orderedQuery != null) - { - query = orderedQuery; - } - } + IOrderedEnumerable? orderedQuery = null; + foreach (var orderExpression in specification.OrderExpressions) + { + if (orderExpression.OrderType == OrderTypeEnum.OrderBy) + { + orderedQuery = query.OrderBy(orderExpression.KeySelectorFunc); + } + else if (orderExpression.OrderType == OrderTypeEnum.OrderByDescending) + { + orderedQuery = query.OrderByDescending(orderExpression.KeySelectorFunc); + } + else if (orderExpression.OrderType == OrderTypeEnum.ThenBy) + { + orderedQuery = orderedQuery.ThenBy(orderExpression.KeySelectorFunc); + } + else if (orderExpression.OrderType == OrderTypeEnum.ThenByDescending) + { + orderedQuery = orderedQuery.ThenByDescending(orderExpression.KeySelectorFunc); + } + } - return query; + if (orderedQuery != null) + { + query = orderedQuery; } + } + + return query; } -} \ No newline at end of file + } +} diff --git a/Specification/src/Ardalis.Specification/Evaluators/PaginationEvaluator.cs b/Specification/src/Ardalis.Specification/Evaluators/PaginationEvaluator.cs index d29b867b..41173a74 100644 --- a/Specification/src/Ardalis.Specification/Evaluators/PaginationEvaluator.cs +++ b/Specification/src/Ardalis.Specification/Evaluators/PaginationEvaluator.cs @@ -5,42 +5,42 @@ namespace Ardalis.Specification { - public class PaginationEvaluator : IEvaluator, IInMemoryEvaluator + public class PaginationEvaluator : IEvaluator, IInMemoryEvaluator + { + private PaginationEvaluator() { } + public static PaginationEvaluator Instance { get; } = new PaginationEvaluator(); + + public bool IsCriteriaEvaluator { get; } = false; + + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class { - private PaginationEvaluator() { } - public static PaginationEvaluator Instance { get; } = new PaginationEvaluator(); - - public bool IsCriteriaEvaluator { get; } = false; - - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - // If skip is 0, avoid adding to the IQueryable. It will generate more optimized SQL that way. - if (specification.Skip != null && specification.Skip != 0) - { - query = query.Skip(specification.Skip.Value); - } - - if (specification.Take != null) - { - query = query.Take(specification.Take.Value); - } - - return query; - } - - public IEnumerable Evaluate(IEnumerable query, ISpecification specification) - { - if (specification.Skip != null && specification.Skip != 0) - { - query = query.Skip(specification.Skip.Value); - } - - if (specification.Take != null) - { - query = query.Take(specification.Take.Value); - } - - return query; - } + // If skip is 0, avoid adding to the IQueryable. It will generate more optimized SQL that way. + if (specification.Skip != null && specification.Skip != 0) + { + query = query.Skip(specification.Skip.Value); + } + + if (specification.Take != null) + { + query = query.Take(specification.Take.Value); + } + + return query; + } + + public IEnumerable Evaluate(IEnumerable query, ISpecification specification) + { + if (specification.Skip != null && specification.Skip != 0) + { + query = query.Skip(specification.Skip.Value); + } + + if (specification.Take != null) + { + query = query.Take(specification.Take.Value); + } + + return query; } + } } diff --git a/Specification/src/Ardalis.Specification/Evaluators/SearchEvaluator.cs b/Specification/src/Ardalis.Specification/Evaluators/SearchEvaluator.cs index c8ace008..c84ac0b0 100644 --- a/Specification/src/Ardalis.Specification/Evaluators/SearchEvaluator.cs +++ b/Specification/src/Ardalis.Specification/Evaluators/SearchEvaluator.cs @@ -3,19 +3,19 @@ namespace Ardalis.Specification { - public class SearchEvaluator : IInMemoryEvaluator - { - private SearchEvaluator() { } - public static SearchEvaluator Instance { get; } = new SearchEvaluator(); + public class SearchEvaluator : IInMemoryEvaluator + { + private SearchEvaluator() { } + public static SearchEvaluator Instance { get; } = new SearchEvaluator(); - public IEnumerable Evaluate(IEnumerable query, ISpecification specification) - { - foreach (var searchGroup in specification.SearchCriterias.GroupBy(x => x.SearchGroup)) - { - query = query.Where(x => searchGroup.Any(c => c.SelectorFunc(x).Like(c.SearchTerm))); - } + public IEnumerable Evaluate(IEnumerable query, ISpecification specification) + { + foreach (var searchGroup in specification.SearchCriterias.GroupBy(x => x.SearchGroup)) + { + query = query.Where(x => searchGroup.Any(c => c.SelectorFunc(x).Like(c.SearchTerm))); + } - return query; - } + return query; } + } } diff --git a/Specification/src/Ardalis.Specification/Evaluators/SearchExtension.cs b/Specification/src/Ardalis.Specification/Evaluators/SearchExtension.cs index b986b45e..5981dfed 100644 --- a/Specification/src/Ardalis.Specification/Evaluators/SearchExtension.cs +++ b/Specification/src/Ardalis.Specification/Evaluators/SearchExtension.cs @@ -4,155 +4,155 @@ namespace Ardalis.Specification { - public static class SearchExtension + public static class SearchExtension + { + public static bool Like(this string input, string pattern) { - public static bool Like(this string input, string pattern) + try + { + return SqlLike(input, pattern); + } + catch (Exception) + { + throw new InvalidSearchPatternException(pattern); + } + } + + // This C# implementation of SQL Like operator is based on the following SO post https://stackoverflow.com/a/8583383/10577116 + // It covers almost all of the scenarios, and it's faster than regex based implementations. + // It may fail/throw in some very specific and edge cases, hence, wrap it in try/catch. + private static bool SqlLike(string str, string pattern) + { + bool isMatch = true, + isWildCardOn = false, + isCharWildCardOn = false, + isCharSetOn = false, + isNotCharSetOn = false, + endOfPattern = false; + int lastWildCard = -1; + int patternIndex = 0; + List set = new List(); + char p = '\0'; + + for (int i = 0; i < str.Length; i++) + { + char c = str[i]; + endOfPattern = (patternIndex >= pattern.Length); + if (!endOfPattern) { - try + p = pattern[patternIndex]; + + if (!isWildCardOn && p == '%') + { + lastWildCard = patternIndex; + isWildCardOn = true; + while (patternIndex < pattern.Length && + pattern[patternIndex] == '%') { - return SqlLike(input, pattern); + patternIndex++; } - catch (Exception) + if (patternIndex >= pattern.Length) p = '\0'; + else p = pattern[patternIndex]; + } + else if (p == '_') + { + isCharWildCardOn = true; + patternIndex++; + } + else if (p == '[') + { + if (pattern[++patternIndex] == '^') { - throw new InvalidSearchPatternException(pattern); + isNotCharSetOn = true; + patternIndex++; } - } - - // This C# implementation of SQL Like operator is based on the following SO post https://stackoverflow.com/a/8583383/10577116 - // It covers almost all of the scenarios, and it's faster than regex based implementations. - // It may fail/throw in some very specific and edge cases, hence, wrap it in try/catch. - private static bool SqlLike(string str, string pattern) - { - bool isMatch = true, - isWildCardOn = false, - isCharWildCardOn = false, - isCharSetOn = false, - isNotCharSetOn = false, - endOfPattern = false; - int lastWildCard = -1; - int patternIndex = 0; - List set = new List(); - char p = '\0'; + else isCharSetOn = true; - for (int i = 0; i < str.Length; i++) + set.Clear(); + if (pattern[patternIndex + 1] == '-' && pattern[patternIndex + 3] == ']') { - char c = str[i]; - endOfPattern = (patternIndex >= pattern.Length); - if (!endOfPattern) + char start = char.ToUpper(pattern[patternIndex]); + patternIndex += 2; + char end = char.ToUpper(pattern[patternIndex]); + if (start <= end) + { + for (char ci = start; ci <= end; ci++) { - p = pattern[patternIndex]; - - if (!isWildCardOn && p == '%') - { - lastWildCard = patternIndex; - isWildCardOn = true; - while (patternIndex < pattern.Length && - pattern[patternIndex] == '%') - { - patternIndex++; - } - if (patternIndex >= pattern.Length) p = '\0'; - else p = pattern[patternIndex]; - } - else if (p == '_') - { - isCharWildCardOn = true; - patternIndex++; - } - else if (p == '[') - { - if (pattern[++patternIndex] == '^') - { - isNotCharSetOn = true; - patternIndex++; - } - else isCharSetOn = true; - - set.Clear(); - if (pattern[patternIndex + 1] == '-' && pattern[patternIndex + 3] == ']') - { - char start = char.ToUpper(pattern[patternIndex]); - patternIndex += 2; - char end = char.ToUpper(pattern[patternIndex]); - if (start <= end) - { - for (char ci = start; ci <= end; ci++) - { - set.Add(ci); - } - } - patternIndex++; - } - - while (patternIndex < pattern.Length && - pattern[patternIndex] != ']') - { - set.Add(pattern[patternIndex]); - patternIndex++; - } - patternIndex++; - } + set.Add(ci); } + } + patternIndex++; + } - if (isWildCardOn) - { - if (char.ToUpper(c) == char.ToUpper(p)) - { - isWildCardOn = false; - patternIndex++; - } - } - else if (isCharWildCardOn) - { - isCharWildCardOn = false; - } - else if (isCharSetOn || isNotCharSetOn) - { - bool charMatch = (set.Contains(char.ToUpper(c))); - if ((isNotCharSetOn && charMatch) || (isCharSetOn && !charMatch)) - { - if (lastWildCard >= 0) patternIndex = lastWildCard; - else - { - isMatch = false; - break; - } - } - isNotCharSetOn = isCharSetOn = false; - } - else - { - if (char.ToUpper(c) == char.ToUpper(p)) - { - patternIndex++; - } - else - { - if (lastWildCard >= 0) patternIndex = lastWildCard; - else - { - isMatch = false; - break; - } - } - } + while (patternIndex < pattern.Length && + pattern[patternIndex] != ']') + { + set.Add(pattern[patternIndex]); + patternIndex++; } - endOfPattern = (patternIndex >= pattern.Length); + patternIndex++; + } + } - if (isMatch && !endOfPattern) + if (isWildCardOn) + { + if (char.ToUpper(c) == char.ToUpper(p)) + { + isWildCardOn = false; + patternIndex++; + } + } + else if (isCharWildCardOn) + { + isCharWildCardOn = false; + } + else if (isCharSetOn || isNotCharSetOn) + { + bool charMatch = (set.Contains(char.ToUpper(c))); + if ((isNotCharSetOn && charMatch) || (isCharSetOn && !charMatch)) + { + if (lastWildCard >= 0) patternIndex = lastWildCard; + else { - bool isOnlyWildCards = true; - for (int i = patternIndex; i < pattern.Length; i++) - { - if (pattern[i] != '%') - { - isOnlyWildCards = false; - break; - } - } - if (isOnlyWildCards) endOfPattern = true; + isMatch = false; + break; } - return isMatch && endOfPattern; + } + isNotCharSetOn = isCharSetOn = false; + } + else + { + if (char.ToUpper(c) == char.ToUpper(p)) + { + patternIndex++; + } + else + { + if (lastWildCard >= 0) patternIndex = lastWildCard; + else + { + isMatch = false; + break; + } + } + } + } + endOfPattern = (patternIndex >= pattern.Length); + + if (isMatch && !endOfPattern) + { + bool isOnlyWildCards = true; + for (int i = patternIndex; i < pattern.Length; i++) + { + if (pattern[i] != '%') + { + isOnlyWildCards = false; + break; + } } + if (isOnlyWildCards) endOfPattern = true; + } + return isMatch && endOfPattern; } + } } diff --git a/Specification/src/Ardalis.Specification/Evaluators/WhereEvaluator.cs b/Specification/src/Ardalis.Specification/Evaluators/WhereEvaluator.cs index 2fbc997b..135fa261 100644 --- a/Specification/src/Ardalis.Specification/Evaluators/WhereEvaluator.cs +++ b/Specification/src/Ardalis.Specification/Evaluators/WhereEvaluator.cs @@ -3,31 +3,31 @@ namespace Ardalis.Specification { - public class WhereEvaluator : IEvaluator, IInMemoryEvaluator - { - private WhereEvaluator() { } - public static WhereEvaluator Instance { get; } = new WhereEvaluator(); + public class WhereEvaluator : IEvaluator, IInMemoryEvaluator + { + private WhereEvaluator() { } + public static WhereEvaluator Instance { get; } = new WhereEvaluator(); - public bool IsCriteriaEvaluator { get; } = true; + public bool IsCriteriaEvaluator { get; } = true; - public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class - { - foreach (var info in specification.WhereExpressions) - { - query = query.Where(info.Filter); - } + public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class + { + foreach (var info in specification.WhereExpressions) + { + query = query.Where(info.Filter); + } - return query; - } + return query; + } - public IEnumerable Evaluate(IEnumerable query, ISpecification specification) - { - foreach (var info in specification.WhereExpressions) - { - query = query.Where(info.FilterFunc); - } + public IEnumerable Evaluate(IEnumerable query, ISpecification specification) + { + foreach (var info in specification.WhereExpressions) + { + query = query.Where(info.FilterFunc); + } - return query; - } + return query; } + } } diff --git a/Specification/src/Ardalis.Specification/Exceptions/DuplicateOrderChainException.cs b/Specification/src/Ardalis.Specification/Exceptions/DuplicateOrderChainException.cs index 0ace4bb6..1ecaf6f1 100644 --- a/Specification/src/Ardalis.Specification/Exceptions/DuplicateOrderChainException.cs +++ b/Specification/src/Ardalis.Specification/Exceptions/DuplicateOrderChainException.cs @@ -5,18 +5,18 @@ namespace Ardalis.Specification { - public class DuplicateOrderChainException : Exception - { - private const string message = "The specification contains more than one Order chain!"; + public class DuplicateOrderChainException : Exception + { + private const string message = "The specification contains more than one Order chain!"; - public DuplicateOrderChainException() - : base(message) - { - } + public DuplicateOrderChainException() + : base(message) + { + } - public DuplicateOrderChainException(Exception innerException) - : base(message, innerException) - { - } + public DuplicateOrderChainException(Exception innerException) + : base(message, innerException) + { } + } } diff --git a/Specification/src/Ardalis.Specification/Exceptions/DuplicateSkipException.cs b/Specification/src/Ardalis.Specification/Exceptions/DuplicateSkipException.cs index 840b28bd..e83edcd5 100644 --- a/Specification/src/Ardalis.Specification/Exceptions/DuplicateSkipException.cs +++ b/Specification/src/Ardalis.Specification/Exceptions/DuplicateSkipException.cs @@ -4,18 +4,18 @@ namespace Ardalis.Specification { - public class DuplicateSkipException : Exception - { - private const string message = "Duplicate use of Skip(). Ensure you don't use Skip() more than once in the same specification!"; + public class DuplicateSkipException : Exception + { + private const string message = "Duplicate use of Skip(). Ensure you don't use Skip() more than once in the same specification!"; - public DuplicateSkipException() - : base(message) - { - } + public DuplicateSkipException() + : base(message) + { + } - public DuplicateSkipException(Exception innerException) - : base(message, innerException) - { - } + public DuplicateSkipException(Exception innerException) + : base(message, innerException) + { } + } } diff --git a/Specification/src/Ardalis.Specification/Exceptions/DuplicateTakeException.cs b/Specification/src/Ardalis.Specification/Exceptions/DuplicateTakeException.cs index 762b8b22..7a1cc2c5 100644 --- a/Specification/src/Ardalis.Specification/Exceptions/DuplicateTakeException.cs +++ b/Specification/src/Ardalis.Specification/Exceptions/DuplicateTakeException.cs @@ -4,18 +4,18 @@ namespace Ardalis.Specification { - public class DuplicateTakeException : Exception - { - private const string message = "Duplicate use of Take(). Ensure you don't use Take() more than once in the same specification!"; + public class DuplicateTakeException : Exception + { + private const string message = "Duplicate use of Take(). Ensure you don't use Take() more than once in the same specification!"; - public DuplicateTakeException() - : base(message) - { - } + public DuplicateTakeException() + : base(message) + { + } - public DuplicateTakeException(Exception innerException) - : base(message, innerException) - { - } + public DuplicateTakeException(Exception innerException) + : base(message, innerException) + { } + } } diff --git a/Specification/src/Ardalis.Specification/Exceptions/InvalidSearchPatternException.cs b/Specification/src/Ardalis.Specification/Exceptions/InvalidSearchPatternException.cs index 1e37b827..21e685d5 100644 --- a/Specification/src/Ardalis.Specification/Exceptions/InvalidSearchPatternException.cs +++ b/Specification/src/Ardalis.Specification/Exceptions/InvalidSearchPatternException.cs @@ -4,18 +4,18 @@ namespace Ardalis.Specification { - public class InvalidSearchPatternException : Exception - { - private const string message = "Invalid search pattern: "; + public class InvalidSearchPatternException : Exception + { + private const string message = "Invalid search pattern: "; - public InvalidSearchPatternException(string searchPattern) - : base($"{message}{searchPattern}") - { - } + public InvalidSearchPatternException(string searchPattern) + : base($"{message}{searchPattern}") + { + } - public InvalidSearchPatternException(string searchPattern, Exception innerException) - : base($"{message}{searchPattern}", innerException) - { - } + public InvalidSearchPatternException(string searchPattern, Exception innerException) + : base($"{message}{searchPattern}", innerException) + { } + } } diff --git a/Specification/src/Ardalis.Specification/Exceptions/SelectorNotFoundException.cs b/Specification/src/Ardalis.Specification/Exceptions/SelectorNotFoundException.cs index be1d73fb..388a7d79 100644 --- a/Specification/src/Ardalis.Specification/Exceptions/SelectorNotFoundException.cs +++ b/Specification/src/Ardalis.Specification/Exceptions/SelectorNotFoundException.cs @@ -4,18 +4,18 @@ namespace Ardalis.Specification { - public class SelectorNotFoundException : Exception - { - private const string message = "The specification must have Selector defined."; + public class SelectorNotFoundException : Exception + { + private const string message = "The specification must have Selector defined."; - public SelectorNotFoundException() - : base(message) - { - } + public SelectorNotFoundException() + : base(message) + { + } - public SelectorNotFoundException(Exception innerException) - : base(message, innerException) - { - } + public SelectorNotFoundException(Exception innerException) + : base(message, innerException) + { } + } } diff --git a/Specification/src/Ardalis.Specification/Expressions/IncludeExpressionInfo.cs b/Specification/src/Ardalis.Specification/Expressions/IncludeExpressionInfo.cs index 236ce75a..2967c88c 100644 --- a/Specification/src/Ardalis.Specification/Expressions/IncludeExpressionInfo.cs +++ b/Specification/src/Ardalis.Specification/Expressions/IncludeExpressionInfo.cs @@ -3,88 +3,88 @@ namespace Ardalis.Specification { + /// + /// Encapsulates data needed to build Include/ThenInclude query. + /// + public class IncludeExpressionInfo + { /// - /// Encapsulates data needed to build Include/ThenInclude query. + /// If is , represents a related entity that should be included. + /// If is , represents a related entity that should be included as part of the previously included entity. /// - public class IncludeExpressionInfo - { - /// - /// If is , represents a related entity that should be included. - /// If is , represents a related entity that should be included as part of the previously included entity. - /// - public LambdaExpression LambdaExpression { get; } + public LambdaExpression LambdaExpression { get; } - /// - /// The type of the source entity. - /// - public Type EntityType { get; } + /// + /// The type of the source entity. + /// + public Type EntityType { get; } - /// - /// The type of the included entity. - /// - public Type PropertyType { get; } + /// + /// The type of the included entity. + /// + public Type PropertyType { get; } - /// - /// The type of the previously included entity. - /// - public Type? PreviousPropertyType { get; } + /// + /// The type of the previously included entity. + /// + public Type? PreviousPropertyType { get; } - /// - /// The include type. - /// - public IncludeTypeEnum Type { get; } + /// + /// The include type. + /// + public IncludeTypeEnum Type { get; } - private IncludeExpressionInfo(LambdaExpression expression, - Type entityType, - Type propertyType, - Type? previousPropertyType, - IncludeTypeEnum includeType) + private IncludeExpressionInfo(LambdaExpression expression, + Type entityType, + Type propertyType, + Type? previousPropertyType, + IncludeTypeEnum includeType) - { - _ = expression ?? throw new ArgumentNullException(nameof(expression)); - _ = entityType ?? throw new ArgumentNullException(nameof(entityType)); - _ = propertyType ?? throw new ArgumentNullException(nameof(propertyType)); + { + _ = expression ?? throw new ArgumentNullException(nameof(expression)); + _ = entityType ?? throw new ArgumentNullException(nameof(entityType)); + _ = propertyType ?? throw new ArgumentNullException(nameof(propertyType)); - if (includeType == IncludeTypeEnum.ThenInclude) - { - _ = previousPropertyType ?? throw new ArgumentNullException(nameof(previousPropertyType)); - } + if (includeType == IncludeTypeEnum.ThenInclude) + { + _ = previousPropertyType ?? throw new ArgumentNullException(nameof(previousPropertyType)); + } - this.LambdaExpression = expression; - this.EntityType = entityType; - this.PropertyType = propertyType; - this.PreviousPropertyType = previousPropertyType; - this.Type = includeType; - } + this.LambdaExpression = expression; + this.EntityType = entityType; + this.PropertyType = propertyType; + this.PreviousPropertyType = previousPropertyType; + this.Type = includeType; + } - /// - /// Creates instance of which describes 'Include' query part. - /// Source (entityType) -> Include (propertyType). - /// - /// The expression represents a related entity that should be included. - /// The type of the source entity. - /// The type of the included entity. - public IncludeExpressionInfo(LambdaExpression expression, - Type entityType, - Type propertyType) - : this(expression, entityType, propertyType, null, IncludeTypeEnum.Include) - { - } + /// + /// Creates instance of which describes 'Include' query part. + /// Source (entityType) -> Include (propertyType). + /// + /// The expression represents a related entity that should be included. + /// The type of the source entity. + /// The type of the included entity. + public IncludeExpressionInfo(LambdaExpression expression, + Type entityType, + Type propertyType) + : this(expression, entityType, propertyType, null, IncludeTypeEnum.Include) + { + } - /// - /// Creates instance of which describes 'ThenInclude' query part. - /// Source (entityType) -> Include (previousPropertyType) -> ThenInclude (propertyType). - /// - /// The expression represents a related entity that should be included as part of the previously included entity. - /// The type of the source entity. - /// The type of the included entity. - /// The type of the previously included entity. - public IncludeExpressionInfo(LambdaExpression expression, - Type entityType, - Type propertyType, - Type previousPropertyType) - : this(expression, entityType, propertyType, previousPropertyType, IncludeTypeEnum.ThenInclude) - { - } + /// + /// Creates instance of which describes 'ThenInclude' query part. + /// Source (entityType) -> Include (previousPropertyType) -> ThenInclude (propertyType). + /// + /// The expression represents a related entity that should be included as part of the previously included entity. + /// The type of the source entity. + /// The type of the included entity. + /// The type of the previously included entity. + public IncludeExpressionInfo(LambdaExpression expression, + Type entityType, + Type propertyType, + Type previousPropertyType) + : this(expression, entityType, propertyType, previousPropertyType, IncludeTypeEnum.ThenInclude) + { } + } } diff --git a/Specification/src/Ardalis.Specification/Expressions/OrderExpressionInfo.cs b/Specification/src/Ardalis.Specification/Expressions/OrderExpressionInfo.cs index 4e636305..0140e3d9 100644 --- a/Specification/src/Ardalis.Specification/Expressions/OrderExpressionInfo.cs +++ b/Specification/src/Ardalis.Specification/Expressions/OrderExpressionInfo.cs @@ -3,43 +3,43 @@ namespace Ardalis.Specification { + /// + /// Encapsulates data needed to perform sorting. + /// + /// Type of the entity to apply sort on. + public class OrderExpressionInfo + { + private readonly Lazy> keySelectorFunc; + /// - /// Encapsulates data needed to perform sorting. + /// Creates instance of . /// - /// Type of the entity to apply sort on. - public class OrderExpressionInfo + /// A function to extract a key from an element. + /// Whether to (subsequently) sort ascending or descending. + /// If is null. + public OrderExpressionInfo(Expression> keySelector, OrderTypeEnum orderType) { - private readonly Lazy> keySelectorFunc; - - /// - /// Creates instance of . - /// - /// A function to extract a key from an element. - /// Whether to (subsequently) sort ascending or descending. - /// If is null. - public OrderExpressionInfo(Expression> keySelector, OrderTypeEnum orderType) - { - _ = keySelector ?? throw new ArgumentNullException(nameof(keySelector)); + _ = keySelector ?? throw new ArgumentNullException(nameof(keySelector)); - this.KeySelector = keySelector; - this.OrderType = orderType; + this.KeySelector = keySelector; + this.OrderType = orderType; - this.keySelectorFunc = new Lazy>(this.KeySelector.Compile); - } + this.keySelectorFunc = new Lazy>(this.KeySelector.Compile); + } - /// - /// A function to extract a key from an element. - /// - public Expression> KeySelector { get; } + /// + /// A function to extract a key from an element. + /// + public Expression> KeySelector { get; } - /// - /// Whether to (subsequently) sort ascending or descending. - /// - public OrderTypeEnum OrderType { get; } + /// + /// Whether to (subsequently) sort ascending or descending. + /// + public OrderTypeEnum OrderType { get; } - /// - /// Compiled . - /// - public Func KeySelectorFunc => this.keySelectorFunc.Value; - } + /// + /// Compiled . + /// + public Func KeySelectorFunc => this.keySelectorFunc.Value; + } } diff --git a/Specification/src/Ardalis.Specification/Expressions/SearchExpressionInfo.cs b/Specification/src/Ardalis.Specification/Expressions/SearchExpressionInfo.cs index 3711fe9f..d0774802 100644 --- a/Specification/src/Ardalis.Specification/Expressions/SearchExpressionInfo.cs +++ b/Specification/src/Ardalis.Specification/Expressions/SearchExpressionInfo.cs @@ -3,52 +3,52 @@ namespace Ardalis.Specification { + /// + /// Encapsulates data needed to perform 'SQL LIKE' operation. + /// + /// Type of the source from which search target should be selected. + public class SearchExpressionInfo + { + private readonly Lazy> selectorFunc; + /// - /// Encapsulates data needed to perform 'SQL LIKE' operation. + /// Creates instance of . /// - /// Type of the source from which search target should be selected. - public class SearchExpressionInfo + /// The property to apply the SQL LIKE against. + /// The value to use for the SQL LIKE. + /// The index used to group sets of Selectors and SearchTerms together. + /// If is null. + /// If is null or empty. + public SearchExpressionInfo(Expression> selector, string searchTerm, int searchGroup = 1) { - private readonly Lazy> selectorFunc; - - /// - /// Creates instance of . - /// - /// The property to apply the SQL LIKE against. - /// The value to use for the SQL LIKE. - /// The index used to group sets of Selectors and SearchTerms together. - /// If is null. - /// If is null or empty. - public SearchExpressionInfo(Expression> selector, string searchTerm, int searchGroup = 1) - { - _ = selector ?? throw new ArgumentNullException(nameof(selector)); - if (string.IsNullOrEmpty(searchTerm)) throw new ArgumentException(nameof(searchTerm)); - - this.Selector = selector; - this.SearchTerm = searchTerm; - this.SearchGroup = searchGroup; - - this.selectorFunc = new Lazy>(this.Selector.Compile); - } - - /// - /// The property to apply the SQL LIKE against. - /// - public Expression> Selector { get; } - - /// - /// The value to use for the SQL LIKE. - /// - public string SearchTerm { get; } - - /// - /// The index used to group sets of Selectors and SearchTerms together. - /// - public int SearchGroup { get; } - - /// - /// Compiled . - /// - public Func SelectorFunc => this.selectorFunc.Value; + _ = selector ?? throw new ArgumentNullException(nameof(selector)); + if (string.IsNullOrEmpty(searchTerm)) throw new ArgumentException(nameof(searchTerm)); + + this.Selector = selector; + this.SearchTerm = searchTerm; + this.SearchGroup = searchGroup; + + this.selectorFunc = new Lazy>(this.Selector.Compile); } + + /// + /// The property to apply the SQL LIKE against. + /// + public Expression> Selector { get; } + + /// + /// The value to use for the SQL LIKE. + /// + public string SearchTerm { get; } + + /// + /// The index used to group sets of Selectors and SearchTerms together. + /// + public int SearchGroup { get; } + + /// + /// Compiled . + /// + public Func SelectorFunc => this.selectorFunc.Value; + } } diff --git a/Specification/src/Ardalis.Specification/Expressions/WhereExpressionInfo.cs b/Specification/src/Ardalis.Specification/Expressions/WhereExpressionInfo.cs index eba94639..68202424 100644 --- a/Specification/src/Ardalis.Specification/Expressions/WhereExpressionInfo.cs +++ b/Specification/src/Ardalis.Specification/Expressions/WhereExpressionInfo.cs @@ -3,36 +3,36 @@ namespace Ardalis.Specification { + /// + /// Encapsulates data needed to perform filtering. + /// + /// Type of the entity to apply filter on. + public class WhereExpressionInfo + { + private readonly Lazy> filterFunc; + /// - /// Encapsulates data needed to perform filtering. + /// Creates instance of . /// - /// Type of the entity to apply filter on. - public class WhereExpressionInfo + /// Condition which should be satisfied by instances of . + /// If is null. + public WhereExpressionInfo(Expression> filter) { - private readonly Lazy> filterFunc; - - /// - /// Creates instance of . - /// - /// Condition which should be satisfied by instances of . - /// If is null. - public WhereExpressionInfo(Expression> filter) - { - _ = filter ?? throw new ArgumentNullException(nameof(filter)); + _ = filter ?? throw new ArgumentNullException(nameof(filter)); - this.Filter = filter; + this.Filter = filter; - this.filterFunc = new Lazy>(this.Filter.Compile); - } + this.filterFunc = new Lazy>(this.Filter.Compile); + } - /// - /// Condition which should be satisfied by instances of . - /// - public Expression> Filter { get; } + /// + /// Condition which should be satisfied by instances of . + /// + public Expression> Filter { get; } - /// - /// Compiled . - /// - public Func FilterFunc => this.filterFunc.Value; - } + /// + /// Compiled . + /// + public Func FilterFunc => this.filterFunc.Value; + } } diff --git a/Specification/src/Ardalis.Specification/IEntity.cs b/Specification/src/Ardalis.Specification/IEntity.cs index 1369d794..da137948 100644 --- a/Specification/src/Ardalis.Specification/IEntity.cs +++ b/Specification/src/Ardalis.Specification/IEntity.cs @@ -1,7 +1,7 @@ namespace Ardalis.Specification { - public interface IEntity - { - TId Id { get; set; } - } -} \ No newline at end of file + public interface IEntity + { + TId Id { get; set; } + } +} diff --git a/Specification/src/Ardalis.Specification/IReadRepositoryBase.cs b/Specification/src/Ardalis.Specification/IReadRepositoryBase.cs index 66f69751..f7fda4e0 100644 --- a/Specification/src/Ardalis.Specification/IReadRepositoryBase.cs +++ b/Specification/src/Ardalis.Specification/IReadRepositoryBase.cs @@ -4,120 +4,120 @@ namespace Ardalis.Specification { + /// + /// + /// A can be used to query instances of . + /// An (or derived) is used to encapsulate the LINQ queries against the database. + /// + /// + /// The type of entity being operated on by this repository. + public interface IReadRepositoryBase where T : class + { /// - /// - /// A can be used to query instances of . - /// An (or derived) is used to encapsulate the LINQ queries against the database. - /// + /// Finds an entity with the given primary key value. /// - /// The type of entity being operated on by this repository. - public interface IReadRepositoryBase where T : class - { - /// - /// Finds an entity with the given primary key value. - /// - /// The type of primary key. - /// The value of the primary key for the entity to be found. - /// - /// A task that represents the asynchronous operation. - /// The task result contains the , or . - /// - Task GetByIdAsync(TId id, CancellationToken cancellationToken = default) where TId : notnull; + /// The type of primary key. + /// The value of the primary key for the entity to be found. + /// + /// A task that represents the asynchronous operation. + /// The task result contains the , or . + /// + Task GetByIdAsync(TId id, CancellationToken cancellationToken = default) where TId : notnull; - /// - /// Finds an entity that matches the encapsulated query logic of the . - /// - /// The encapsulated query logic. - /// - /// A task that represents the asynchronous operation. - /// The task result contains the , or . - /// - Task GetBySpecAsync(Spec specification, CancellationToken cancellationToken = default) where Spec : ISingleResultSpecification, ISpecification; + /// + /// Finds an entity that matches the encapsulated query logic of the . + /// + /// The encapsulated query logic. + /// + /// A task that represents the asynchronous operation. + /// The task result contains the , or . + /// + Task GetBySpecAsync(Spec specification, CancellationToken cancellationToken = default) where Spec : ISingleResultSpecification, ISpecification; - /// - /// Finds an entity that matches the encapsulated query logic of the . - /// - /// The type of the result. - /// The encapsulated query logic. - /// - /// A task that represents the asynchronous operation. - /// The task result contains the . - /// - Task GetBySpecAsync(ISpecification specification, CancellationToken cancellationToken = default); + /// + /// Finds an entity that matches the encapsulated query logic of the . + /// + /// The type of the result. + /// The encapsulated query logic. + /// + /// A task that represents the asynchronous operation. + /// The task result contains the . + /// + Task GetBySpecAsync(ISpecification specification, CancellationToken cancellationToken = default); - /// - /// Finds all entities of from the database. - /// - /// - /// A task that represents the asynchronous operation. - /// The task result contains a that contains elements from the input sequence. - /// - Task> ListAsync(CancellationToken cancellationToken = default); + /// + /// Finds all entities of from the database. + /// + /// + /// A task that represents the asynchronous operation. + /// The task result contains a that contains elements from the input sequence. + /// + Task> ListAsync(CancellationToken cancellationToken = default); - /// - /// Finds all entities of , that matches the encapsulated query logic of the - /// , from the database. - /// - /// The encapsulated query logic. - /// - /// A task that represents the asynchronous operation. - /// The task result contains a that contains elements from the input sequence. - /// - Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default); + /// + /// Finds all entities of , that matches the encapsulated query logic of the + /// , from the database. + /// + /// The encapsulated query logic. + /// + /// A task that represents the asynchronous operation. + /// The task result contains a that contains elements from the input sequence. + /// + Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default); - /// - /// Finds all entities of , that matches the encapsulated query logic of the - /// , from the database. - /// - /// Projects each entity into a new form, being . - /// - /// - /// The type of the value returned by the projection. - /// The encapsulated query logic. - /// - /// A task that represents the asynchronous operation. - /// The task result contains a that contains elements from the input sequence. - /// - Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default); + /// + /// Finds all entities of , that matches the encapsulated query logic of the + /// , from the database. + /// + /// Projects each entity into a new form, being . + /// + /// + /// The type of the value returned by the projection. + /// The encapsulated query logic. + /// + /// A task that represents the asynchronous operation. + /// The task result contains a that contains elements from the input sequence. + /// + Task> ListAsync(ISpecification specification, CancellationToken cancellationToken = default); - /// - /// Returns a number that represents how many entities satisfy the encapsulated query logic - /// of the . - /// - /// The encapsulated query logic. - /// - /// A task that represents the asynchronous operation. The task result contains the - /// number of elements in the input sequence. - /// - Task CountAsync(ISpecification specification, CancellationToken cancellationToken = default); + /// + /// Returns a number that represents how many entities satisfy the encapsulated query logic + /// of the . + /// + /// The encapsulated query logic. + /// + /// A task that represents the asynchronous operation. The task result contains the + /// number of elements in the input sequence. + /// + Task CountAsync(ISpecification specification, CancellationToken cancellationToken = default); - /// - /// Returns the total number of records. - /// - /// - /// A task that represents the asynchronous operation. The task result contains the - /// number of elements in the input sequence. - /// - Task CountAsync(CancellationToken cancellationToken = default); + /// + /// Returns the total number of records. + /// + /// + /// A task that represents the asynchronous operation. The task result contains the + /// number of elements in the input sequence. + /// + Task CountAsync(CancellationToken cancellationToken = default); - /// - /// Returns a boolean that represents whether any entity satisfy the encapsulated query logic - /// of the or not. - /// - /// The encapsulated query logic. - /// - /// A task that represents the asynchronous operation. The task result contains true if the - /// source sequence contains any elements; otherwise, false. - /// - Task AnyAsync(ISpecification specification, CancellationToken cancellationToken = default); + /// + /// Returns a boolean that represents whether any entity satisfy the encapsulated query logic + /// of the or not. + /// + /// The encapsulated query logic. + /// + /// A task that represents the asynchronous operation. The task result contains true if the + /// source sequence contains any elements; otherwise, false. + /// + Task AnyAsync(ISpecification specification, CancellationToken cancellationToken = default); - /// - /// Returns a boolean whether any entity exists or not. - /// - /// - /// A task that represents the asynchronous operation. The task result contains true if the - /// source sequence contains any elements; otherwise, false. - /// - Task AnyAsync(CancellationToken cancellationToken = default); - } + /// + /// Returns a boolean whether any entity exists or not. + /// + /// + /// A task that represents the asynchronous operation. The task result contains true if the + /// source sequence contains any elements; otherwise, false. + /// + Task AnyAsync(CancellationToken cancellationToken = default); + } } diff --git a/Specification/src/Ardalis.Specification/IRepositoryBaseOfT.cs b/Specification/src/Ardalis.Specification/IRepositoryBaseOfT.cs index 02549993..ebdf7a6a 100644 --- a/Specification/src/Ardalis.Specification/IRepositoryBaseOfT.cs +++ b/Specification/src/Ardalis.Specification/IRepositoryBaseOfT.cs @@ -5,46 +5,46 @@ namespace Ardalis.Specification { + /// + /// + /// A can be used to query and save instances of . + /// An (or derived) is used to encapsulate the LINQ queries against the database. + /// + /// + /// The type of entity being operated on by this repository. + public interface IRepositoryBase : IReadRepositoryBase where T : class + { /// - /// - /// A can be used to query and save instances of . - /// An (or derived) is used to encapsulate the LINQ queries against the database. - /// + /// Adds an entity in the database. /// - /// The type of entity being operated on by this repository. - public interface IRepositoryBase : IReadRepositoryBase where T : class - { - /// - /// Adds an entity in the database. - /// - /// The entity to add. - /// - /// A task that represents the asynchronous operation. - /// The task result contains the . - /// - Task AddAsync(T entity, CancellationToken cancellationToken = default); - /// - /// Updates an entity in the database - /// - /// The entity to update. - /// A task that represents the asynchronous operation. - Task UpdateAsync(T entity, CancellationToken cancellationToken = default); - /// - /// Removes an entity in the database - /// - /// The entity to delete. - /// A task that represents the asynchronous operation. - Task DeleteAsync(T entity, CancellationToken cancellationToken = default); - /// - /// Removes the given entities in the database - /// - /// The entities to remove. - /// A task that represents the asynchronous operation. - Task DeleteRangeAsync(IEnumerable entities, CancellationToken cancellationToken = default); - /// - /// Persists changes to the database. - /// - /// A task that represents the asynchronous operation. - Task SaveChangesAsync(CancellationToken cancellationToken = default); - } + /// The entity to add. + /// + /// A task that represents the asynchronous operation. + /// The task result contains the . + /// + Task AddAsync(T entity, CancellationToken cancellationToken = default); + /// + /// Updates an entity in the database + /// + /// The entity to update. + /// A task that represents the asynchronous operation. + Task UpdateAsync(T entity, CancellationToken cancellationToken = default); + /// + /// Removes an entity in the database + /// + /// The entity to delete. + /// A task that represents the asynchronous operation. + Task DeleteAsync(T entity, CancellationToken cancellationToken = default); + /// + /// Removes the given entities in the database + /// + /// The entities to remove. + /// A task that represents the asynchronous operation. + Task DeleteRangeAsync(IEnumerable entities, CancellationToken cancellationToken = default); + /// + /// Persists changes to the database. + /// + /// A task that represents the asynchronous operation. + Task SaveChangesAsync(CancellationToken cancellationToken = default); + } } diff --git a/Specification/src/Ardalis.Specification/ISingleResultSpecification.cs b/Specification/src/Ardalis.Specification/ISingleResultSpecification.cs index d0a50f87..cfb47117 100644 --- a/Specification/src/Ardalis.Specification/ISingleResultSpecification.cs +++ b/Specification/src/Ardalis.Specification/ISingleResultSpecification.cs @@ -1,10 +1,10 @@ namespace Ardalis.Specification { - /// - /// A marker interface for specifications that are meant to return a single entity. Used to constrain methods - /// that accept a Specification and return a single result rather than a collection of results - /// - public interface ISingleResultSpecification - { - } + /// + /// A marker interface for specifications that are meant to return a single entity. Used to constrain methods + /// that accept a Specification and return a single result rather than a collection of results + /// + public interface ISingleResultSpecification + { + } } diff --git a/Specification/src/Ardalis.Specification/ISingleResultSpecificationOfT.cs b/Specification/src/Ardalis.Specification/ISingleResultSpecificationOfT.cs index 3659c2ce..1a10a907 100644 --- a/Specification/src/Ardalis.Specification/ISingleResultSpecificationOfT.cs +++ b/Specification/src/Ardalis.Specification/ISingleResultSpecificationOfT.cs @@ -4,7 +4,7 @@ namespace Ardalis.Specification { - public interface ISingleResultSpecification : ISpecification, ISingleResultSpecification - { - } + public interface ISingleResultSpecification : ISpecification, ISingleResultSpecification + { + } } diff --git a/Specification/src/Ardalis.Specification/ISpecification.cs b/Specification/src/Ardalis.Specification/ISpecification.cs index 0c90405a..9a57af04 100644 --- a/Specification/src/Ardalis.Specification/ISpecification.cs +++ b/Specification/src/Ardalis.Specification/ISpecification.cs @@ -4,132 +4,132 @@ namespace Ardalis.Specification { + /// + /// Encapsulates query logic for , + /// and projects the result into . + /// + /// The type being queried against. + /// The type of the result. + public interface ISpecification : ISpecification + { /// - /// Encapsulates query logic for , - /// and projects the result into . - /// - /// The type being queried against. - /// The type of the result. - public interface ISpecification : ISpecification - { - /// - /// The transform function to apply to the element. - /// - Expression>? Selector { get; } - - /// - /// The transform function to apply to the result of the query encapsulated by the . - /// - new Func, IEnumerable>? PostProcessingAction { get; } - - new IEnumerable Evaluate(IEnumerable entities); - } - - /// - /// Encapsulates query logic for . - /// - /// The type being queried against. - public interface ISpecification - { - /// - /// The collection of filters. - /// - IEnumerable> WhereExpressions { get; } - - /// - /// The collections of functions used to determine the sorting (and subsequent sorting), - /// to apply to the result of the query encapsulated by the . - /// - IEnumerable> OrderExpressions { get; } - - /// - /// The collection of s describing each include expression. - /// This information is utilized to build Include/ThenInclude functions in the query. - /// - IEnumerable IncludeExpressions { get; } - - /// - /// The collection of navigation properties, as strings, to include in the query. - /// - IEnumerable IncludeStrings { get; } - - /// - /// The collection of 'SQL LIKE' operations. - /// - IEnumerable> SearchCriterias { get; } - - /// - /// The number of elements to return. - /// - int? Take { get; } - - /// - /// The number of elements to skip before returning the remaining elements. - /// - int? Skip { get; } - - /// - /// The transform function to apply to the result of the query encapsulated by the . - /// - Func, IEnumerable>? PostProcessingAction { get; } - - /// - /// Return whether or not the results should be cached. - /// - bool CacheEnabled { get; } - - /// - /// The identifier to use to store and retrieve results from the cache. - /// - string? CacheKey { get; } - - /// - /// Returns whether or not the change tracker will track any of the entities - /// that are returned. When true, if the entity instances are modified, this will not be detected - /// by the change tracker. - /// - bool AsNoTracking { get; } - - /// - /// Returns whether or not the generated sql query should be split into multiple SQL queries - /// - /// - /// This feature was introduced in EF Core 5.0. It only works when using Include - /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/single-split-queries - /// - bool AsSplitQuery { get; } - - /// - /// Returns whether or not the query will then keep track of returned instances - /// (without tracking them in the normal way) - /// and ensure no duplicates are created in the query results - /// - /// - /// for more info: https://docs.microsoft.com/en-us/ef/core/change-tracking/identity-resolution#identity-resolution-and-queries - /// - bool AsNoTrackingWithIdentityResolution { get; } - - /// - /// Returns whether or not the query should ignore the defined global query filters - /// - /// - /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/filters - /// - bool IgnoreQueryFilters { get; } - - /// - /// Applies the query defined within the specification to the given objects. - /// This is specially helpful when unit testing specification classes - /// - /// the list of entities to which the specification will be applied - /// - IEnumerable Evaluate(IEnumerable entities); - - /// - /// It returns whether the given entity satisfies the conditions of the specification. - /// - /// The entity to be validated - /// - bool IsSatisfiedBy(T entity); - } -} \ No newline at end of file + /// The transform function to apply to the element. + /// + Expression>? Selector { get; } + + /// + /// The transform function to apply to the result of the query encapsulated by the . + /// + new Func, IEnumerable>? PostProcessingAction { get; } + + new IEnumerable Evaluate(IEnumerable entities); + } + + /// + /// Encapsulates query logic for . + /// + /// The type being queried against. + public interface ISpecification + { + /// + /// The collection of filters. + /// + IEnumerable> WhereExpressions { get; } + + /// + /// The collections of functions used to determine the sorting (and subsequent sorting), + /// to apply to the result of the query encapsulated by the . + /// + IEnumerable> OrderExpressions { get; } + + /// + /// The collection of s describing each include expression. + /// This information is utilized to build Include/ThenInclude functions in the query. + /// + IEnumerable IncludeExpressions { get; } + + /// + /// The collection of navigation properties, as strings, to include in the query. + /// + IEnumerable IncludeStrings { get; } + + /// + /// The collection of 'SQL LIKE' operations. + /// + IEnumerable> SearchCriterias { get; } + + /// + /// The number of elements to return. + /// + int? Take { get; } + + /// + /// The number of elements to skip before returning the remaining elements. + /// + int? Skip { get; } + + /// + /// The transform function to apply to the result of the query encapsulated by the . + /// + Func, IEnumerable>? PostProcessingAction { get; } + + /// + /// Return whether or not the results should be cached. + /// + bool CacheEnabled { get; } + + /// + /// The identifier to use to store and retrieve results from the cache. + /// + string? CacheKey { get; } + + /// + /// Returns whether or not the change tracker will track any of the entities + /// that are returned. When true, if the entity instances are modified, this will not be detected + /// by the change tracker. + /// + bool AsNoTracking { get; } + + /// + /// Returns whether or not the generated sql query should be split into multiple SQL queries + /// + /// + /// This feature was introduced in EF Core 5.0. It only works when using Include + /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/single-split-queries + /// + bool AsSplitQuery { get; } + + /// + /// Returns whether or not the query will then keep track of returned instances + /// (without tracking them in the normal way) + /// and ensure no duplicates are created in the query results + /// + /// + /// for more info: https://docs.microsoft.com/en-us/ef/core/change-tracking/identity-resolution#identity-resolution-and-queries + /// + bool AsNoTrackingWithIdentityResolution { get; } + + /// + /// Returns whether or not the query should ignore the defined global query filters + /// + /// + /// for more info: https://docs.microsoft.com/en-us/ef/core/querying/filters + /// + bool IgnoreQueryFilters { get; } + + /// + /// Applies the query defined within the specification to the given objects. + /// This is specially helpful when unit testing specification classes + /// + /// the list of entities to which the specification will be applied + /// + IEnumerable Evaluate(IEnumerable entities); + + /// + /// It returns whether the given entity satisfies the conditions of the specification. + /// + /// The entity to be validated + /// + bool IsSatisfiedBy(T entity); + } +} diff --git a/Specification/src/Ardalis.Specification/IncludeTypeEnum.cs b/Specification/src/Ardalis.Specification/IncludeTypeEnum.cs index 3d21790f..7a99c3bb 100644 --- a/Specification/src/Ardalis.Specification/IncludeTypeEnum.cs +++ b/Specification/src/Ardalis.Specification/IncludeTypeEnum.cs @@ -4,9 +4,9 @@ namespace Ardalis.Specification { - public enum IncludeTypeEnum - { - Include = 1, - ThenInclude = 2 - } + public enum IncludeTypeEnum + { + Include = 1, + ThenInclude = 2 + } } diff --git a/Specification/src/Ardalis.Specification/OrderTypeEnum.cs b/Specification/src/Ardalis.Specification/OrderTypeEnum.cs index 05c45227..d645c398 100644 --- a/Specification/src/Ardalis.Specification/OrderTypeEnum.cs +++ b/Specification/src/Ardalis.Specification/OrderTypeEnum.cs @@ -4,14 +4,14 @@ namespace Ardalis.Specification { - /// - /// Whether to (subsequently) sort ascending or descending. - /// - public enum OrderTypeEnum - { - OrderBy = 1, - OrderByDescending = 2, - ThenBy = 3, - ThenByDescending = 4 - } + /// + /// Whether to (subsequently) sort ascending or descending. + /// + public enum OrderTypeEnum + { + OrderBy = 1, + OrderByDescending = 2, + ThenBy = 3, + ThenByDescending = 4 + } } diff --git a/Specification/src/Ardalis.Specification/Specification.cs b/Specification/src/Ardalis.Specification/Specification.cs index 05a20231..d32dc03b 100644 --- a/Specification/src/Ardalis.Specification/Specification.cs +++ b/Specification/src/Ardalis.Specification/Specification.cs @@ -4,114 +4,114 @@ namespace Ardalis.Specification { - /// - public abstract class Specification : Specification, ISpecification + /// + public abstract class Specification : Specification, ISpecification + { + protected new virtual ISpecificationBuilder Query { get; } + + protected Specification() + : this(InMemorySpecificationEvaluator.Default) { - protected new virtual ISpecificationBuilder Query { get; } + } + + protected Specification(IInMemorySpecificationEvaluator inMemorySpecificationEvaluator) + : base(inMemorySpecificationEvaluator) + { + this.Query = new SpecificationBuilder(this); + } - protected Specification() - : this(InMemorySpecificationEvaluator.Default) - { - } + public new virtual IEnumerable Evaluate(IEnumerable entities) + { + return Evaluator.Evaluate(entities, this); + } - protected Specification(IInMemorySpecificationEvaluator inMemorySpecificationEvaluator) - : base(inMemorySpecificationEvaluator) - { - this.Query = new SpecificationBuilder(this); - } + /// + public Expression>? Selector { get; internal set; } - public new virtual IEnumerable Evaluate(IEnumerable entities) - { - return Evaluator.Evaluate(entities, this); - } + /// + public new Func, IEnumerable>? PostProcessingAction { get; internal set; } = null; + } - /// - public Expression>? Selector { get; internal set; } + /// + public abstract class Specification : ISpecification + { + protected IInMemorySpecificationEvaluator Evaluator { get; } + protected ISpecificationValidator Validator { get; } + protected virtual ISpecificationBuilder Query { get; } - /// - public new Func, IEnumerable>? PostProcessingAction { get; internal set; } = null; + protected Specification() + : this(InMemorySpecificationEvaluator.Default, SpecificationValidator.Default) + { } - /// - public abstract class Specification : ISpecification + protected Specification(IInMemorySpecificationEvaluator inMemorySpecificationEvaluator) + : this(inMemorySpecificationEvaluator, SpecificationValidator.Default) { - protected IInMemorySpecificationEvaluator Evaluator { get; } - protected ISpecificationValidator Validator { get; } - protected virtual ISpecificationBuilder Query { get; } - - protected Specification() - : this(InMemorySpecificationEvaluator.Default, SpecificationValidator.Default) - { - } - - protected Specification(IInMemorySpecificationEvaluator inMemorySpecificationEvaluator) - : this(inMemorySpecificationEvaluator, SpecificationValidator.Default) - { - } + } - protected Specification(ISpecificationValidator specificationValidator) - : this(InMemorySpecificationEvaluator.Default, specificationValidator) - { - } + protected Specification(ISpecificationValidator specificationValidator) + : this(InMemorySpecificationEvaluator.Default, specificationValidator) + { + } - protected Specification(IInMemorySpecificationEvaluator inMemorySpecificationEvaluator, ISpecificationValidator specificationValidator) - { - this.Evaluator = inMemorySpecificationEvaluator; - this.Validator = specificationValidator; - this.Query = new SpecificationBuilder(this); - } + protected Specification(IInMemorySpecificationEvaluator inMemorySpecificationEvaluator, ISpecificationValidator specificationValidator) + { + this.Evaluator = inMemorySpecificationEvaluator; + this.Validator = specificationValidator; + this.Query = new SpecificationBuilder(this); + } - /// - public virtual IEnumerable Evaluate(IEnumerable entities) - { - return Evaluator.Evaluate(entities, this); - } + /// + public virtual IEnumerable Evaluate(IEnumerable entities) + { + return Evaluator.Evaluate(entities, this); + } - /// - public virtual bool IsSatisfiedBy(T entity) - { - return Validator.IsValid(entity, this); - } + /// + public virtual bool IsSatisfiedBy(T entity) + { + return Validator.IsValid(entity, this); + } - /// - public IEnumerable> WhereExpressions { get; } = new List>(); + /// + public IEnumerable> WhereExpressions { get; } = new List>(); - public IEnumerable> OrderExpressions { get; } = new List>(); + public IEnumerable> OrderExpressions { get; } = new List>(); - /// - public IEnumerable IncludeExpressions { get; } = new List(); + /// + public IEnumerable IncludeExpressions { get; } = new List(); - /// - public IEnumerable IncludeStrings { get; } = new List(); + /// + public IEnumerable IncludeStrings { get; } = new List(); - /// - public IEnumerable> SearchCriterias { get; } = new List>(); + /// + public IEnumerable> SearchCriterias { get; } = new List>(); - /// - public int? Take { get; internal set; } = null; + /// + public int? Take { get; internal set; } = null; - /// - public int? Skip { get; internal set; } = null; + /// + public int? Skip { get; internal set; } = null; - /// - public Func, IEnumerable>? PostProcessingAction { get; internal set; } = null; + /// + public Func, IEnumerable>? PostProcessingAction { get; internal set; } = null; - /// - public string? CacheKey { get; internal set; } + /// + public string? CacheKey { get; internal set; } - /// - public bool CacheEnabled { get; internal set; } + /// + public bool CacheEnabled { get; internal set; } - /// - public bool AsNoTracking { get; internal set; } = false; + /// + public bool AsNoTracking { get; internal set; } = false; - /// - public bool AsSplitQuery { get; internal set; } = false; + /// + public bool AsSplitQuery { get; internal set; } = false; - /// - public bool AsNoTrackingWithIdentityResolution { get; internal set; } = false; + /// + public bool AsNoTrackingWithIdentityResolution { get; internal set; } = false; - /// - public bool IgnoreQueryFilters { get; internal set; } = false; - } -} \ No newline at end of file + /// + public bool IgnoreQueryFilters { get; internal set; } = false; + } +} diff --git a/Specification/src/Ardalis.Specification/Validators/ISpecificationValidator.cs b/Specification/src/Ardalis.Specification/Validators/ISpecificationValidator.cs index e66c0b09..c7b2914f 100644 --- a/Specification/src/Ardalis.Specification/Validators/ISpecificationValidator.cs +++ b/Specification/src/Ardalis.Specification/Validators/ISpecificationValidator.cs @@ -4,8 +4,8 @@ namespace Ardalis.Specification { - public interface ISpecificationValidator - { - bool IsValid(T entity, ISpecification specification); - } + public interface ISpecificationValidator + { + bool IsValid(T entity, ISpecification specification); + } } diff --git a/Specification/src/Ardalis.Specification/Validators/IValidator.cs b/Specification/src/Ardalis.Specification/Validators/IValidator.cs index 5e882cad..952a088b 100644 --- a/Specification/src/Ardalis.Specification/Validators/IValidator.cs +++ b/Specification/src/Ardalis.Specification/Validators/IValidator.cs @@ -4,8 +4,8 @@ namespace Ardalis.Specification { - public interface IValidator - { - bool IsValid(T entity, ISpecification specification); - } + public interface IValidator + { + bool IsValid(T entity, ISpecification specification); + } } diff --git a/Specification/src/Ardalis.Specification/Validators/SearchValidator.cs b/Specification/src/Ardalis.Specification/Validators/SearchValidator.cs index cac4485c..1cec047f 100644 --- a/Specification/src/Ardalis.Specification/Validators/SearchValidator.cs +++ b/Specification/src/Ardalis.Specification/Validators/SearchValidator.cs @@ -5,19 +5,19 @@ namespace Ardalis.Specification { - public class SearchValidator : IValidator - { - private SearchValidator() { } - public static SearchValidator Instance { get; } = new SearchValidator(); + public class SearchValidator : IValidator + { + private SearchValidator() { } + public static SearchValidator Instance { get; } = new SearchValidator(); - public bool IsValid(T entity, ISpecification specification) - { - foreach (var searchGroup in specification.SearchCriterias.GroupBy(x => x.SearchGroup)) - { - if (searchGroup.Any(c => c.SelectorFunc(entity).Like(c.SearchTerm)) == false) return false; - } + public bool IsValid(T entity, ISpecification specification) + { + foreach (var searchGroup in specification.SearchCriterias.GroupBy(x => x.SearchGroup)) + { + if (searchGroup.Any(c => c.SelectorFunc(entity).Like(c.SearchTerm)) == false) return false; + } - return true; - } + return true; } + } } diff --git a/Specification/src/Ardalis.Specification/Validators/SpecificationValidator.cs b/Specification/src/Ardalis.Specification/Validators/SpecificationValidator.cs index 4b6151bb..6ec6498e 100644 --- a/Specification/src/Ardalis.Specification/Validators/SpecificationValidator.cs +++ b/Specification/src/Ardalis.Specification/Validators/SpecificationValidator.cs @@ -4,34 +4,34 @@ namespace Ardalis.Specification { - public class SpecificationValidator : ISpecificationValidator - { - // Will use singleton for default configuration. Yet, it can be instantiated if necessary, with default or provided validators. - public static SpecificationValidator Default { get; } = new SpecificationValidator(); + public class SpecificationValidator : ISpecificationValidator + { + // Will use singleton for default configuration. Yet, it can be instantiated if necessary, with default or provided validators. + public static SpecificationValidator Default { get; } = new SpecificationValidator(); - private readonly List validators = new List(); + private readonly List validators = new List(); - public SpecificationValidator() - { - this.validators.AddRange(new IValidator[] - { + public SpecificationValidator() + { + this.validators.AddRange(new IValidator[] + { WhereValidator.Instance, SearchValidator.Instance - }); - } - public SpecificationValidator(IEnumerable validators) - { - this.validators.AddRange(validators); - } + }); + } + public SpecificationValidator(IEnumerable validators) + { + this.validators.AddRange(validators); + } - public virtual bool IsValid(T entity, ISpecification specification) - { - foreach (var partialValidator in validators) - { - if (partialValidator.IsValid(entity, specification) == false) return false; - } + public virtual bool IsValid(T entity, ISpecification specification) + { + foreach (var partialValidator in validators) + { + if (partialValidator.IsValid(entity, specification) == false) return false; + } - return true; - } + return true; } + } } diff --git a/Specification/src/Ardalis.Specification/Validators/WhereValidator.cs b/Specification/src/Ardalis.Specification/Validators/WhereValidator.cs index a7f913ff..4b31f3a1 100644 --- a/Specification/src/Ardalis.Specification/Validators/WhereValidator.cs +++ b/Specification/src/Ardalis.Specification/Validators/WhereValidator.cs @@ -4,19 +4,19 @@ namespace Ardalis.Specification { - public class WhereValidator : IValidator - { - private WhereValidator() { } - public static WhereValidator Instance { get; } = new WhereValidator(); + public class WhereValidator : IValidator + { + private WhereValidator() { } + public static WhereValidator Instance { get; } = new WhereValidator(); - public bool IsValid(T entity, ISpecification specification) - { - foreach (var info in specification.WhereExpressions) - { - if (info.FilterFunc(entity) == false) return false; - } + public bool IsValid(T entity, ISpecification specification) + { + foreach (var info in specification.WhereExpressions) + { + if (info.FilterFunc(entity) == false) return false; + } - return true; - } + return true; } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/IncludableBuilderExtensions_ThenInclude.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/IncludableBuilderExtensions_ThenInclude.cs index c8001873..41a7817c 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/IncludableBuilderExtensions_ThenInclude.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/IncludableBuilderExtensions_ThenInclude.cs @@ -7,49 +7,49 @@ namespace Ardalis.Specification.UnitTests { - public class IncludableBuilderExtensions_ThenInclude + public class IncludableBuilderExtensions_ThenInclude + { + [Fact] + public void AppendIncludeExpressionInfoToListWithTypeThenInclude_GivenThenIncludeExpression() { - [Fact] - public void AppendIncludeExpressionInfoToListWithTypeThenInclude_GivenThenIncludeExpression() - { - var spec = new StoreIncludeCompanyThenCountrySpec(); + var spec = new StoreIncludeCompanyThenCountrySpec(); - var includeExpressions = spec.IncludeExpressions.ToList(); + var includeExpressions = spec.IncludeExpressions.ToList(); - // The list must have two items, since ThenInclude can be applied once the first level is applied. - includeExpressions.Should().HaveCount(2); + // The list must have two items, since ThenInclude can be applied once the first level is applied. + includeExpressions.Should().HaveCount(2); - includeExpressions[1].Type.Should().Be(IncludeTypeEnum.ThenInclude); - } + includeExpressions[1].Type.Should().Be(IncludeTypeEnum.ThenInclude); + } - [Fact] - public void AddsNothingToList_GivenDiscardedIncludeChain() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void AddsNothingToList_GivenDiscardedIncludeChain() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.IncludeExpressions.Should().BeEmpty(); - } + spec.IncludeExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsNothingToList_GivenThenIncludeExpressionWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditionsForInnerChains(1); + [Fact] + public void AddsNothingToList_GivenThenIncludeExpressionWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditionsForInnerChains(1); - spec.IncludeExpressions.Should().HaveCount(1); - spec.IncludeExpressions.First().Type.Should().Be(IncludeTypeEnum.Include); - spec.IncludeExpressions.Where(x => x.Type == IncludeTypeEnum.ThenInclude).Should().BeEmpty(); - } + spec.IncludeExpressions.Should().HaveCount(1); + spec.IncludeExpressions.First().Type.Should().Be(IncludeTypeEnum.Include); + spec.IncludeExpressions.Where(x => x.Type == IncludeTypeEnum.ThenInclude).Should().BeEmpty(); + } - [Fact] - public void ThenInclude_Append_IncludeExpressionInfo_With_EnumerablePreviousPropertyType() - { - var spec = new StoreIncludeCompanyThenStoresSpec(); + [Fact] + public void ThenInclude_Append_IncludeExpressionInfo_With_EnumerablePreviousPropertyType() + { + var spec = new StoreIncludeCompanyThenStoresSpec(); - var includeExpressions = spec.IncludeExpressions.ToList(); + var includeExpressions = spec.IncludeExpressions.ToList(); - includeExpressions.Should().HaveCount(3); + includeExpressions.Should().HaveCount(3); - includeExpressions[2].PreviousPropertyType.Should().Be(typeof(IEnumerable)); - } + includeExpressions[2].PreviousPropertyType.Should().Be(typeof(IEnumerable)); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/OrderedBuilderExtensions_ThenBy.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/OrderedBuilderExtensions_ThenBy.cs index b70dee2f..6b7502df 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/OrderedBuilderExtensions_ThenBy.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/OrderedBuilderExtensions_ThenBy.cs @@ -1,46 +1,46 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class OrderedBuilderExtensions_ThenBy + public class OrderedBuilderExtensions_ThenBy + { + [Fact] + public void AppendOrderExpressionToListWithThenByType_GivenThenByExpression() { - [Fact] - public void AppendOrderExpressionToListWithThenByType_GivenThenByExpression() - { - var spec = new StoresByCompanyOrderedDescByNameThenByIdSpec(1); + var spec = new StoresByCompanyOrderedDescByNameThenByIdSpec(1); - var orderExpressions = spec.OrderExpressions.ToList(); + var orderExpressions = spec.OrderExpressions.ToList(); - // The list must have two items, since Then can be applied once the first level is applied. - orderExpressions.Should().HaveCount(2); + // The list must have two items, since Then can be applied once the first level is applied. + orderExpressions.Should().HaveCount(2); - orderExpressions[1].OrderType.Should().Be(OrderTypeEnum.ThenBy); - } + orderExpressions[1].OrderType.Should().Be(OrderTypeEnum.ThenBy); + } - [Fact] - public void AddsNothingToList_GivenDiscardedOrderChain() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void AddsNothingToList_GivenDiscardedOrderChain() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.OrderExpressions.Should().BeEmpty(); - } + spec.OrderExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsNothingToList_GivenThenByExpressionWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditionsForInnerChains(1); + [Fact] + public void AddsNothingToList_GivenThenByExpressionWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditionsForInnerChains(1); - spec.OrderExpressions.Should().HaveCount(2); - spec.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy); - spec.OrderExpressions.Skip(1).First().OrderType.Should().Be(OrderTypeEnum.OrderByDescending); - spec.OrderExpressions.Where(x => x.OrderType == OrderTypeEnum.ThenBy).Should().BeEmpty(); - } + spec.OrderExpressions.Should().HaveCount(2); + spec.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy); + spec.OrderExpressions.Skip(1).First().OrderType.Should().Be(OrderTypeEnum.OrderByDescending); + spec.OrderExpressions.Where(x => x.OrderType == OrderTypeEnum.ThenBy).Should().BeEmpty(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/OrderedBuilderExtensions_ThenByDescending.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/OrderedBuilderExtensions_ThenByDescending.cs index f92a3b41..0de28e3d 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/OrderedBuilderExtensions_ThenByDescending.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/OrderedBuilderExtensions_ThenByDescending.cs @@ -1,46 +1,46 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class OrderedBuilderExtensions_ThenByDescending + public class OrderedBuilderExtensions_ThenByDescending + { + [Fact] + public void AppendsOrderExpressionToListWithThenByDescendingType_GivenThenByDescendingExpression() { - [Fact] - public void AppendsOrderExpressionToListWithThenByDescendingType_GivenThenByDescendingExpression() - { - var spec = new StoresByCompanyOrderedDescByNameThenByDescIdSpec(1); + var spec = new StoresByCompanyOrderedDescByNameThenByDescIdSpec(1); - var orderExpressions = spec.OrderExpressions.ToList(); + var orderExpressions = spec.OrderExpressions.ToList(); - // The list must have two items, since Then can be applied once the first level is applied. - orderExpressions.Should().HaveCount(2); + // The list must have two items, since Then can be applied once the first level is applied. + orderExpressions.Should().HaveCount(2); - orderExpressions[1].OrderType.Should().Be(OrderTypeEnum.ThenByDescending); - } + orderExpressions[1].OrderType.Should().Be(OrderTypeEnum.ThenByDescending); + } - [Fact] - public void AddsNothingToList_GivenDiscardedOrderChain() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void AddsNothingToList_GivenDiscardedOrderChain() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.OrderExpressions.Should().BeEmpty(); - } + spec.OrderExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsNothingToList_GivenThenByDescendingExpressionWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditionsForInnerChains(1); + [Fact] + public void AddsNothingToList_GivenThenByDescendingExpressionWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditionsForInnerChains(1); - spec.OrderExpressions.Should().HaveCount(2); - spec.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy); - spec.OrderExpressions.Skip(1).First().OrderType.Should().Be(OrderTypeEnum.OrderByDescending); - spec.OrderExpressions.Where(x => x.OrderType == OrderTypeEnum.ThenByDescending).Should().BeEmpty(); - } + spec.OrderExpressions.Should().HaveCount(2); + spec.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy); + spec.OrderExpressions.Skip(1).First().OrderType.Should().Be(OrderTypeEnum.OrderByDescending); + spec.OrderExpressions.Where(x => x.OrderType == OrderTypeEnum.ThenByDescending).Should().BeEmpty(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsNoTracking.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsNoTracking.cs index 12d55039..ec4d7beb 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsNoTracking.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsNoTracking.cs @@ -4,30 +4,30 @@ namespace Ardalis.Specification.UnitTests.BuilderTests { - public class SpecificationBuilderExtensions_AsNoTracking + public class SpecificationBuilderExtensions_AsNoTracking + { + [Fact] + public void DoesNothing_GivenSpecWithoutAsNoTracking() { - [Fact] - public void DoesNothing_GivenSpecWithoutAsNoTracking() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.AsNoTracking.Should().Be(false); - } + spec.AsNoTracking.Should().Be(false); + } - [Fact] - public void DoesNothing_GivenAsNoTrackingWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void DoesNothing_GivenAsNoTrackingWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.AsNoTracking.Should().Be(false); - } + spec.AsNoTracking.Should().Be(false); + } - [Fact] - public void FlagsAsNoTracking_GivenSpecWithAsNoTracking() - { - var spec = new CompanyByIdAsUntrackedSpec(1); + [Fact] + public void FlagsAsNoTracking_GivenSpecWithAsNoTracking() + { + var spec = new CompanyByIdAsUntrackedSpec(1); - spec.AsNoTracking.Should().Be(true); - } + spec.AsNoTracking.Should().Be(true); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsNoTrackingWithIdentityResolution.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsNoTrackingWithIdentityResolution.cs index d2a37170..4916bc76 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsNoTrackingWithIdentityResolution.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsNoTrackingWithIdentityResolution.cs @@ -4,30 +4,30 @@ namespace Ardalis.Specification.UnitTests.BuilderTests { - public class SpecificationBuilderExtensions_AsNoTrackingWithIdentityResolution + public class SpecificationBuilderExtensions_AsNoTrackingWithIdentityResolution + { + [Fact] + public void DoesNothing_GivenSpecWithoutAsNoTrackingWithIdentityResolution() { - [Fact] - public void DoesNothing_GivenSpecWithoutAsNoTrackingWithIdentityResolution() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.AsNoTrackingWithIdentityResolution.Should().Be(false); - } + spec.AsNoTrackingWithIdentityResolution.Should().Be(false); + } - [Fact] - public void DoesNothing_GivenAsNoTrackingWithIdentityResolutionWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void DoesNothing_GivenAsNoTrackingWithIdentityResolutionWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.AsNoTrackingWithIdentityResolution.Should().Be(false); - } + spec.AsNoTrackingWithIdentityResolution.Should().Be(false); + } - [Fact] - public void FlagsAsNoTracking_GivenSpecWithAsNoTrackingWithIdentityResolution() - { - var spec = new CompanyByIdAsUntrackedWithIdentityResolutionSpec(1); + [Fact] + public void FlagsAsNoTracking_GivenSpecWithAsNoTrackingWithIdentityResolution() + { + var spec = new CompanyByIdAsUntrackedWithIdentityResolutionSpec(1); - spec.AsNoTrackingWithIdentityResolution.Should().Be(true); - } + spec.AsNoTrackingWithIdentityResolution.Should().Be(true); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsSplitQuery.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsSplitQuery.cs index 12a955c9..97b688d1 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsSplitQuery.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsSplitQuery.cs @@ -4,30 +4,30 @@ namespace Ardalis.Specification.UnitTests.BuilderTests { - public class SpecificationBuilderExtensions_AsSplitQuery + public class SpecificationBuilderExtensions_AsSplitQuery + { + [Fact] + public void DoesNothing_GivenSpecWithoutAsSplitQuery() { - [Fact] - public void DoesNothing_GivenSpecWithoutAsSplitQuery() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.AsSplitQuery.Should().Be(false); - } + spec.AsSplitQuery.Should().Be(false); + } - [Fact] - public void DoesNothing_GivenAsSplitQueryWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void DoesNothing_GivenAsSplitQueryWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.AsSplitQuery.Should().Be(false); - } + spec.AsSplitQuery.Should().Be(false); + } - [Fact] - public void FlagsAsNoTracking_GivenSpecWithAsSplitQuery() - { - var spec = new CompanyByIdAsSplitQuery(1); + [Fact] + public void FlagsAsNoTracking_GivenSpecWithAsSplitQuery() + { + var spec = new CompanyByIdAsSplitQuery(1); - spec.AsSplitQuery.Should().Be(true); - } + spec.AsSplitQuery.Should().Be(true); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_IgnoreQueryFilters.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_IgnoreQueryFilters.cs index e120cc10..be66b0ec 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_IgnoreQueryFilters.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_IgnoreQueryFilters.cs @@ -4,30 +4,30 @@ namespace Ardalis.Specification.UnitTests.BuilderTests { - public class SpecificationBuilderExtensions_IgnoreQueryFilters + public class SpecificationBuilderExtensions_IgnoreQueryFilters + { + [Fact] + public void DoesNothing_GivenSpecWithoutIgnoreQueryFilters() { - [Fact] - public void DoesNothing_GivenSpecWithoutIgnoreQueryFilters() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.IgnoreQueryFilters.Should().Be(false); - } + spec.IgnoreQueryFilters.Should().Be(false); + } - [Fact] - public void DoesNothing_GivenIgnoreQueryFiltersWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void DoesNothing_GivenIgnoreQueryFiltersWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.IgnoreQueryFilters.Should().Be(false); - } + spec.IgnoreQueryFilters.Should().Be(false); + } - [Fact] - public void FlagsIgnoreQueryFilters_GivenSpecWithIgnoreQueryFilters() - { - var spec = new CompanyByIdIgnoreQueryFilters(1); + [Fact] + public void FlagsIgnoreQueryFilters_GivenSpecWithIgnoreQueryFilters() + { + var spec = new CompanyByIdIgnoreQueryFilters(1); - spec.IgnoreQueryFilters.Should().Be(true); - } + spec.IgnoreQueryFilters.Should().Be(true); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Include.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Include.cs index 02da6c87..988eed52 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Include.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Include.cs @@ -1,39 +1,39 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class SpecificationBuilderExtensions_Include + public class SpecificationBuilderExtensions_Include + { + [Fact] + public void AddsNothingToList_GivenNoIncludeExpression() { - [Fact] - public void AddsNothingToList_GivenNoIncludeExpression() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.IncludeExpressions.Should().BeEmpty(); - } + spec.IncludeExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsNothingToList_GivenIncludeExpressionWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void AddsNothingToList_GivenIncludeExpressionWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.IncludeExpressions.Should().BeEmpty(); - } + spec.IncludeExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsIncludeExpressionInfoToListWithTypeInclude_GivenIncludeExpression() - { - var spec = new StoreIncludeAddressSpec(); + [Fact] + public void AddsIncludeExpressionInfoToListWithTypeInclude_GivenIncludeExpression() + { + var spec = new StoreIncludeAddressSpec(); - spec.IncludeExpressions.Should().ContainSingle(); - spec.IncludeExpressions.Single().Type.Should().Be(IncludeTypeEnum.Include); - } + spec.IncludeExpressions.Should().ContainSingle(); + spec.IncludeExpressions.Single().Type.Should().Be(IncludeTypeEnum.Include); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_IncludeString.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_IncludeString.cs index 005e98be..01274505 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_IncludeString.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_IncludeString.cs @@ -1,41 +1,41 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class SpecificationBuilderExtensions_IncludeString + public class SpecificationBuilderExtensions_IncludeString + { + [Fact] + public void AddsNothingToList_GivenNoIncludeStringExpression() { - [Fact] - public void AddsNothingToList_GivenNoIncludeStringExpression() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.WhereExpressions.Should().BeEmpty(); - } + spec.WhereExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsNothingToList_GivenIncludeStringWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void AddsNothingToList_GivenIncludeStringWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.IncludeStrings.Should().BeEmpty(); - } + spec.IncludeStrings.Should().BeEmpty(); + } - [Fact] - public void AddsIncludeStringToList_GivenString() - { - var spec = new StoreIncludeCompanyThenCountryAsStringSpec(); + [Fact] + public void AddsIncludeStringToList_GivenString() + { + var spec = new StoreIncludeCompanyThenCountryAsStringSpec(); - var expected = $"{nameof(Company)}.{nameof(Company.Country)}"; + var expected = $"{nameof(Company)}.{nameof(Company.Country)}"; - spec.IncludeStrings.Should().ContainSingle(); - spec.IncludeStrings.Single().Should().Be(expected); - } + spec.IncludeStrings.Should().ContainSingle(); + spec.IncludeStrings.Single().Should().Be(expected); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_OrderBy.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_OrderBy.cs index ad9c24e1..c351b11c 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_OrderBy.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_OrderBy.cs @@ -1,39 +1,39 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class SpecificationBuilderExtensions_OrderBy + public class SpecificationBuilderExtensions_OrderBy + { + [Fact] + public void AddsNothingToList_GivenNoOrderExpression() { - [Fact] - public void AddsNothingToList_GivenNoOrderExpression() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.OrderExpressions.Should().BeEmpty(); - } + spec.OrderExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsNothingToList_GivenOrderExpressionWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void AddsNothingToList_GivenOrderExpressionWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.OrderExpressions.Should().BeEmpty(); - } + spec.OrderExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsOrderExpressionToListWithOrderByType_GivenOrderByExpression() - { - var spec = new StoresOrderedSpecByName(); + [Fact] + public void AddsOrderExpressionToListWithOrderByType_GivenOrderByExpression() + { + var spec = new StoresOrderedSpecByName(); - spec.OrderExpressions.Should().ContainSingle(); - spec.OrderExpressions.Single().OrderType.Should().Be(OrderTypeEnum.OrderBy); - } + spec.OrderExpressions.Should().ContainSingle(); + spec.OrderExpressions.Single().OrderType.Should().Be(OrderTypeEnum.OrderBy); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_OrderByDescending.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_OrderByDescending.cs index f5322158..3a59828a 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_OrderByDescending.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_OrderByDescending.cs @@ -1,39 +1,39 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class SpecificationBuilderExtensions_OrderByDescending + public class SpecificationBuilderExtensions_OrderByDescending + { + [Fact] + public void AddsNothingToList_GivenNoOrderExpression() { - [Fact] - public void AddsNothingToList_GivenNoOrderExpression() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.OrderExpressions.Should().BeEmpty(); - } + spec.OrderExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsNothingToList_GivenOrderExpressionWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void AddsNothingToList_GivenOrderExpressionWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.OrderExpressions.Should().BeEmpty(); - } + spec.OrderExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsOrderExpressionToListWithOrderByDescendingType_GivenOrderByDescendingExpression() - { - var spec = new StoresOrderedDescendingByNameSpec(); + [Fact] + public void AddsOrderExpressionToListWithOrderByDescendingType_GivenOrderByDescendingExpression() + { + var spec = new StoresOrderedDescendingByNameSpec(); - spec.OrderExpressions.Should().ContainSingle(); - spec.OrderExpressions.Single().OrderType.Should().Be(OrderTypeEnum.OrderByDescending); - } + spec.OrderExpressions.Should().ContainSingle(); + spec.OrderExpressions.Single().OrderType.Should().Be(OrderTypeEnum.OrderByDescending); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_PostProcessingAction.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_PostProcessingAction.cs index 1f082abc..c4f22b0a 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_PostProcessingAction.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_PostProcessingAction.cs @@ -1,46 +1,46 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class SpecificationBuilderExtensions_PostProcessingAction + public class SpecificationBuilderExtensions_PostProcessingAction + { + [Fact] + public void SetsNothing_GivenNoPostProcessingAction() { - [Fact] - public void SetsNothing_GivenNoPostProcessingAction() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.PostProcessingAction.Should().BeNull(); - } + spec.PostProcessingAction.Should().BeNull(); + } - [Fact] - public void SetsNothing_GivenSelectorSpecWithNoPostProcessingAction() - { - var spec = new StoreNamesEmptySpec(); + [Fact] + public void SetsNothing_GivenSelectorSpecWithNoPostProcessingAction() + { + var spec = new StoreNamesEmptySpec(); - spec.PostProcessingAction.Should().BeNull(); - } + spec.PostProcessingAction.Should().BeNull(); + } - [Fact] - public void SetsPostProcessingPredicate_GivenPostProcessingAction() - { - var spec = new StoreWithPostProcessingActionSpec(); + [Fact] + public void SetsPostProcessingPredicate_GivenPostProcessingAction() + { + var spec = new StoreWithPostProcessingActionSpec(); - spec.PostProcessingAction.Should().NotBeNull(); - } + spec.PostProcessingAction.Should().NotBeNull(); + } - [Fact] - public void SetsPostProcessingPredicate_GivenSelectorSpecWithPostProcessingAction() - { - var spec = new StoreNamesWithPostProcessingActionSpec(); + [Fact] + public void SetsPostProcessingPredicate_GivenSelectorSpecWithPostProcessingAction() + { + var spec = new StoreNamesWithPostProcessingActionSpec(); - spec.PostProcessingAction.Should().NotBeNull(); - } + spec.PostProcessingAction.Should().NotBeNull(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Search.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Search.cs index 7c879960..be6a3492 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Search.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Search.cs @@ -1,65 +1,65 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class SpecificationBuilderExtensions_Search + public class SpecificationBuilderExtensions_Search + { + [Fact] + public void AddsNothingToList_GivenNoWhereExpression() { - [Fact] - public void AddsNothingToList_GivenNoWhereExpression() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.SearchCriterias.Should().BeEmpty(); - } + spec.SearchCriterias.Should().BeEmpty(); + } - [Fact] - public void AddsNothingToList_GivenSearchExpressionWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void AddsNothingToList_GivenSearchExpressionWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.SearchCriterias.Should().BeEmpty(); - } + spec.SearchCriterias.Should().BeEmpty(); + } - [Fact] - public void AddsOneCriteriaWithDefaultGroupToList_GivenOneSearchExpressionWithNoGroup() - { - var spec = new StoreSearchByNameSpec("test"); + [Fact] + public void AddsOneCriteriaWithDefaultGroupToList_GivenOneSearchExpressionWithNoGroup() + { + var spec = new StoreSearchByNameSpec("test"); - spec.SearchCriterias.Should().ContainSingle(); - spec.SearchCriterias.Single().SearchTerm.Should().Be("%test%"); - spec.SearchCriterias.Single().SearchGroup.Should().Be(1); - } + spec.SearchCriterias.Should().ContainSingle(); + spec.SearchCriterias.Single().SearchTerm.Should().Be("%test%"); + spec.SearchCriterias.Single().SearchGroup.Should().Be(1); + } - [Fact] - public void AddsTwoCriteriaWithSameGroupToList_GivenTwoSearchExpressionWithNoGroup() - { - var spec = new StoreSearchByNameOrCitySpec("test"); + [Fact] + public void AddsTwoCriteriaWithSameGroupToList_GivenTwoSearchExpressionWithNoGroup() + { + var spec = new StoreSearchByNameOrCitySpec("test"); - var criterias = spec.SearchCriterias.ToList(); + var criterias = spec.SearchCriterias.ToList(); - criterias.Should().HaveCount(2); - criterias.ForEach(x => x.SearchTerm.Should().Be("%test%")); - criterias.ForEach(x => x.SearchGroup.Should().Be(1)); - } + criterias.Should().HaveCount(2); + criterias.ForEach(x => x.SearchTerm.Should().Be("%test%")); + criterias.ForEach(x => x.SearchGroup.Should().Be(1)); + } - [Fact] - public void AddsTwoCriteriaWithDifferentGroupToList_GivenTwoSearchExpressionWithDistinctGroup() - { - var spec = new StoreSearchByNameAndCitySpec("test"); + [Fact] + public void AddsTwoCriteriaWithDifferentGroupToList_GivenTwoSearchExpressionWithDistinctGroup() + { + var spec = new StoreSearchByNameAndCitySpec("test"); - var criterias = spec.SearchCriterias.ToList(); + var criterias = spec.SearchCriterias.ToList(); - criterias.Should().HaveCount(2); - criterias.ForEach(x => x.SearchTerm.Should().Be("%test%")); - criterias[0].SearchGroup.Should().Be(1); - criterias[1].SearchGroup.Should().Be(2); - } + criterias.Should().HaveCount(2); + criterias.ForEach(x => x.SearchTerm.Should().Be("%test%")); + criterias[0].SearchGroup.Should().Be(1); + criterias[1].SearchGroup.Should().Be(2); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Select.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Select.cs index c2ceb922..b23e3028 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Select.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Select.cs @@ -1,30 +1,30 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class SpecificationBuilderExtensions_Select + public class SpecificationBuilderExtensions_Select + { + [Fact] + public void SetsNothing_GivenNoSelectExpression() { - [Fact] - public void SetsNothing_GivenNoSelectExpression() - { - var spec = new StoreNamesEmptySpec(); + var spec = new StoreNamesEmptySpec(); - spec.Selector.Should().BeNull(); - } + spec.Selector.Should().BeNull(); + } - [Fact] - public void SetsSelector_GivenSelectExpression() - { - var spec = new StoreNamesSpec(); + [Fact] + public void SetsSelector_GivenSelectExpression() + { + var spec = new StoreNamesSpec(); - spec.Selector.Should().NotBeNull(); - } + spec.Selector.Should().NotBeNull(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Skip.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Skip.cs index 2b990e1b..9a1ceea4 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Skip.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Skip.cs @@ -1,41 +1,39 @@ using System; - -using Xunit; -using FluentAssertions; - using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; +using Xunit; namespace Ardalis.Specification.UnitTests { - public class SpecificationBuilderExtensions_Skip + public class SpecificationBuilderExtensions_Skip + { + [Fact] + public void SetsSkipProperty_GivenValue() { - [Fact] - public void SetsSkipProperty_GivenValue() - { - var skip = 1; + var skip = 1; - var spec = new StoreNamesPaginatedSpec(skip, 10); + var spec = new StoreNamesPaginatedSpec(skip, 10); - spec.Skip.Should() - .Be(skip); - } + spec.Skip.Should() + .Be(skip); + } - [Fact] - public void DoesNothing_GivenSkipWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void DoesNothing_GivenSkipWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.Skip.Should().BeNull(); - } + spec.Skip.Should().BeNull(); + } - [Fact] - public void ThrowsDuplicateSkipException_GivenSkipUsedMoreThanOnce() - { - Action sutAction = () => new StoreDuplicateSkipSpec(); + [Fact] + public void ThrowsDuplicateSkipException_GivenSkipUsedMoreThanOnce() + { + Action sutAction = () => new StoreDuplicateSkipSpec(); - sutAction.Should() - .Throw() - .WithMessage("Duplicate use of Skip(). Ensure you don't use Skip() more than once in the same specification!"); - } + sutAction.Should() + .Throw() + .WithMessage("Duplicate use of Skip(). Ensure you don't use Skip() more than once in the same specification!"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Take.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Take.cs index 4b02d4a7..4e238011 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Take.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Take.cs @@ -1,39 +1,37 @@ using System; - -using Xunit; -using FluentAssertions; - using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; +using Xunit; namespace Ardalis.Specification.UnitTests { - public class SpecificationBuilderExtensions_Take + public class SpecificationBuilderExtensions_Take + { + [Fact] + public void SetsTakeProperty_GivenValue() { - [Fact] - public void SetsTakeProperty_GivenValue() - { - var take = 10; - var spec = new StoreNamesPaginatedSpec(0, take); + var take = 10; + var spec = new StoreNamesPaginatedSpec(0, take); - spec.Take.Should().Be(take); - } + spec.Take.Should().Be(take); + } - [Fact] - public void DoesNothing_GivenTakeWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void DoesNothing_GivenTakeWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.Take.Should().BeNull(); - } + spec.Take.Should().BeNull(); + } - [Fact] - public void ThrowsDuplicateTakeException_GivenTakeUsedMoreThanOnce() - { - Action sutAction = () => new StoreDuplicateTakeSpec(); + [Fact] + public void ThrowsDuplicateTakeException_GivenTakeUsedMoreThanOnce() + { + Action sutAction = () => new StoreDuplicateTakeSpec(); - sutAction.Should() - .Throw() - .WithMessage("Duplicate use of Take(). Ensure you don't use Take() more than once in the same specification!"); - } + sutAction.Should() + .Throw() + .WithMessage("Duplicate use of Take(). Ensure you don't use Take() more than once in the same specification!"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Where.cs b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Where.cs index 286e712f..97f3c64c 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Where.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_Where.cs @@ -1,46 +1,46 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class SpecificationBuilderExtensions_Where + public class SpecificationBuilderExtensions_Where + { + [Fact] + public void AddsNothingToList_GivenNoWhereExpression() { - [Fact] - public void AddsNothingToList_GivenNoWhereExpression() - { - var spec = new StoreEmptySpec(); + var spec = new StoreEmptySpec(); - spec.WhereExpressions.Should().BeEmpty(); - } + spec.WhereExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsNothingToList_GivenWhereExpressionWithFalseCondition() - { - var spec = new CompanyByIdWithFalseConditions(1); + [Fact] + public void AddsNothingToList_GivenWhereExpressionWithFalseCondition() + { + var spec = new CompanyByIdWithFalseConditions(1); - spec.WhereExpressions.Should().BeEmpty(); - } + spec.WhereExpressions.Should().BeEmpty(); + } - [Fact] - public void AddsOneExpressionToList_GivenOneWhereExpression() - { - var spec = new StoreByIdSpec(1); + [Fact] + public void AddsOneExpressionToList_GivenOneWhereExpression() + { + var spec = new StoreByIdSpec(1); - spec.WhereExpressions.Should().ContainSingle(); - } + spec.WhereExpressions.Should().ContainSingle(); + } - [Fact] - public void AddsTwoExpressionsToList_GivenTwoWhereExpressions() - { - var spec = new StoreByIdAndNameSpec(1, "name"); + [Fact] + public void AddsTwoExpressionsToList_GivenTwoWhereExpressions() + { + var spec = new StoreByIdAndNameSpec(1, "name"); - spec.WhereExpressions.Should().HaveCount(2); - } + spec.WhereExpressions.Should().HaveCount(2); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/InMemorySpecificationEvaluatorTests.cs b/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/InMemorySpecificationEvaluatorTests.cs index 321247f9..e518f0fe 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/InMemorySpecificationEvaluatorTests.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/InMemorySpecificationEvaluatorTests.cs @@ -1,156 +1,156 @@ -using FluentAssertions; -using Ardalis.Specification.UnitTests.Fixture; -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Ardalis.Specification.UnitTests.Fixture; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class InMemorySpecificationEvaluatorTests + public class InMemorySpecificationEvaluatorTests + { + [Fact] + public void ReturnsStoreWithId10_GivenStoreByIdSpec() { - [Fact] - public void ReturnsStoreWithId10_GivenStoreByIdSpec() - { - var spec = new StoreByIdSpec(10); + var spec = new StoreByIdSpec(10); - var store = spec.Evaluate(StoreSeed.Get()).FirstOrDefault(); + var store = spec.Evaluate(StoreSeed.Get()).FirstOrDefault(); - store?.Id.Should().Be(10); - } + store?.Id.Should().Be(10); + } - [Fact] - public void ReturnsStoreWithIdFrom15To30_GivenStoresByIdListSpec() - { - var ids = Enumerable.Range(15, 16); - var spec = new StoresByIdListSpec(ids); + [Fact] + public void ReturnsStoreWithIdFrom15To30_GivenStoresByIdListSpec() + { + var ids = Enumerable.Range(15, 16); + var spec = new StoresByIdListSpec(ids); - var stores = spec.Evaluate(StoreSeed.Get()); + var stores = spec.Evaluate(StoreSeed.Get()); - stores.Count().Should().Be(16); - stores.OrderBy(x => x.Id).First().Id.Should().Be(15); - stores.OrderBy(x => x.Id).Last().Id.Should().Be(30); - } + stores.Count().Should().Be(16); + stores.OrderBy(x => x.Id).First().Id.Should().Be(15); + stores.OrderBy(x => x.Id).Last().Id.Should().Be(30); + } - [Fact] - public void ReturnsSecondPageOfStoreNames_GivenStoreNamesPaginatedSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 + [Fact] + public void ReturnsSecondPageOfStoreNames_GivenStoreNamesPaginatedSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 - var spec = new StoreNamesPaginatedSpec(skip, take); + var spec = new StoreNamesPaginatedSpec(skip, take); - var storeNames = spec.Evaluate(StoreSeed.Get()); + var storeNames = spec.Evaluate(StoreSeed.Get()); - storeNames.Count().Should().Be(take); - storeNames.First().Should().Be("Store 11"); - storeNames.Last().Should().Be("Store 20"); - } + storeNames.Count().Should().Be(take); + storeNames.First().Should().Be("Store 11"); + storeNames.Last().Should().Be("Store 20"); + } - [Fact] - public void ReturnsSecondPageOfStores_GivenStoresPaginatedSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 + [Fact] + public void ReturnsSecondPageOfStores_GivenStoresPaginatedSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 - var spec = new StoresPaginatedSpec(skip, take); + var spec = new StoresPaginatedSpec(skip, take); - var stores = spec.Evaluate(StoreSeed.Get()); + var stores = spec.Evaluate(StoreSeed.Get()); - stores.Count().Should().Be(take); - stores.OrderBy(x => x.Id).First().Id.Should().Be(11); - stores.OrderBy(x => x.Id).Last().Id.Should().Be(20); - } + stores.Count().Should().Be(take); + stores.OrderBy(x => x.Id).First().Id.Should().Be(11); + stores.OrderBy(x => x.Id).Last().Id.Should().Be(20); + } - [Fact] - public void ReturnsOrderStoresByNameDescForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameSpec() - { - var spec = new StoresByCompanyOrderedDescByNameSpec(2); + [Fact] + public void ReturnsOrderStoresByNameDescForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameSpec() + { + var spec = new StoresByCompanyOrderedDescByNameSpec(2); - var stores = spec.Evaluate(StoreSeed.Get()); + var stores = spec.Evaluate(StoreSeed.Get()); - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_LAST_ID); - } + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_LAST_ID); + } - [Fact] - public void ReturnsOrderStoresByNameDescThenByIdForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameThenByIdSpec() - { - var spec = new StoresByCompanyOrderedDescByNameThenByIdSpec(2); + [Fact] + public void ReturnsOrderStoresByNameDescThenByIdForCompanyWithId2_GivenStoresByCompanyOrderedDescByNameThenByIdSpec() + { + var spec = new StoresByCompanyOrderedDescByNameThenByIdSpec(2); - var stores = spec.Evaluate(StoreSeed.Get()); + var stores = spec.Evaluate(StoreSeed.Get()); - stores.First().Id.Should().Be(99); - stores.Last().Id.Should().Be(98); - } + stores.First().Id.Should().Be(99); + stores.Last().Id.Should().Be(98); + } - [Fact] - public void ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedOrderedDescByNameSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 + [Fact] + public void ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedOrderedDescByNameSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 - var spec = new StoresByCompanyPaginatedOrderedDescByNameSpec(2, skip, take); + var spec = new StoresByCompanyPaginatedOrderedDescByNameSpec(2, skip, take); - var stores = spec.Evaluate(StoreSeed.Get()); + var stores = spec.Evaluate(StoreSeed.Get()); - stores.Count().Should().Be(take); - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_LAST_ID); - } + stores.Count().Should().Be(take); + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_LAST_ID); + } - [Fact] - public void ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedSpec() - { - int take = 10; // pagesize 10 - int skip = (2 - 1) * 10; // page 2 + [Fact] + public void ReturnsSecondPageOfStoresForCompanyWithId2_GivenStoresByCompanyPaginatedSpec() + { + int take = 10; // pagesize 10 + int skip = (2 - 1) * 10; // page 2 - var spec = new StoresByCompanyPaginatedSpec(2, skip, take); + var spec = new StoresByCompanyPaginatedSpec(2, skip, take); - var stores = spec.Evaluate(StoreSeed.Get()); + var stores = spec.Evaluate(StoreSeed.Get()); - stores.Count().Should().Be(take); - stores.OrderBy(x => x.Id).First().Id.Should().Be(61); - stores.OrderBy(x => x.Id).Last().Id.Should().Be(70); - } + stores.Count().Should().Be(take); + stores.OrderBy(x => x.Id).First().Id.Should().Be(61); + stores.OrderBy(x => x.Id).Last().Id.Should().Be(70); + } - [Fact] - public void ReturnsOrderedStores_GivenStoresOrderedSpecByName() - { - var spec = new StoresOrderedSpecByName(); + [Fact] + public void ReturnsOrderedStores_GivenStoresOrderedSpecByName() + { + var spec = new StoresOrderedSpecByName(); - var stores = spec.Evaluate(StoreSeed.Get()); + var stores = spec.Evaluate(StoreSeed.Get()); - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_LAST_ID); - } + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_LAST_ID); + } - [Fact] - public void ReturnsOrderedStores_GivenStoresOrderedDescendingByNameSpec() - { - var spec = new StoresOrderedDescendingByNameSpec(); + [Fact] + public void ReturnsOrderedStores_GivenStoresOrderedDescendingByNameSpec() + { + var spec = new StoresOrderedDescendingByNameSpec(); - var stores = spec.Evaluate(StoreSeed.Get()); + var stores = spec.Evaluate(StoreSeed.Get()); - stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FIRST_ID); - stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_LAST_ID); - } + stores.First().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_FIRST_ID); + stores.Last().Id.Should().Be(StoreSeed.ORDERED_BY_NAME_DESC_LAST_ID); + } - [Fact] - public void ThrowsDuplicateOrderChainException_GivenSpecWithMultipleOrderChains() - { - var spec = new StoresOrderedTwoChainsSpec(); + [Fact] + public void ThrowsDuplicateOrderChainException_GivenSpecWithMultipleOrderChains() + { + var spec = new StoresOrderedTwoChainsSpec(); - Action sutAction = () => spec.Evaluate(StoreSeed.Get()); + Action sutAction = () => spec.Evaluate(StoreSeed.Get()); - sutAction.Should() - .Throw() - .WithMessage("The specification contains more than one Order chain!"); - } + sutAction.Should() + .Throw() + .WithMessage("The specification contains more than one Order chain!"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/SearchEvaluator_Evaluate.cs b/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/SearchEvaluator_Evaluate.cs index 22f8f5af..9760fc22 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/SearchEvaluator_Evaluate.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/SearchEvaluator_Evaluate.cs @@ -1,16 +1,16 @@ -using FluentAssertions; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class SearchEvaluator_Evaluate - { - public static List Data = new List + public class SearchEvaluator_Evaluate + { + public static List Data = new List { new Person("James"), new Person("Robert"), @@ -20,36 +20,36 @@ public class SearchEvaluator_Evaluate new Person("David"), }; - [Theory] - [InlineData("%mes", 1)] - [InlineData("%r%", 2)] - [InlineData("_inda", 1)] - [InlineData("M%", 2)] - [InlineData("[RM]%", 3)] - [InlineData("_[IA]%", 5)] - public void ReturnsFilteredList_GivenSearchExpression(string searchTerm, int expectedCount) - { - var result = SearchEvaluator.Instance.Evaluate(Data, new PersonSpecification(searchTerm)); + [Theory] + [InlineData("%mes", 1)] + [InlineData("%r%", 2)] + [InlineData("_inda", 1)] + [InlineData("M%", 2)] + [InlineData("[RM]%", 3)] + [InlineData("_[IA]%", 5)] + public void ReturnsFilteredList_GivenSearchExpression(string searchTerm, int expectedCount) + { + var result = SearchEvaluator.Instance.Evaluate(Data, new PersonSpecification(searchTerm)); - result.Should().HaveCount(expectedCount); - } + result.Should().HaveCount(expectedCount); } + } - public class PersonSpecification : Specification + public class PersonSpecification : Specification + { + public PersonSpecification(string searchTerm) { - public PersonSpecification(string searchTerm) - { - Query.Search(x => x.Name, searchTerm); - } + Query.Search(x => x.Name, searchTerm); } + } - public class Person - { - public string Name { get; } + public class Person + { + public string Name { get; } - public Person(string name) - { - Name = name; - } + public Person(string name) + { + Name = name; } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/SearchExtension_Like.cs b/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/SearchExtension_Like.cs index bda48430..137389d7 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/SearchExtension_Like.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/EvaluatorTests/SearchExtension_Like.cs @@ -1,98 +1,98 @@ -using FluentAssertions; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests.EvaluatorTests { - public class SearchExtension_Like + public class SearchExtension_Like + { + [Theory] + [InlineData(true, "%", "")] + [InlineData(true, "%", " ")] + [InlineData(true, "%", "asdfa asdf asdf")] + [InlineData(true, "%", "%")] + [InlineData(false, "_", "")] + [InlineData(true, "_", " ")] + [InlineData(true, "_", "4")] + [InlineData(true, "_", "C")] + [InlineData(true, "_", "c")] + [InlineData(false, "_", "CX")] + [InlineData(false, "_", "cx")] + [InlineData(true, "[A]", "a")] + [InlineData(false, "[A]", "ab")] + [InlineData(false, "[ABCD]", "")] + [InlineData(true, "[ABCD]", "A")] + [InlineData(true, "[ABCD]", "b")] + [InlineData(false, "[ABCD]", "X")] + [InlineData(false, "[ABCD]", "AB")] + [InlineData(true, "[B-D]", "C")] + [InlineData(true, "[B-D]", "D")] + [InlineData(false, "[B-D]", "A")] + [InlineData(false, "[^B-D]", "C")] + [InlineData(false, "[^B-D]", "D")] + [InlineData(true, "[^B-D)]", "A")] + [InlineData(true, "%TEST[ABCD]XXX", "lolTESTBXXX")] + [InlineData(false, "%TEST[ABCD]XXX", "lolTESTZXXX")] + [InlineData(false, "%TEST[^ABCD]XXX", "lolTESTBXXX")] + [InlineData(true, "%TEST[^ABCD]XXX", "lolTESTZXXX")] + [InlineData(true, "%TEST[B-D]XXX", "lolTESTBXXX")] + [InlineData(true, "%TEST[^B-D)]XXX", "lolTESTZXXX")] + [InlineData(true, "%Stuff.txt", "Stuff.txt")] + [InlineData(true, "%Stuff.txt", "MagicStuff.txt")] + [InlineData(false, "%Stuff.txt", "MagicStuff.txt.img")] + [InlineData(false, "%Stuff.txt", "Stuff.txt.img")] + [InlineData(false, "%Stuff.txt", "MagicStuff001.txt.img")] + [InlineData(true, "Stuff.txt%", "Stuff.txt")] + [InlineData(false, "Stuff.txt%", "MagicStuff.txt")] + [InlineData(false, "Stuff.txt%", "MagicStuff.txt.img")] + [InlineData(true, "Stuff.txt%", "Stuff.txt.img")] + [InlineData(false, "Stuff.txt%", "MagicStuff001.txt.img")] + [InlineData(true, "%Stuff.txt%", "Stuff.txt")] + [InlineData(true, "%Stuff.txt%", "MagicStuff.txt")] + [InlineData(true, "%Stuff.txt%", "MagicStuff.txt.img")] + [InlineData(true, "%Stuff.txt%", "Stuff.txt.img")] + [InlineData(false, "%Stuff.txt%", "MagicStuff001.txt.img")] + [InlineData(true, "%Stuff%.txt", "Stuff.txt")] + [InlineData(true, "%Stuff%.txt", "MagicStuff.txt")] + [InlineData(false, "%Stuff%.txt", "MagicStuff.txt.img")] + [InlineData(false, "%Stuff%.txt", "Stuff.txt.img")] + [InlineData(false, "%Stuff%.txt", "MagicStuff001.txt.img")] + [InlineData(true, "%Stuff%.txt", "MagicStuff001.txt")] + [InlineData(true, "Stuff%.txt%", "Stuff.txt")] + [InlineData(false, "Stuff%.txt%", "MagicStuff.txt")] + [InlineData(false, "Stuff%.txt%", "MagicStuff.txt.img")] + [InlineData(true, "Stuff%.txt%", "Stuff.txt.img")] + [InlineData(false, "Stuff%.txt%", "MagicStuff001.txt.img")] + [InlineData(false, "Stuff%.txt%", "MagicStuff001.txt")] + [InlineData(true, "%Stuff%.txt%", "Stuff.txt")] + [InlineData(true, "%Stuff%.txt%", "MagicStuff.txt")] + [InlineData(true, "%Stuff%.txt%", "MagicStuff.txt.img")] + [InlineData(true, "%Stuff%.txt%", "Stuff.txt.img")] + [InlineData(true, "%Stuff%.txt%", "MagicStuff001.txt.img")] + [InlineData(true, "%Stuff%.txt%", "MagicStuff001.txt")] + [InlineData(true, "_Stuff_.txt_", "1Stuff3.txt4")] + [InlineData(false, "_Stuff_.txt_", "1Stuff.txt4")] + [InlineData(false, "_Stuff_.txt_", "1Stuff3.txt")] + [InlineData(false, "_Stuff_.txt_", "Stuff3.txt4")] + public void ReturnsExpectedResult_GivenPatternAndInput(bool expectedResult, string pattern, string input) { - [Theory] - [InlineData(true, "%", "")] - [InlineData(true, "%", " ")] - [InlineData(true, "%", "asdfa asdf asdf")] - [InlineData(true, "%", "%")] - [InlineData(false, "_", "")] - [InlineData(true, "_", " ")] - [InlineData(true, "_", "4")] - [InlineData(true, "_", "C")] - [InlineData(true, "_", "c")] - [InlineData(false, "_", "CX")] - [InlineData(false, "_", "cx")] - [InlineData(true, "[A]", "a")] - [InlineData(false, "[A]", "ab")] - [InlineData(false, "[ABCD]", "")] - [InlineData(true, "[ABCD]", "A")] - [InlineData(true, "[ABCD]", "b")] - [InlineData(false, "[ABCD]", "X")] - [InlineData(false, "[ABCD]", "AB")] - [InlineData(true, "[B-D]", "C")] - [InlineData(true, "[B-D]", "D")] - [InlineData(false, "[B-D]", "A")] - [InlineData(false, "[^B-D]", "C")] - [InlineData(false, "[^B-D]", "D")] - [InlineData(true, "[^B-D)]", "A")] - [InlineData(true, "%TEST[ABCD]XXX", "lolTESTBXXX")] - [InlineData(false, "%TEST[ABCD]XXX", "lolTESTZXXX")] - [InlineData(false, "%TEST[^ABCD]XXX", "lolTESTBXXX")] - [InlineData(true, "%TEST[^ABCD]XXX", "lolTESTZXXX")] - [InlineData(true, "%TEST[B-D]XXX", "lolTESTBXXX")] - [InlineData(true, "%TEST[^B-D)]XXX", "lolTESTZXXX")] - [InlineData(true, "%Stuff.txt", "Stuff.txt")] - [InlineData(true, "%Stuff.txt", "MagicStuff.txt")] - [InlineData(false, "%Stuff.txt", "MagicStuff.txt.img")] - [InlineData(false, "%Stuff.txt", "Stuff.txt.img")] - [InlineData(false, "%Stuff.txt", "MagicStuff001.txt.img")] - [InlineData(true, "Stuff.txt%", "Stuff.txt")] - [InlineData(false, "Stuff.txt%", "MagicStuff.txt")] - [InlineData(false, "Stuff.txt%", "MagicStuff.txt.img")] - [InlineData(true, "Stuff.txt%", "Stuff.txt.img")] - [InlineData(false, "Stuff.txt%", "MagicStuff001.txt.img")] - [InlineData(true, "%Stuff.txt%", "Stuff.txt")] - [InlineData(true, "%Stuff.txt%", "MagicStuff.txt")] - [InlineData(true, "%Stuff.txt%", "MagicStuff.txt.img")] - [InlineData(true, "%Stuff.txt%", "Stuff.txt.img")] - [InlineData(false, "%Stuff.txt%", "MagicStuff001.txt.img")] - [InlineData(true, "%Stuff%.txt", "Stuff.txt")] - [InlineData(true, "%Stuff%.txt", "MagicStuff.txt")] - [InlineData(false, "%Stuff%.txt", "MagicStuff.txt.img")] - [InlineData(false, "%Stuff%.txt", "Stuff.txt.img")] - [InlineData(false, "%Stuff%.txt", "MagicStuff001.txt.img")] - [InlineData(true, "%Stuff%.txt", "MagicStuff001.txt")] - [InlineData(true, "Stuff%.txt%", "Stuff.txt")] - [InlineData(false, "Stuff%.txt%", "MagicStuff.txt")] - [InlineData(false, "Stuff%.txt%", "MagicStuff.txt.img")] - [InlineData(true, "Stuff%.txt%", "Stuff.txt.img")] - [InlineData(false, "Stuff%.txt%", "MagicStuff001.txt.img")] - [InlineData(false, "Stuff%.txt%", "MagicStuff001.txt")] - [InlineData(true, "%Stuff%.txt%", "Stuff.txt")] - [InlineData(true, "%Stuff%.txt%", "MagicStuff.txt")] - [InlineData(true, "%Stuff%.txt%", "MagicStuff.txt.img")] - [InlineData(true, "%Stuff%.txt%", "Stuff.txt.img")] - [InlineData(true, "%Stuff%.txt%", "MagicStuff001.txt.img")] - [InlineData(true, "%Stuff%.txt%", "MagicStuff001.txt")] - [InlineData(true, "_Stuff_.txt_", "1Stuff3.txt4")] - [InlineData(false, "_Stuff_.txt_", "1Stuff.txt4")] - [InlineData(false, "_Stuff_.txt_", "1Stuff3.txt")] - [InlineData(false, "_Stuff_.txt_", "Stuff3.txt4")] - public void ReturnsExpectedResult_GivenPatternAndInput(bool expectedResult, string pattern, string input) - { - var result = input.Like(pattern); + var result = input.Like(pattern); - result.Should().Be(expectedResult); - } + result.Should().Be(expectedResult); + } - [Theory] - [InlineData("[", "asd")] - [InlineData("[]", "asd")] - public void ShouldThrowInvalidSearchPattern_GivenInvalidPattern(string pattern, string input) - { - Action action = () => input.Like(pattern); + [Theory] + [InlineData("[", "asd")] + [InlineData("[]", "asd")] + public void ShouldThrowInvalidSearchPattern_GivenInvalidPattern(string pattern, string input) + { + Action action = () => input.Like(pattern); - action.Should().Throw().WithMessage($"Invalid search pattern: {pattern}"); - } + action.Should().Throw().WithMessage($"Invalid search pattern: {pattern}"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateOrderChainExceptionTests.cs b/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateOrderChainExceptionTests.cs index d6e113c4..ef5a30d3 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateOrderChainExceptionTests.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateOrderChainExceptionTests.cs @@ -1,30 +1,30 @@ -using FluentAssertions; -using System; +using System; using System.Collections.Generic; using System.Text; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class DuplicateOrderChainExceptionTests - { - private const string defaultMessage = "The specification contains more than one Order chain!"; + public class DuplicateOrderChainExceptionTests + { + private const string defaultMessage = "The specification contains more than one Order chain!"; - [Fact] - public void ThrowWithDefaultConstructor() - { - Action action = () => throw new DuplicateOrderChainException(); + [Fact] + public void ThrowWithDefaultConstructor() + { + Action action = () => throw new DuplicateOrderChainException(); - action.Should().Throw().WithMessage(defaultMessage); - } + action.Should().Throw().WithMessage(defaultMessage); + } - [Fact] - public void ThrowWithInnerException() - { - Exception inner = new Exception("test"); - Action action = () => throw new DuplicateOrderChainException(inner); + [Fact] + public void ThrowWithInnerException() + { + Exception inner = new Exception("test"); + Action action = () => throw new DuplicateOrderChainException(inner); - action.Should().Throw().WithMessage(defaultMessage).WithInnerException().WithMessage("test"); - } + action.Should().Throw().WithMessage(defaultMessage).WithInnerException().WithMessage("test"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateSkipExceptionTests.cs b/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateSkipExceptionTests.cs index edee0301..6d3f4c95 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateSkipExceptionTests.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateSkipExceptionTests.cs @@ -1,30 +1,30 @@ -using FluentAssertions; -using System; +using System; using System.Collections.Generic; using System.Text; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class DuplicateSkipExceptionTests - { - private const string defaultMessage = "Duplicate use of Skip(). Ensure you don't use Skip() more than once in the same specification!"; + public class DuplicateSkipExceptionTests + { + private const string defaultMessage = "Duplicate use of Skip(). Ensure you don't use Skip() more than once in the same specification!"; - [Fact] - public void ThrowWithDefaultConstructor() - { - Action action = () => throw new DuplicateSkipException(); + [Fact] + public void ThrowWithDefaultConstructor() + { + Action action = () => throw new DuplicateSkipException(); - action.Should().Throw().WithMessage(defaultMessage); - } + action.Should().Throw().WithMessage(defaultMessage); + } - [Fact] - public void ThrowWithInnerException() - { - Exception inner = new Exception("test"); - Action action = () => throw new DuplicateSkipException(inner); + [Fact] + public void ThrowWithInnerException() + { + Exception inner = new Exception("test"); + Action action = () => throw new DuplicateSkipException(inner); - action.Should().Throw().WithMessage(defaultMessage).WithInnerException().WithMessage("test"); - } + action.Should().Throw().WithMessage(defaultMessage).WithInnerException().WithMessage("test"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateTakeExceptionTests.cs b/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateTakeExceptionTests.cs index b8a2e249..147646c8 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateTakeExceptionTests.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/DuplicateTakeExceptionTests.cs @@ -1,30 +1,30 @@ -using FluentAssertions; -using System; +using System; using System.Collections.Generic; using System.Text; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class DuplicateTakeExceptionTests - { - private const string defaultMessage = "Duplicate use of Take(). Ensure you don't use Take() more than once in the same specification!"; + public class DuplicateTakeExceptionTests + { + private const string defaultMessage = "Duplicate use of Take(). Ensure you don't use Take() more than once in the same specification!"; - [Fact] - public void ThrowWithDefaultConstructor() - { - Action action = () => throw new DuplicateTakeException(); + [Fact] + public void ThrowWithDefaultConstructor() + { + Action action = () => throw new DuplicateTakeException(); - action.Should().Throw().WithMessage(defaultMessage); - } + action.Should().Throw().WithMessage(defaultMessage); + } - [Fact] - public void ThrowWithInnerException() - { - Exception inner = new Exception("test"); - Action action = () => throw new DuplicateTakeException(inner); + [Fact] + public void ThrowWithInnerException() + { + Exception inner = new Exception("test"); + Action action = () => throw new DuplicateTakeException(inner); - action.Should().Throw().WithMessage(defaultMessage).WithInnerException().WithMessage("test"); - } + action.Should().Throw().WithMessage(defaultMessage).WithInnerException().WithMessage("test"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/InvalidSearchPatternExceptionTests.cs b/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/InvalidSearchPatternExceptionTests.cs index a00003d4..3c0fa1ff 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/InvalidSearchPatternExceptionTests.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/InvalidSearchPatternExceptionTests.cs @@ -1,31 +1,31 @@ -using FluentAssertions; -using System; +using System; using System.Collections.Generic; using System.Text; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class InvalidSearchPatternExceptionTests - { - private const string defaultMessage = "Invalid search pattern: " + pattern; - private const string pattern = "x"; + public class InvalidSearchPatternExceptionTests + { + private const string defaultMessage = "Invalid search pattern: " + pattern; + private const string pattern = "x"; - [Fact] - public void ThrowWithDefaultConstructor() - { - Action action = () => throw new InvalidSearchPatternException(pattern); + [Fact] + public void ThrowWithDefaultConstructor() + { + Action action = () => throw new InvalidSearchPatternException(pattern); - action.Should().Throw(pattern).WithMessage(defaultMessage); - } + action.Should().Throw(pattern).WithMessage(defaultMessage); + } - [Fact] - public void ThrowWithInnerException() - { - Exception inner = new Exception("test"); - Action action = () => throw new InvalidSearchPatternException(pattern, inner); + [Fact] + public void ThrowWithInnerException() + { + Exception inner = new Exception("test"); + Action action = () => throw new InvalidSearchPatternException(pattern, inner); - action.Should().Throw(pattern).WithMessage(defaultMessage).WithInnerException().WithMessage("test"); - } + action.Should().Throw(pattern).WithMessage(defaultMessage).WithInnerException().WithMessage("test"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/SelectorNotFoundExceptionTests.cs b/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/SelectorNotFoundExceptionTests.cs index 713c5cb6..cbe92f96 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/SelectorNotFoundExceptionTests.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/ExceptionTests/SelectorNotFoundExceptionTests.cs @@ -1,30 +1,30 @@ -using FluentAssertions; -using System; +using System; using System.Collections.Generic; using System.Text; +using FluentAssertions; using Xunit; namespace Ardalis.Specification.UnitTests { - public class SelectorNotFoundExceptionTests - { - private const string defaultMessage = "The specification must have Selector defined."; + public class SelectorNotFoundExceptionTests + { + private const string defaultMessage = "The specification must have Selector defined."; - [Fact] - public void ThrowWithDefaultConstructor() - { - Action action = () => throw new SelectorNotFoundException(); + [Fact] + public void ThrowWithDefaultConstructor() + { + Action action = () => throw new SelectorNotFoundException(); - action.Should().Throw().WithMessage(defaultMessage); - } + action.Should().Throw().WithMessage(defaultMessage); + } - [Fact] - public void ThrowWithInnerException() - { - Exception inner = new Exception("test"); - Action action = () => throw new SelectorNotFoundException(inner); + [Fact] + public void ThrowWithInnerException() + { + Exception inner = new Exception("test"); + Action action = () => throw new SelectorNotFoundException(inner); - action.Should().Throw().WithMessage(defaultMessage).WithInnerException().WithMessage("test"); - } + action.Should().Throw().WithMessage(defaultMessage).WithInnerException().WithMessage("test"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Address.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Address.cs index b93f7b03..8018c28f 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Address.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Address.cs @@ -4,17 +4,17 @@ namespace Ardalis.Specification.UnitTests.Fixture.Entities { - public class Address - { - public int Id { get; set; } - public string? Street { get; set; } + public class Address + { + public int Id { get; set; } + public string? Street { get; set; } - public int StoreId { get; set; } - public Store? Store { get; set; } + public int StoreId { get; set; } + public Store? Store { get; set; } - public object GetSomethingFromAddress() - { - return new object(); - } + public object GetSomethingFromAddress() + { + return new object(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Company.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Company.cs index 1d7e17da..ac748568 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Company.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Company.cs @@ -4,14 +4,14 @@ namespace Ardalis.Specification.UnitTests.Fixture.Entities { - public class Company - { - public int Id { get; set; } - public string? Name { get; set; } + public class Company + { + public int Id { get; set; } + public string? Name { get; set; } - public int CountryId { get; set; } - public Country? Country { get; set; } + public int CountryId { get; set; } + public Country? Country { get; set; } - public List Stores { get; set; } = new List(); - } + public List Stores { get; set; } = new List(); + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Country.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Country.cs index 4d592c4a..6fb115e9 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Country.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Country.cs @@ -4,11 +4,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Entities { - public class Country - { - public int Id { get; set; } - public string? Name { get; set; } + public class Country + { + public int Id { get; set; } + public string? Name { get; set; } - public List Companies { get; set; } = new List(); - } + public List Companies { get; set; } = new List(); + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Product.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Product.cs index 438ad632..acda3ac9 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Product.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Product.cs @@ -4,12 +4,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Entities { - public class Product - { - public int Id { get; set; } - public string? Name { get; set; } + public class Product + { + public int Id { get; set; } + public string? Name { get; set; } - public int StoreId { get; set; } - public Store? Store { get; set; } - } + public int StoreId { get; set; } + public Store? Store { get; set; } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/AddressSeed.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/AddressSeed.cs index b85867b0..c82320ee 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/AddressSeed.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/AddressSeed.cs @@ -4,25 +4,25 @@ namespace Ardalis.Specification.UnitTests.Fixture.Entities.Seeds { - public class AddressSeed + public class AddressSeed + { + public const string VALID_STREET_FOR_STOREID1 = "Street 1"; + + public static List
Get() { - public const string VALID_STREET_FOR_STOREID1 = "Street 1"; + var addresses = new List
(); - public static List
Get() + for (int i = 1; i <= 100; i++) + { + addresses.Add(new Address() { - var addresses = new List
(); - - for (int i = 1; i <= 100; i++) - { - addresses.Add(new Address() - { - Id = i, - Street = $"Street {i}", - StoreId = i - }); - } + Id = i, + Street = $"Street {i}", + StoreId = i + }); + } - return addresses; - } + return addresses; } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/CompanySeed.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/CompanySeed.cs index 4b5feb8a..69a91eab 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/CompanySeed.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/CompanySeed.cs @@ -4,37 +4,37 @@ namespace Ardalis.Specification.UnitTests.Fixture.Entities.Seeds { - public class CompanySeed - { - public const int VALID_COMPANY_ID = 1; - public const string VALID_COMPANY_NAME = "Company 1"; + public class CompanySeed + { + public const int VALID_COMPANY_ID = 1; + public const string VALID_COMPANY_NAME = "Company 1"; - public static List Get() - { - var companies = new List(); + public static List Get() + { + var companies = new List(); - companies.Add(new Company() - { - Id = 1, - Name = "Company 1", - CountryId = 1, - }); + companies.Add(new Company() + { + Id = 1, + Name = "Company 1", + CountryId = 1, + }); - companies.Add(new Company() - { - Id = 2, - Name = "Company 2", - CountryId = 2, - }); + companies.Add(new Company() + { + Id = 2, + Name = "Company 2", + CountryId = 2, + }); - companies.Add(new Company() - { - Id = 3, - Name = "Company 3", - CountryId = 1, - }); + companies.Add(new Company() + { + Id = 3, + Name = "Company 3", + CountryId = 1, + }); - return companies; - } + return companies; } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/CountrySeed.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/CountrySeed.cs index 5228a551..aaf83868 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/CountrySeed.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/CountrySeed.cs @@ -4,25 +4,25 @@ namespace Ardalis.Specification.UnitTests.Fixture.Entities.Seeds { - public class CountrySeed + public class CountrySeed + { + public static List Get() { - public static List Get() - { - var countries = new List(); + var countries = new List(); - countries.Add(new Country() - { - Id = 1, - Name = "Country 1", - }); + countries.Add(new Country() + { + Id = 1, + Name = "Country 1", + }); - countries.Add(new Country() - { - Id = 2, - Name = "Country 2", - }); + countries.Add(new Country() + { + Id = 2, + Name = "Country 2", + }); - return countries; - } + return countries; } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/ProductSeed.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/ProductSeed.cs index 5a054186..27e8fe6a 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/ProductSeed.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/ProductSeed.cs @@ -4,29 +4,29 @@ namespace Ardalis.Specification.UnitTests.Fixture.Entities.Seeds { - public class ProductSeed + public class ProductSeed + { + public static List Get() { - public static List Get() - { - var products = new List(); + var products = new List(); - for (int i = 1; i < 100; i=i+2) - { - products.Add(new Product() - { - Id = i, - Name = $"Product {i}", - StoreId = i, - }); - products.Add(new Product() - { - Id = i + 1, - Name = $"Product {i + 1}", - StoreId = i, - }); - } + for (int i = 1; i < 100; i = i + 2) + { + products.Add(new Product() + { + Id = i, + Name = $"Product {i}", + StoreId = i, + }); + products.Add(new Product() + { + Id = i + 1, + Name = $"Product {i + 1}", + StoreId = i, + }); + } - return products; - } + return products; } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/StoreSeed.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/StoreSeed.cs index 6b53c997..95429d9e 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/StoreSeed.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Seeds/StoreSeed.cs @@ -5,73 +5,73 @@ namespace Ardalis.Specification.UnitTests.Fixture.Entities.Seeds { - public class StoreSeed - { - public const int VALID_STORE_ID = 1; - public const string VALID_STORE_NAME = "Store 1"; - public const string VALID_STORE_City = "City 1"; + public class StoreSeed + { + public const int VALID_STORE_ID = 1; + public const string VALID_STORE_NAME = "Store 1"; + public const string VALID_STORE_City = "City 1"; - public const int VALID_Search_ID = 50; - public const string VALID_Search_City_Key = "BCD"; - public const string VALID_Search_Name_Key = "BCE"; - public const string VALID_Search_City_Name_Key = "BC"; + public const int VALID_Search_ID = 50; + public const string VALID_Search_City_Key = "BCD"; + public const string VALID_Search_Name_Key = "BCE"; + public const string VALID_Search_City_Name_Key = "BC"; - public const int ORDERED_BY_NAME_FIRST_ID = 48; - public const int ORDERED_BY_NAME_LAST_ID = 49; - public const int ORDERED_BY_NAME_DESC_FIRST_ID = 49; - public const int ORDERED_BY_NAME_DESC_LAST_ID = 48; + public const int ORDERED_BY_NAME_FIRST_ID = 48; + public const int ORDERED_BY_NAME_LAST_ID = 49; + public const int ORDERED_BY_NAME_DESC_FIRST_ID = 49; + public const int ORDERED_BY_NAME_DESC_LAST_ID = 48; - public const int ORDERED_BY_NAME_FOR_COMPANY2_FIRST_ID = 98; - public const int ORDERED_BY_NAME_FOR_COMPANY2_LAST_ID = 99; - public const int ORDERED_BY_NAME_DESC_FOR_COMPANY2_FIRST_ID = 99; - public const int ORDERED_BY_NAME_DESC_FOR_COMPANY2_LAST_ID = 98; - public const int ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_FIRST_ID = 89; - public const int ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_LAST_ID = 80; + public const int ORDERED_BY_NAME_FOR_COMPANY2_FIRST_ID = 98; + public const int ORDERED_BY_NAME_FOR_COMPANY2_LAST_ID = 99; + public const int ORDERED_BY_NAME_DESC_FOR_COMPANY2_FIRST_ID = 99; + public const int ORDERED_BY_NAME_DESC_FOR_COMPANY2_LAST_ID = 98; + public const int ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_FIRST_ID = 89; + public const int ORDERED_BY_NAME_DESC_FOR_COMPANY2_PAGE2_LAST_ID = 80; - public static List Get() - { - var stores = new List(); + public static List Get() + { + var stores = new List(); - for (int i = 1; i <= 50; i++) - { - stores.Add(new Store() - { - Id = i, - Name = $"Store {i}", - City = $"City {i}", - AddressId = i, - CompanyId = 1, - }); - } - for (int i = 51; i <= 100; i++) - { - stores.Add(new Store() - { - Id = i, - Name = $"Store {i}", - City = $"City {i}", - AddressId = i, - CompanyId = 2, - }); - } + for (int i = 1; i <= 50; i++) + { + stores.Add(new Store() + { + Id = i, + Name = $"Store {i}", + City = $"City {i}", + AddressId = i, + CompanyId = 1, + }); + } + for (int i = 51; i <= 100; i++) + { + stores.Add(new Store() + { + Id = i, + Name = $"Store {i}", + City = $"City {i}", + AddressId = i, + CompanyId = 2, + }); + } - stores[49 - 1].Name = "ZZZ"; - stores[48 - 1].Name = "AAA"; - stores[99 - 1].Name = "YYY"; - stores[98 - 1].Name = "BBB"; + stores[49 - 1].Name = "ZZZ"; + stores[48 - 1].Name = "AAA"; + stores[99 - 1].Name = "YYY"; + stores[98 - 1].Name = "BBB"; - stores[100 - 1].Name = "Store 999"; + stores[100 - 1].Name = "Store 999"; - stores[50 - 1].City = "ABCDEFGH"; - stores[50 - 1].Name = "ABCEFGH"; + stores[50 - 1].City = "ABCDEFGH"; + stores[50 - 1].Name = "ABCEFGH"; - return stores; - } + return stores; + } - internal static IQueryable AsQueryable() - { - return Get().AsQueryable(); - } + internal static IQueryable AsQueryable() + { + return Get().AsQueryable(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Store.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Store.cs index f8a58579..6775a0eb 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Store.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Entities/Store.cs @@ -2,23 +2,23 @@ namespace Ardalis.Specification.UnitTests.Fixture.Entities { - public class Store - { - public int Id { get; set; } - public string? Name { get; set; } - public string? City { get; set; } + public class Store + { + public int Id { get; set; } + public string? Name { get; set; } + public string? City { get; set; } - public int CompanyId { get; set; } - public Company? Company { get; set; } + public int CompanyId { get; set; } + public Company? Company { get; set; } - public int AddressId { get; set; } - public Address? Address { get; set; } + public int AddressId { get; set; } + public Address? Address { get; set; } - public List Products { get; set; } = new List(); + public List Products { get; set; } = new List(); - public object GetSomethingFromStore() - { - return new object(); - } + public object GetSomethingFromStore() + { + return new object(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsSplitQuery.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsSplitQuery.cs index 9d7e1788..142ff1cd 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsSplitQuery.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsSplitQuery.cs @@ -2,14 +2,14 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class CompanyByIdAsSplitQuery : Specification, ISingleResultSpecification + public class CompanyByIdAsSplitQuery : Specification, ISingleResultSpecification + { + public CompanyByIdAsSplitQuery(int id) { - public CompanyByIdAsSplitQuery(int id) - { - Query.Where(company => company.Id == id) - .Include(x=>x.Stores) - .ThenInclude(x=>x.Products) - .AsSplitQuery(); - } + Query.Where(company => company.Id == id) + .Include(x => x.Stores) + .ThenInclude(x => x.Products) + .AsSplitQuery(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsUntrackedSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsUntrackedSpec.cs index 4567e1b4..c927e1c1 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsUntrackedSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsUntrackedSpec.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class CompanyByIdAsUntrackedSpec : Specification, ISingleResultSpecification + public class CompanyByIdAsUntrackedSpec : Specification, ISingleResultSpecification + { + public CompanyByIdAsUntrackedSpec(int id) { - public CompanyByIdAsUntrackedSpec(int id) - { - Query.Where(company => company.Id == id).AsNoTracking(); - } + Query.Where(company => company.Id == id).AsNoTracking(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsUntrackedWithIdentityResolutionSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsUntrackedWithIdentityResolutionSpec.cs index b08ee850..8da92f0e 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsUntrackedWithIdentityResolutionSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdAsUntrackedWithIdentityResolutionSpec.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class CompanyByIdAsUntrackedWithIdentityResolutionSpec : Specification, ISingleResultSpecification + public class CompanyByIdAsUntrackedWithIdentityResolutionSpec : Specification, ISingleResultSpecification + { + public CompanyByIdAsUntrackedWithIdentityResolutionSpec(int id) { - public CompanyByIdAsUntrackedWithIdentityResolutionSpec(int id) - { - Query.Where(company => company.Id == id).AsNoTrackingWithIdentityResolution(); - } + Query.Where(company => company.Id == id).AsNoTrackingWithIdentityResolution(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIgnoreQueryFilters.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIgnoreQueryFilters.cs index e146192d..3514d637 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIgnoreQueryFilters.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIgnoreQueryFilters.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class CompanyByIdIgnoreQueryFilters : Specification, ISingleResultSpecification + public class CompanyByIdIgnoreQueryFilters : Specification, ISingleResultSpecification + { + public CompanyByIdIgnoreQueryFilters(int id) { - public CompanyByIdIgnoreQueryFilters(int id) - { - Query.Where(company => company.Id == id).IgnoreQueryFilters(); - } + Query.Where(company => company.Id == id).IgnoreQueryFilters(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIncludeStoresThenIncludeAddressSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIncludeStoresThenIncludeAddressSpec.cs index f1b00617..2d655299 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIncludeStoresThenIncludeAddressSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIncludeStoresThenIncludeAddressSpec.cs @@ -2,13 +2,13 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class CompanyByIdIncludeStoresThenIncludeAddressSpec : Specification, ISingleResultSpecification + public class CompanyByIdIncludeStoresThenIncludeAddressSpec : Specification, ISingleResultSpecification + { + public CompanyByIdIncludeStoresThenIncludeAddressSpec(int id) { - public CompanyByIdIncludeStoresThenIncludeAddressSpec(int id) - { - Query.Where(x => x.Id == id) - .Include(x => x.Stores) - .ThenInclude(x => x.Address); - } + Query.Where(x => x.Id == id) + .Include(x => x.Stores) + .ThenInclude(x => x.Address); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIncludeStoresThenIncludeProductsSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIncludeStoresThenIncludeProductsSpec.cs index fdedaecf..85948f8b 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIncludeStoresThenIncludeProductsSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdIncludeStoresThenIncludeProductsSpec.cs @@ -2,13 +2,13 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class CompanyByIdIncludeStoresThenIncludeProductsSpec : Specification, ISingleResultSpecification + public class CompanyByIdIncludeStoresThenIncludeProductsSpec : Specification, ISingleResultSpecification + { + public CompanyByIdIncludeStoresThenIncludeProductsSpec(int id) { - public CompanyByIdIncludeStoresThenIncludeProductsSpec(int id) - { - Query.Where(x => x.Id == id) - .Include(x => x.Stores) - .ThenInclude(x => x.Products); - } + Query.Where(x => x.Id == id) + .Include(x => x.Stores) + .ThenInclude(x => x.Products); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdSpec.cs index d1993d2c..9ffc3458 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdSpec.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class CompanyByIdSpec : Specification, ISingleResultSpecification + public class CompanyByIdSpec : Specification, ISingleResultSpecification + { + public CompanyByIdSpec(int id) { - public CompanyByIdSpec(int id) - { - Query.Where(company => company.Id == id); - } + Query.Where(company => company.Id == id); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdWithFalseConditions.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdWithFalseConditions.cs index d1c7d3f7..3be772f7 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdWithFalseConditions.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdWithFalseConditions.cs @@ -2,28 +2,28 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class CompanyByIdWithFalseConditions : Specification, ISingleResultSpecification + public class CompanyByIdWithFalseConditions : Specification, ISingleResultSpecification + { + public CompanyByIdWithFalseConditions(int id) { - public CompanyByIdWithFalseConditions(int id) - { - Query.Where(x => x.Id == id, false) - .OrderBy(x => x.Id, false) - .ThenBy(x => x.Name) - .ThenByDescending(x => x.Name) - .OrderByDescending(x => x.Id, false) - .ThenBy(x => x.Name) - .ThenByDescending(x => x.Name) - .Include(x => x.Stores, false) - .ThenInclude(x => x.Products) - .Include(nameof(Store), false) - .Take(10, false) - .Skip(10, false) - .AsNoTracking(false) - .AsNoTrackingWithIdentityResolution(false) - .AsSplitQuery(false) - .IgnoreQueryFilters(false) - .Search(x => x.Name!, "asd", false) - .EnableCache(nameof(CompanyByIdWithFalseConditions), false, id); - } + Query.Where(x => x.Id == id, false) + .OrderBy(x => x.Id, false) + .ThenBy(x => x.Name) + .ThenByDescending(x => x.Name) + .OrderByDescending(x => x.Id, false) + .ThenBy(x => x.Name) + .ThenByDescending(x => x.Name) + .Include(x => x.Stores, false) + .ThenInclude(x => x.Products) + .Include(nameof(Store), false) + .Take(10, false) + .Skip(10, false) + .AsNoTracking(false) + .AsNoTrackingWithIdentityResolution(false) + .AsSplitQuery(false) + .IgnoreQueryFilters(false) + .Search(x => x.Name!, "asd", false) + .EnableCache(nameof(CompanyByIdWithFalseConditions), false, id); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdWithFalseConditionsForInnerChains.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdWithFalseConditionsForInnerChains.cs index 0b62b2bd..4d64b3ba 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdWithFalseConditionsForInnerChains.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/CompanyByIdWithFalseConditionsForInnerChains.cs @@ -2,29 +2,29 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class CompanyByIdWithFalseConditionsForInnerChains : Specification, ISingleResultSpecification + public class CompanyByIdWithFalseConditionsForInnerChains : Specification, ISingleResultSpecification + { + public CompanyByIdWithFalseConditionsForInnerChains(int id) { - public CompanyByIdWithFalseConditionsForInnerChains(int id) - { - Query.Where(x => x.Id == id, false) - .OrderBy(x => x.Id) - .ThenBy(x => x.Name, false) - .ThenByDescending(x => x.Name) - .OrderByDescending(x => x.Id) - .ThenByDescending(x => x.Name, false) - .ThenBy(x => x.Name) - .Include(x => x.Stores) - .ThenInclude(x => x.Products, false) - .ThenInclude(x => x.Store) - .Include(nameof(Store), false) - .Take(10, false) - .Skip(10, false) - .AsNoTracking(false) - .AsNoTrackingWithIdentityResolution(false) - .AsSplitQuery(false) - .IgnoreQueryFilters(false) - .Search(x => x.Name!, "asd", false) - .EnableCache(nameof(CompanyByIdWithFalseConditions), false, id); - } + Query.Where(x => x.Id == id, false) + .OrderBy(x => x.Id) + .ThenBy(x => x.Name, false) + .ThenByDescending(x => x.Name) + .OrderByDescending(x => x.Id) + .ThenByDescending(x => x.Name, false) + .ThenBy(x => x.Name) + .Include(x => x.Stores) + .ThenInclude(x => x.Products, false) + .ThenInclude(x => x.Store) + .Include(nameof(Store), false) + .Take(10, false) + .Skip(10, false) + .AsNoTracking(false) + .AsNoTrackingWithIdentityResolution(false) + .AsSplitQuery(false) + .IgnoreQueryFilters(false) + .Search(x => x.Name!, "asd", false) + .EnableCache(nameof(CompanyByIdWithFalseConditions), false, id); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdAndNameSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdAndNameSpec.cs index 6c07210f..959acd2c 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdAndNameSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdAndNameSpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreByIdAndNameSpec : Specification + public class StoreByIdAndNameSpec : Specification + { + public StoreByIdAndNameSpec(int Id, string name) { - public StoreByIdAndNameSpec(int Id, string name) - { - Query.Where(x => x.Id == Id) - .Where(x => x.Name == name); - } + Query.Where(x => x.Id == Id) + .Where(x => x.Name == name); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeAddressAndProductsSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeAddressAndProductsSpec.cs index c1070ce6..7534700f 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeAddressAndProductsSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeAddressAndProductsSpec.cs @@ -2,13 +2,13 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreByIdIncludeAddressAndProductsSpec : Specification, ISingleResultSpecification + public class StoreByIdIncludeAddressAndProductsSpec : Specification, ISingleResultSpecification + { + public StoreByIdIncludeAddressAndProductsSpec(int id) { - public StoreByIdIncludeAddressAndProductsSpec(int id) - { - Query.Where(x => x.Id == id); - Query.Include(x => x.Address); - Query.Include(x => x.Products); - } + Query.Where(x => x.Id == id); + Query.Include(x => x.Address); + Query.Include(x => x.Products); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeAddressSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeAddressSpec.cs index 30e03f58..37f50348 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeAddressSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeAddressSpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreByIdIncludeAddressSpec : Specification, ISingleResultSpecification + public class StoreByIdIncludeAddressSpec : Specification, ISingleResultSpecification + { + public StoreByIdIncludeAddressSpec(int id) { - public StoreByIdIncludeAddressSpec(int id) - { - Query.Where(x => x.Id == id) - .Include(x => x.Address); - } + Query.Where(x => x.Id == id) + .Include(x => x.Address); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec.cs index af181b72..8c55bb14 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec.cs @@ -2,13 +2,13 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec : Specification, ISingleResultSpecification + public class StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec : Specification, ISingleResultSpecification + { + public StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec(int id) { - public StoreByIdIncludeCompanyAndCountryAndStoresForCompanySpec(int id) - { - Query.Where(x => x.Id == id); - Query.Include(x => x.Company).ThenInclude(x => x!.Country); - Query.Include(x => x.Company).ThenInclude(x => x!.Stores).ThenInclude(x => x.Products); - } + Query.Where(x => x.Id == id); + Query.Include(x => x.Company).ThenInclude(x => x!.Country); + Query.Include(x => x.Company).ThenInclude(x => x!.Stores).ThenInclude(x => x.Products); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeProductsSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeProductsSpec.cs index 8d3f8b55..a8bcb0b7 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeProductsSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeProductsSpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreByIdIncludeProductsSpec : Specification, ISingleResultSpecification + public class StoreByIdIncludeProductsSpec : Specification, ISingleResultSpecification + { + public StoreByIdIncludeProductsSpec(int id) { - public StoreByIdIncludeProductsSpec(int id) - { - Query.Where(x => x.Id == id) - .Include(x => x.Products); - } + Query.Where(x => x.Id == id) + .Include(x => x.Products); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeProductsUsingStringSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeProductsUsingStringSpec.cs index 58172555..97272316 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeProductsUsingStringSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdIncludeProductsUsingStringSpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreByIdIncludeProductsUsingStringSpec : Specification, ISingleResultSpecification + public class StoreByIdIncludeProductsUsingStringSpec : Specification, ISingleResultSpecification + { + public StoreByIdIncludeProductsUsingStringSpec(int id) { - public StoreByIdIncludeProductsUsingStringSpec(int id) - { - Query.Where(x => x.Id == id) - .Include(nameof(Store.Products)); - } + Query.Where(x => x.Id == id) + .Include(nameof(Store.Products)); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSearchByNameAndCitySpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSearchByNameAndCitySpec.cs index dfb2c722..e5125d9e 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSearchByNameAndCitySpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSearchByNameAndCitySpec.cs @@ -2,13 +2,13 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreByIdSearchByNameAndCitySpec : Specification + public class StoreByIdSearchByNameAndCitySpec : Specification + { + public StoreByIdSearchByNameAndCitySpec(int id, string searchTerm) { - public StoreByIdSearchByNameAndCitySpec(int id, string searchTerm) - { - Query.Where(x=> x.Id == id) - .Search(x => x.Name!, "%" + searchTerm + "%", 1) - .Search(x => x.City!, "%" + searchTerm + "%", 2); - } + Query.Where(x => x.Id == id) + .Search(x => x.Name!, "%" + searchTerm + "%", 1) + .Search(x => x.City!, "%" + searchTerm + "%", 2); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSearchByNameOrCitySpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSearchByNameOrCitySpec.cs index ef8cf1cf..626b6d4c 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSearchByNameOrCitySpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSearchByNameOrCitySpec.cs @@ -2,13 +2,13 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreByIdSearchByNameOrCitySpec : Specification + public class StoreByIdSearchByNameOrCitySpec : Specification + { + public StoreByIdSearchByNameOrCitySpec(int id, string searchTerm) { - public StoreByIdSearchByNameOrCitySpec(int id, string searchTerm) - { - Query.Where(x => x.Id == id) - .Search(x => x.Name!, "%" + searchTerm + "%") - .Search(x => x.City!, "%" + searchTerm + "%"); - } + Query.Where(x => x.Id == id) + .Search(x => x.Name!, "%" + searchTerm + "%") + .Search(x => x.City!, "%" + searchTerm + "%"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSpec.cs index 2ff7c5fb..275d92ec 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreByIdSpec.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreByIdSpec : Specification + public class StoreByIdSpec : Specification + { + public StoreByIdSpec(int Id) { - public StoreByIdSpec(int Id) - { - Query.Where(x => x.Id == Id); - } + Query.Where(x => x.Id == Id); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreDuplicateSkipSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreDuplicateSkipSpec.cs index 731c0d7f..30269ad6 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreDuplicateSkipSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreDuplicateSkipSpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreDuplicateSkipSpec : Specification + public class StoreDuplicateSkipSpec : Specification + { + public StoreDuplicateSkipSpec() { - public StoreDuplicateSkipSpec() - { - Query.Skip(1) - .Skip(2); - } + Query.Skip(1) + .Skip(2); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreDuplicateTakeSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreDuplicateTakeSpec.cs index be2e4ffb..7c57fcab 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreDuplicateTakeSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreDuplicateTakeSpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreDuplicateTakeSpec : Specification + public class StoreDuplicateTakeSpec : Specification + { + public StoreDuplicateTakeSpec() { - public StoreDuplicateTakeSpec() - { - Query.Take(1) - .Take(2); - } + Query.Take(1) + .Take(2); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreEmptySpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreEmptySpec.cs index ee32680a..4d0bc45b 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreEmptySpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreEmptySpec.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreEmptySpec : Specification + public class StoreEmptySpec : Specification + { + public StoreEmptySpec() { - public StoreEmptySpec() - { - } } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesEmptySpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesEmptySpec.cs index 62df32b1..2593d0b9 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesEmptySpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesEmptySpec.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreNamesEmptySpec : Specification + public class StoreNamesEmptySpec : Specification + { + public StoreNamesEmptySpec() { - public StoreNamesEmptySpec() - { - } } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesPaginatedSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesPaginatedSpec.cs index cfd31154..f15756f4 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesPaginatedSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesPaginatedSpec.cs @@ -2,15 +2,15 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreNamesPaginatedSpec : Specification + public class StoreNamesPaginatedSpec : Specification + { + public StoreNamesPaginatedSpec(int skip, int take) { - public StoreNamesPaginatedSpec(int skip, int take) - { - Query.OrderBy(x => x.Id) - .Skip(skip) - .Take(take); + Query.OrderBy(x => x.Id) + .Skip(skip) + .Take(take); - Query.Select(x => x.Name); - } + Query.Select(x => x.Name); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesSpec.cs index 765006d5..38a3ad4c 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesSpec.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreNamesSpec : Specification + public class StoreNamesSpec : Specification + { + public StoreNamesSpec() { - public StoreNamesSpec() - { - Query.Select(x => x.Name); - } + Query.Select(x => x.Name); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesWithPostProcessingActionSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesWithPostProcessingActionSpec.cs index 04fc9761..44d85f05 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesWithPostProcessingActionSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreNamesWithPostProcessingActionSpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreNamesWithPostProcessingActionSpec : Specification + public class StoreNamesWithPostProcessingActionSpec : Specification + { + public StoreNamesWithPostProcessingActionSpec() { - public StoreNamesWithPostProcessingActionSpec() - { - Query.Select(x=>x.Name) - .PostProcessingAction(x => x); - } + Query.Select(x => x.Name) + .PostProcessingAction(x => x); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameAndCitySpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameAndCitySpec.cs index eef31263..3efccacc 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameAndCitySpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameAndCitySpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreSearchByNameAndCitySpec : Specification + public class StoreSearchByNameAndCitySpec : Specification + { + public StoreSearchByNameAndCitySpec(string searchTerm) { - public StoreSearchByNameAndCitySpec(string searchTerm) - { - Query.Search(x => x.Name!, "%" + searchTerm + "%", 1) - .Search(x => x.City!, "%" + searchTerm + "%", 2); - } + Query.Search(x => x.Name!, "%" + searchTerm + "%", 1) + .Search(x => x.City!, "%" + searchTerm + "%", 2); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameOrCitySpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameOrCitySpec.cs index 0eb15174..643f0a1c 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameOrCitySpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameOrCitySpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreSearchByNameOrCitySpec : Specification + public class StoreSearchByNameOrCitySpec : Specification + { + public StoreSearchByNameOrCitySpec(string searchTerm) { - public StoreSearchByNameOrCitySpec(string searchTerm) - { - Query.Search(x => x.Name!, "%" + searchTerm + "%") - .Search(x => x.City!, "%" + searchTerm + "%"); - } + Query.Search(x => x.Name!, "%" + searchTerm + "%") + .Search(x => x.City!, "%" + searchTerm + "%"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameSpec.cs index afec911a..3cd31ca6 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreSearchByNameSpec.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreSearchByNameSpec : Specification + public class StoreSearchByNameSpec : Specification + { + public StoreSearchByNameSpec(string searchTerm) { - public StoreSearchByNameSpec(string searchTerm) - { - Query.Search(x => x.Name!, "%" + searchTerm + "%"); - } + Query.Search(x => x.Name!, "%" + searchTerm + "%"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreWithPostProcessingActionSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreWithPostProcessingActionSpec.cs index 97ab3881..a8d93937 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreWithPostProcessingActionSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoreWithPostProcessingActionSpec.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreWithPostProcessingActionSpec : Specification + public class StoreWithPostProcessingActionSpec : Specification + { + public StoreWithPostProcessingActionSpec() { - public StoreWithPostProcessingActionSpec() - { - Query.PostProcessingAction(x => x); - } + Query.PostProcessingAction(x => x); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameSpec.cs index bbdaed01..1d805b02 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameSpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoresByCompanyOrderedDescByNameSpec : Specification + public class StoresByCompanyOrderedDescByNameSpec : Specification + { + public StoresByCompanyOrderedDescByNameSpec(int companyId) { - public StoresByCompanyOrderedDescByNameSpec(int companyId) - { - Query.Where(x => x.CompanyId == companyId) - .OrderByDescending(x => x.Name); - } + Query.Where(x => x.CompanyId == companyId) + .OrderByDescending(x => x.Name); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameThenByDescIdSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameThenByDescIdSpec.cs index 10ed04fc..5e7e2581 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameThenByDescIdSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameThenByDescIdSpec.cs @@ -2,13 +2,13 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoresByCompanyOrderedDescByNameThenByDescIdSpec : Specification + public class StoresByCompanyOrderedDescByNameThenByDescIdSpec : Specification + { + public StoresByCompanyOrderedDescByNameThenByDescIdSpec(int companyId) { - public StoresByCompanyOrderedDescByNameThenByDescIdSpec(int companyId) - { - Query.Where(x => x.CompanyId == companyId) - .OrderByDescending(x => x.Name) - .ThenByDescending(x => x.Id); - } + Query.Where(x => x.CompanyId == companyId) + .OrderByDescending(x => x.Name) + .ThenByDescending(x => x.Id); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameThenByIdSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameThenByIdSpec.cs index e7a7d758..fbf6f944 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameThenByIdSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyOrderedDescByNameThenByIdSpec.cs @@ -2,13 +2,13 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoresByCompanyOrderedDescByNameThenByIdSpec : Specification + public class StoresByCompanyOrderedDescByNameThenByIdSpec : Specification + { + public StoresByCompanyOrderedDescByNameThenByIdSpec(int companyId) { - public StoresByCompanyOrderedDescByNameThenByIdSpec(int companyId) - { - Query.Where(x => x.CompanyId == companyId) - .OrderByDescending(x => x.Name) - .ThenBy(x => x.Id); - } + Query.Where(x => x.CompanyId == companyId) + .OrderByDescending(x => x.Name) + .ThenBy(x => x.Id); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyPaginatedOrderedDescByNameSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyPaginatedOrderedDescByNameSpec.cs index 1c42e7fb..21e171ba 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyPaginatedOrderedDescByNameSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyPaginatedOrderedDescByNameSpec.cs @@ -1,19 +1,19 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoresByCompanyPaginatedOrderedDescByNameSpec : Specification + public class StoresByCompanyPaginatedOrderedDescByNameSpec : Specification + { + public StoresByCompanyPaginatedOrderedDescByNameSpec(int companyId, int skip, int take) { - public StoresByCompanyPaginatedOrderedDescByNameSpec(int companyId, int skip, int take) - { - Query.Where(x => x.CompanyId == companyId) - .Skip(skip) - .Take(take) - .OrderByDescending(x => x.Name); - } + Query.Where(x => x.CompanyId == companyId) + .Skip(skip) + .Take(take) + .OrderByDescending(x => x.Name); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyPaginatedSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyPaginatedSpec.cs index 747da9fc..a7520152 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyPaginatedSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByCompanyPaginatedSpec.cs @@ -2,14 +2,14 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoresByCompanyPaginatedSpec : Specification + public class StoresByCompanyPaginatedSpec : Specification + { + public StoresByCompanyPaginatedSpec(int companyId, int skip, int take) { - public StoresByCompanyPaginatedSpec(int companyId, int skip, int take) - { - Query.Where(x => x.CompanyId == companyId) - .OrderBy(x => x.CompanyId) - .Skip(skip) - .Take(take); - } + Query.Where(x => x.CompanyId == companyId) + .OrderBy(x => x.CompanyId) + .Skip(skip) + .Take(take); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByIdListSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByIdListSpec.cs index 0a1c3648..7e389f9b 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByIdListSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresByIdListSpec.cs @@ -1,15 +1,15 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Linq; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoresByIdListSpec : Specification + public class StoresByIdListSpec : Specification + { + public StoresByIdListSpec(IEnumerable Ids) { - public StoresByIdListSpec(IEnumerable Ids) - { - Query.Where(x => Ids.Contains(x.Id)); - } + Query.Where(x => Ids.Contains(x.Id)); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedDescendingByNameSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedDescendingByNameSpec.cs index 60440b6f..cbd3632e 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedDescendingByNameSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedDescendingByNameSpec.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoresOrderedDescendingByNameSpec : Specification + public class StoresOrderedDescendingByNameSpec : Specification + { + public StoresOrderedDescendingByNameSpec() { - public StoresOrderedDescendingByNameSpec() - { - Query.OrderByDescending(x => x.Name); - } + Query.OrderByDescending(x => x.Name); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedSpecByName.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedSpecByName.cs index c247ff9a..de1d9dcb 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedSpecByName.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedSpecByName.cs @@ -2,11 +2,11 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoresOrderedSpecByName : Specification + public class StoresOrderedSpecByName : Specification + { + public StoresOrderedSpecByName() { - public StoresOrderedSpecByName() - { - Query.OrderBy(x => x.Name); - } + Query.OrderBy(x => x.Name); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedTwoChainsSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedTwoChainsSpec.cs index d21a948a..1de74c49 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedTwoChainsSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresOrderedTwoChainsSpec.cs @@ -2,12 +2,12 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoresOrderedTwoChainsSpec : Specification + public class StoresOrderedTwoChainsSpec : Specification + { + public StoresOrderedTwoChainsSpec() { - public StoresOrderedTwoChainsSpec() - { - Query.OrderBy(x => x.Name) - .OrderBy(x => x.Id); - } + Query.OrderBy(x => x.Name) + .OrderBy(x => x.Id); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresPaginatedSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresPaginatedSpec.cs index 44300014..62fb5834 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresPaginatedSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/Specs/StoresPaginatedSpec.cs @@ -2,13 +2,13 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoresPaginatedSpec : Specification + public class StoresPaginatedSpec : Specification + { + public StoresPaginatedSpec(int skip, int take) { - public StoresPaginatedSpec(int skip, int take) - { - Query.OrderBy(s => s.Id) - .Skip(skip) - .Take(take); - } + Query.OrderBy(s => s.Id) + .Skip(skip) + .Take(take); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/CompanyIncludeFilteredStoresSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/CompanyIncludeFilteredStoresSpec.cs index 1fcd27c1..4a1c614a 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/CompanyIncludeFilteredStoresSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/CompanyIncludeFilteredStoresSpec.cs @@ -1,17 +1,17 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class CompanyIncludeFilteredStoresSpec : Specification + public class CompanyIncludeFilteredStoresSpec : Specification + { + public CompanyIncludeFilteredStoresSpec(int id) { - public CompanyIncludeFilteredStoresSpec(int id) - { - Query.Where(x => x.Id == id) - .Include(x => x.Stores.Where(s => s.Id == 1)); - } + Query.Where(x => x.Id == id) + .Include(x => x.Stores.Where(s => s.Id == 1)); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeAddressAndProductsSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeAddressAndProductsSpec.cs index 45ec82d0..eeb278b5 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeAddressAndProductsSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeAddressAndProductsSpec.cs @@ -1,16 +1,16 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeAddressAndProductsSpec : Specification + public class StoreIncludeAddressAndProductsSpec : Specification + { + public StoreIncludeAddressAndProductsSpec() { - public StoreIncludeAddressAndProductsSpec() - { - Query.Include(x => x.Products) - .Include(x=>x!.Address); - } + Query.Include(x => x.Products) + .Include(x => x!.Address); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeAddressSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeAddressSpec.cs index 00b19493..7190c595 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeAddressSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeAddressSpec.cs @@ -1,15 +1,15 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeAddressSpec : Specification + public class StoreIncludeAddressSpec : Specification + { + public StoreIncludeAddressSpec() { - public StoreIncludeAddressSpec() - { - Query.Include(x => x.Address); - } + Query.Include(x => x.Address); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyCountryDotSeparatedSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyCountryDotSeparatedSpec.cs index 2d733f5f..a38ac825 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyCountryDotSeparatedSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyCountryDotSeparatedSpec.cs @@ -1,15 +1,15 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeCompanyCountryDotSeparatedSpec : Specification + public class StoreIncludeCompanyCountryDotSeparatedSpec : Specification + { + public StoreIncludeCompanyCountryDotSeparatedSpec() { - public StoreIncludeCompanyCountryDotSeparatedSpec() - { - Query.Include(x => x.Company!.Country); - } + Query.Include(x => x.Company!.Country); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenCountryAsStringSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenCountryAsStringSpec.cs index 786132b7..1d06bb3c 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenCountryAsStringSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenCountryAsStringSpec.cs @@ -1,15 +1,15 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeCompanyThenCountryAsStringSpec : Specification + public class StoreIncludeCompanyThenCountryAsStringSpec : Specification + { + public StoreIncludeCompanyThenCountryAsStringSpec() { - public StoreIncludeCompanyThenCountryAsStringSpec() - { - Query.Include($"{nameof(Company)}.{nameof(Company.Country)}"); - } + Query.Include($"{nameof(Company)}.{nameof(Company.Country)}"); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenCountrySpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenCountrySpec.cs index 8937bb17..efbadcf0 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenCountrySpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenCountrySpec.cs @@ -1,16 +1,16 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeCompanyThenCountrySpec : Specification + public class StoreIncludeCompanyThenCountrySpec : Specification + { + public StoreIncludeCompanyThenCountrySpec() { - public StoreIncludeCompanyThenCountrySpec() - { - Query.Include(x => x.Company) - .ThenInclude(x=>x!.Country); - } + Query.Include(x => x.Company) + .ThenInclude(x => x!.Country); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenNameSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenNameSpec.cs index c4b3ee00..a41f8979 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenNameSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenNameSpec.cs @@ -1,16 +1,16 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeCompanyThenNameSpec : Specification + public class StoreIncludeCompanyThenNameSpec : Specification + { + public StoreIncludeCompanyThenNameSpec() { - public StoreIncludeCompanyThenNameSpec() - { - Query.Include(x => x.Company) - .ThenInclude(x=>x!.Name); - } + Query.Include(x => x.Company) + .ThenInclude(x => x!.Name); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenStoresSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenStoresSpec.cs index 84772a43..c23482a6 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenStoresSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeCompanyThenStoresSpec.cs @@ -2,13 +2,13 @@ namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeCompanyThenStoresSpec : Specification + public class StoreIncludeCompanyThenStoresSpec : Specification + { + public StoreIncludeCompanyThenStoresSpec() { - public StoreIncludeCompanyThenStoresSpec() - { - Query.Include(x => x.Company) - .ThenInclude(x => x!.Stores) - .ThenInclude(x => x.Products); - } + Query.Include(x => x.Company) + .ThenInclude(x => x!.Stores) + .ThenInclude(x => x.Products); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeMethodOfNavigationSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeMethodOfNavigationSpec.cs index 2a8c493e..fe8f7af6 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeMethodOfNavigationSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeMethodOfNavigationSpec.cs @@ -1,15 +1,15 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeMethodOfNavigationSpec : Specification + public class StoreIncludeMethodOfNavigationSpec : Specification + { + public StoreIncludeMethodOfNavigationSpec() { - public StoreIncludeMethodOfNavigationSpec() - { - Query.Include(x => x.Address!.GetSomethingFromAddress()); - } + Query.Include(x => x.Address!.GetSomethingFromAddress()); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeMethodSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeMethodSpec.cs index 93fd4b43..5b7599de 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeMethodSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeMethodSpec.cs @@ -1,15 +1,15 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeMethodSpec : Specification + public class StoreIncludeMethodSpec : Specification + { + public StoreIncludeMethodSpec() { - public StoreIncludeMethodSpec() - { - Query.Include(x => x.GetSomethingFromStore()); - } + Query.Include(x => x.GetSomethingFromStore()); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeNameSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeNameSpec.cs index 3aacd166..9ace7e9e 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeNameSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeNameSpec.cs @@ -1,15 +1,15 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeNameSpec : Specification + public class StoreIncludeNameSpec : Specification + { + public StoreIncludeNameSpec() { - public StoreIncludeNameSpec() - { - Query.Include(x => x.Name); - } + Query.Include(x => x.Name); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeProductsSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeProductsSpec.cs index fa03a66d..44a235bd 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeProductsSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreIncludeProductsSpec.cs @@ -1,15 +1,15 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreIncludeProductsSpec : Specification + public class StoreIncludeProductsSpec : Specification + { + public StoreIncludeProductsSpec() { - public StoreIncludeProductsSpec() - { - Query.Include(x => x.Products); - } + Query.Include(x => x.Products); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreWithFaultyIncludeSpec.cs b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreWithFaultyIncludeSpec.cs index f08ff181..35dabccd 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreWithFaultyIncludeSpec.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/Fixture/SpecsForIncludeTests/StoreWithFaultyIncludeSpec.cs @@ -1,15 +1,15 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.Specification.UnitTests.Fixture.Entities; namespace Ardalis.Specification.UnitTests.Fixture.Specs { - public class StoreWithFaultyIncludeSpec : Specification + public class StoreWithFaultyIncludeSpec : Specification + { + public StoreWithFaultyIncludeSpec() { - public StoreWithFaultyIncludeSpec() - { - Query.Include(x => x.Id == 1 && x.Name == "Something"); - } + Query.Include(x => x.Id == 1 && x.Name == "Something"); } -} \ No newline at end of file + } +} diff --git a/Specification/tests/Ardalis.Specification.UnitTests/IncludeExpressionInfoTests.cs b/Specification/tests/Ardalis.Specification.UnitTests/IncludeExpressionInfoTests.cs index 424629ee..b4e930ab 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/IncludeExpressionInfoTests.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/IncludeExpressionInfoTests.cs @@ -1,56 +1,54 @@ using System; using System.Linq.Expressions; - -using Xunit; -using FluentAssertions; - using Ardalis.Specification.UnitTests.Fixture.Entities; +using FluentAssertions; +using Xunit; namespace Ardalis.Specification.UnitTests { - public class IncludeExpressionInfoTests + public class IncludeExpressionInfoTests + { + private readonly Expression> expr; + + public IncludeExpressionInfoTests() + { + expr = x => x.Country!; + } + + [Fact] + public void ThrowsArgumentNullException_GivenNullForLambdaExpression() { - private readonly Expression> expr; - - public IncludeExpressionInfoTests() - { - expr = x => x.Country!; - } - - [Fact] - public void ThrowsArgumentNullException_GivenNullForLambdaExpression() - { - Action sutAction = () => new IncludeExpressionInfo(null!, typeof(Company), typeof(Country)); - - sutAction.Should() - .Throw(); - } - - [Fact] - public void ThrowsArgumentNullException_GivenNullForEntityType() - { - Action sutAction = () => new IncludeExpressionInfo(expr, null!, typeof(Country)); - - sutAction.Should() - .Throw(); - } - - [Fact] - public void ThrowsArgumentNullException_GivenNullForPropertyType() - { - Action sutAction = () => new IncludeExpressionInfo(expr, typeof(Company), null!); - - sutAction.Should() - .Throw(); - } - - [Fact] - public void ThrowsArgumentNullException_GivenNullForPreviousPropertyType() - { - Action sutAction = () => new IncludeExpressionInfo(expr, typeof(Company), typeof(Country), null!); - - sutAction.Should() - .Throw(); - } + Action sutAction = () => new IncludeExpressionInfo(null!, typeof(Company), typeof(Country)); + + sutAction.Should() + .Throw(); + } + + [Fact] + public void ThrowsArgumentNullException_GivenNullForEntityType() + { + Action sutAction = () => new IncludeExpressionInfo(expr, null!, typeof(Country)); + + sutAction.Should() + .Throw(); + } + + [Fact] + public void ThrowsArgumentNullException_GivenNullForPropertyType() + { + Action sutAction = () => new IncludeExpressionInfo(expr, typeof(Company), null!); + + sutAction.Should() + .Throw(); + } + + [Fact] + public void ThrowsArgumentNullException_GivenNullForPreviousPropertyType() + { + Action sutAction = () => new IncludeExpressionInfo(expr, typeof(Company), typeof(Country), null!); + + sutAction.Should() + .Throw(); } + } } diff --git a/Specification/tests/Ardalis.Specification.UnitTests/ValidatorTests/SpecificationValidator_Tests.cs b/Specification/tests/Ardalis.Specification.UnitTests/ValidatorTests/SpecificationValidator_Tests.cs index 7a36c6f4..e9d4b309 100644 --- a/Specification/tests/Ardalis.Specification.UnitTests/ValidatorTests/SpecificationValidator_Tests.cs +++ b/Specification/tests/Ardalis.Specification.UnitTests/ValidatorTests/SpecificationValidator_Tests.cs @@ -1,98 +1,98 @@ -using Ardalis.Specification.UnitTests.Fixture.Entities; -using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; -using Ardalis.Specification.UnitTests.Fixture.Specs; -using FluentAssertions; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Ardalis.Specification.UnitTests.Fixture.Entities; +using Ardalis.Specification.UnitTests.Fixture.Entities.Seeds; +using Ardalis.Specification.UnitTests.Fixture.Specs; +using FluentAssertions; namespace Ardalis.Specification.UnitTests.ValidatorTests { - public class SpecificationValidator_Tests - { - Store store = StoreSeed.Get().Single(x => x.Id == StoreSeed.VALID_Search_ID); + public class SpecificationValidator_Tests + { + Store store = StoreSeed.Get().Single(x => x.Id == StoreSeed.VALID_Search_ID); - public void ReturnsTrue_GivenStoreByIdSearchByNameAndCitySpec_WithValidValues() - { - var spec = new StoreByIdSearchByNameAndCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_City_Name_Key); + public void ReturnsTrue_GivenStoreByIdSearchByNameAndCitySpec_WithValidValues() + { + var spec = new StoreByIdSearchByNameAndCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_City_Name_Key); - var result = spec.IsSatisfiedBy(store); + var result = spec.IsSatisfiedBy(store); - result.Should().BeTrue(); - } + result.Should().BeTrue(); + } - public void ReturnsFalse_GivenStoreByIdSearchByNameAndCitySpec_WithInvalidId() - { - var spec = new StoreByIdSearchByNameAndCitySpec(1, StoreSeed.VALID_Search_City_Name_Key); + public void ReturnsFalse_GivenStoreByIdSearchByNameAndCitySpec_WithInvalidId() + { + var spec = new StoreByIdSearchByNameAndCitySpec(1, StoreSeed.VALID_Search_City_Name_Key); - var result = spec.IsSatisfiedBy(store); + var result = spec.IsSatisfiedBy(store); - result.Should().BeFalse(); - } + result.Should().BeFalse(); + } - public void ReturnsFalse_GivenStoreByIdSearchByNameAndCitySpec_WithInvalidNameSearchString() - { - var spec = new StoreByIdSearchByNameAndCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_City_Key); + public void ReturnsFalse_GivenStoreByIdSearchByNameAndCitySpec_WithInvalidNameSearchString() + { + var spec = new StoreByIdSearchByNameAndCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_City_Key); - var result = spec.IsSatisfiedBy(store); + var result = spec.IsSatisfiedBy(store); - result.Should().BeFalse(); - } + result.Should().BeFalse(); + } - public void ReturnsFalse_GivenStoreByIdSearchByNameAndCitySpec_WithInvalidCitySearchString() - { - var spec = new StoreByIdSearchByNameAndCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_Name_Key); + public void ReturnsFalse_GivenStoreByIdSearchByNameAndCitySpec_WithInvalidCitySearchString() + { + var spec = new StoreByIdSearchByNameAndCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_Name_Key); - var result = spec.IsSatisfiedBy(store); + var result = spec.IsSatisfiedBy(store); - result.Should().BeFalse(); - } + result.Should().BeFalse(); + } - public void ReturnsFalse_StoreByIdSearchByNameAndCitySpecSpec_WithInvalidCityAndNameSearchString() - { - var spec = new StoreByIdSearchByNameAndCitySpec(StoreSeed.VALID_Search_ID, "random"); + public void ReturnsFalse_StoreByIdSearchByNameAndCitySpecSpec_WithInvalidCityAndNameSearchString() + { + var spec = new StoreByIdSearchByNameAndCitySpec(StoreSeed.VALID_Search_ID, "random"); - var result = spec.IsSatisfiedBy(store); + var result = spec.IsSatisfiedBy(store); - result.Should().BeFalse(); - } + result.Should().BeFalse(); + } - public void ReturnsTrue_StoreByIdSearchByNameOrCitySpecSpec_WithValidValues() - { - var spec = new StoreByIdSearchByNameOrCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_City_Name_Key); + public void ReturnsTrue_StoreByIdSearchByNameOrCitySpecSpec_WithValidValues() + { + var spec = new StoreByIdSearchByNameOrCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_City_Name_Key); - var result = spec.IsSatisfiedBy(store); + var result = spec.IsSatisfiedBy(store); - result.Should().BeTrue(); - } + result.Should().BeTrue(); + } - public void ReturnsTrue_StoreByIdSearchByNameOrCitySpecSpec_WithInvalidNameSearchString() - { - var spec = new StoreByIdSearchByNameOrCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_City_Key); + public void ReturnsTrue_StoreByIdSearchByNameOrCitySpecSpec_WithInvalidNameSearchString() + { + var spec = new StoreByIdSearchByNameOrCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_City_Key); - var result = spec.IsSatisfiedBy(store); + var result = spec.IsSatisfiedBy(store); - result.Should().BeTrue(); - } + result.Should().BeTrue(); + } - public void ReturnsTrue_StoreByIdSearchByNameOrCitySpecSpec_WithInvalidCitySearchString() - { - var spec = new StoreByIdSearchByNameOrCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_Name_Key); + public void ReturnsTrue_StoreByIdSearchByNameOrCitySpecSpec_WithInvalidCitySearchString() + { + var spec = new StoreByIdSearchByNameOrCitySpec(StoreSeed.VALID_Search_ID, StoreSeed.VALID_Search_Name_Key); - var result = spec.IsSatisfiedBy(store); + var result = spec.IsSatisfiedBy(store); - result.Should().BeTrue(); - } + result.Should().BeTrue(); + } - public void ReturnsFalse_StoreByIdSearchByNameOrCitySpecSpec_WithInvalidCityAndNameSearchString() - { - var spec = new StoreByIdSearchByNameOrCitySpec(StoreSeed.VALID_Search_ID, "random"); + public void ReturnsFalse_StoreByIdSearchByNameOrCitySpecSpec_WithInvalidCityAndNameSearchString() + { + var spec = new StoreByIdSearchByNameOrCitySpec(StoreSeed.VALID_Search_ID, "random"); - var result = spec.IsSatisfiedBy(store); + var result = spec.IsSatisfiedBy(store); - result.Should().BeFalse(); - } + result.Should().BeFalse(); } + } } diff --git a/sample/Ardalis.SampleApp.Core/Entities/CustomerAggregate/Customer.cs b/sample/Ardalis.SampleApp.Core/Entities/CustomerAggregate/Customer.cs index f8e48feb..0607c5a3 100644 --- a/sample/Ardalis.SampleApp.Core/Entities/CustomerAggregate/Customer.cs +++ b/sample/Ardalis.SampleApp.Core/Entities/CustomerAggregate/Customer.cs @@ -5,51 +5,51 @@ namespace Ardalis.SampleApp.Core.Entities.CustomerAggregate { - public class Customer : IAggregateRoot - { - public int Id { get; private set; } - public string Name { get; private set; } - public string Email { get; private set; } - public string Address { get; private set; } + public class Customer : IAggregateRoot + { + public int Id { get; private set; } + public string Name { get; private set; } + public string Email { get; private set; } + public string Address { get; private set; } - public IEnumerable Stores => _stores.AsEnumerable(); - private readonly List _stores = new List(); + public IEnumerable Stores => _stores.AsEnumerable(); + private readonly List _stores = new List(); - public Customer(string name, string email, string address) - { - Guard.Against.NullOrEmpty(name, nameof(name)); - Guard.Against.NullOrEmpty(email, nameof(email)); + public Customer(string name, string email, string address) + { + Guard.Against.NullOrEmpty(name, nameof(name)); + Guard.Against.NullOrEmpty(email, nameof(email)); - this.Name = name; - this.Email = email; - this.Address = address; - } + this.Name = name; + this.Email = email; + this.Address = address; + } - public Store GetStore(int storeId) - { - var store = Stores.FirstOrDefault(x => x.Id == storeId); + public Store GetStore(int storeId) + { + var store = Stores.FirstOrDefault(x => x.Id == storeId); - Guard.Against.Null(store, nameof(store)); + Guard.Against.Null(store, nameof(store)); - return store; - } + return store; + } - public Store AddStore(Store store) - { - Guard.Against.Null(store, nameof(store)); + public Store AddStore(Store store) + { + Guard.Against.Null(store, nameof(store)); - // Do some other operation while adding it. + // Do some other operation while adding it. - _stores.Add(store); + _stores.Add(store); - return store; - } + return store; + } - public void DeleteStore(int storeID) - { - var store = GetStore(storeID); + public void DeleteStore(int storeID) + { + var store = GetStore(storeID); - _stores.Remove(store); - } + _stores.Remove(store); } + } } diff --git a/sample/Ardalis.SampleApp.Core/Entities/CustomerAggregate/Store.cs b/sample/Ardalis.SampleApp.Core/Entities/CustomerAggregate/Store.cs index b8a1d736..7c2a7ee2 100644 --- a/sample/Ardalis.SampleApp.Core/Entities/CustomerAggregate/Store.cs +++ b/sample/Ardalis.SampleApp.Core/Entities/CustomerAggregate/Store.cs @@ -2,20 +2,20 @@ namespace Ardalis.SampleApp.Core.Entities.CustomerAggregate { - public class Store - { - public int Id { get; private set; } - public string Name { get; private set; } - public string Address { get; private set; } + public class Store + { + public int Id { get; private set; } + public string Name { get; private set; } + public string Address { get; private set; } - public int CustomerId { get; private set; } + public int CustomerId { get; private set; } - public Store(string name, string address) - { - Guard.Against.NullOrEmpty(name, nameof(name)); + public Store(string name, string address) + { + Guard.Against.NullOrEmpty(name, nameof(name)); - this.Name = name; - this.Address = address; - } + this.Name = name; + this.Address = address; } + } } diff --git a/sample/Ardalis.SampleApp.Core/Entities/Seeds/CustomerSeed.cs b/sample/Ardalis.SampleApp.Core/Entities/Seeds/CustomerSeed.cs index 6fc21a9b..6370e33a 100644 --- a/sample/Ardalis.SampleApp.Core/Entities/Seeds/CustomerSeed.cs +++ b/sample/Ardalis.SampleApp.Core/Entities/Seeds/CustomerSeed.cs @@ -3,22 +3,22 @@ namespace Ardalis.SampleApp.Core.Entities.Seeds { - public static class CustomerSeed + public static class CustomerSeed + { + public static List Seed() { - public static List Seed() - { - List output = new List(); + List output = new List(); - for (int i = 1; i <= 100000; i++) - { - var customer = new Customer($"Customer{i}", $"Email{i}@local", $"Customer{i} address"); - customer.AddStore(new Store($"Store{i}-1", $"Store{i}-1 address")); - customer.AddStore(new Store($"Store{i}-2", $"Store{i}-2 address")); + for (int i = 1; i <= 100000; i++) + { + var customer = new Customer($"Customer{i}", $"Email{i}@local", $"Customer{i} address"); + customer.AddStore(new Store($"Store{i}-1", $"Store{i}-1 address")); + customer.AddStore(new Store($"Store{i}-2", $"Store{i}-2 address")); - output.Add(customer); - } + output.Add(customer); + } - return output; - } + return output; } + } } diff --git a/sample/Ardalis.SampleApp.Core/Interfaces/IAggregateRoot.cs b/sample/Ardalis.SampleApp.Core/Interfaces/IAggregateRoot.cs index 5059e5c6..0b98eb7b 100644 --- a/sample/Ardalis.SampleApp.Core/Interfaces/IAggregateRoot.cs +++ b/sample/Ardalis.SampleApp.Core/Interfaces/IAggregateRoot.cs @@ -1,6 +1,6 @@ namespace Ardalis.SampleApp.Core.Interfaces { - public interface IAggregateRoot - { - } + public interface IAggregateRoot + { + } } diff --git a/sample/Ardalis.SampleApp.Core/Interfaces/ICustomerRepository.cs b/sample/Ardalis.SampleApp.Core/Interfaces/ICustomerRepository.cs index 463d2978..fb77ec20 100644 --- a/sample/Ardalis.SampleApp.Core/Interfaces/ICustomerRepository.cs +++ b/sample/Ardalis.SampleApp.Core/Interfaces/ICustomerRepository.cs @@ -1,12 +1,12 @@ -using Ardalis.SampleApp.Core.Entities.CustomerAggregate; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using Ardalis.SampleApp.Core.Entities.CustomerAggregate; namespace Ardalis.SampleApp.Core.Interfaces { - public interface ICustomerRepository - { - // This is just to demonstrate that at anytime you can create custom repositories, and use to create some complex queries working directly with EF or your ORM. - Task> GetCustomers(string addressSearchTerm); - } + public interface ICustomerRepository + { + // This is just to demonstrate that at anytime you can create custom repositories, and use to create some complex queries working directly with EF or your ORM. + Task> GetCustomers(string addressSearchTerm); + } } diff --git a/sample/Ardalis.SampleApp.Core/Interfaces/IRepository.cs b/sample/Ardalis.SampleApp.Core/Interfaces/IRepository.cs index d62e6c97..27b1013d 100644 --- a/sample/Ardalis.SampleApp.Core/Interfaces/IRepository.cs +++ b/sample/Ardalis.SampleApp.Core/Interfaces/IRepository.cs @@ -2,13 +2,13 @@ namespace Ardalis.SampleApp.Core.Interfaces { - /// - public interface IRepository : IRepositoryBase where T : class, IAggregateRoot - { - } + /// + public interface IRepository : IRepositoryBase where T : class, IAggregateRoot + { + } - /// - public interface IReadRepository : IReadRepositoryBase where T : class, IAggregateRoot - { - } + /// + public interface IReadRepository : IReadRepositoryBase where T : class, IAggregateRoot + { + } } diff --git a/sample/Ardalis.SampleApp.Core/Specifications/CustomerByNameSpec.cs b/sample/Ardalis.SampleApp.Core/Specifications/CustomerByNameSpec.cs index b2fb600b..8335f5a2 100644 --- a/sample/Ardalis.SampleApp.Core/Specifications/CustomerByNameSpec.cs +++ b/sample/Ardalis.SampleApp.Core/Specifications/CustomerByNameSpec.cs @@ -3,13 +3,13 @@ namespace Ardalis.SampleApp.Core.Specifications { - public class CustomerByNameSpec : Specification, ISingleResultSpecification + public class CustomerByNameSpec : Specification, ISingleResultSpecification + { + public CustomerByNameSpec(string name) { - public CustomerByNameSpec(string name) - { - Query.Where(x => x.Name == name) - .OrderBy(x => x.Name) - .ThenByDescending(x => x.Address); - } + Query.Where(x => x.Name == name) + .OrderBy(x => x.Name) + .ThenByDescending(x => x.Address); } + } } diff --git a/sample/Ardalis.SampleApp.Core/Specifications/CustomerByNameWithStoresSpec.cs b/sample/Ardalis.SampleApp.Core/Specifications/CustomerByNameWithStoresSpec.cs index db0e7395..6f9f9335 100644 --- a/sample/Ardalis.SampleApp.Core/Specifications/CustomerByNameWithStoresSpec.cs +++ b/sample/Ardalis.SampleApp.Core/Specifications/CustomerByNameWithStoresSpec.cs @@ -3,13 +3,13 @@ namespace Ardalis.SampleApp.Core.Specifications { - public class CustomerByNameWithStoresSpec : Specification, ISingleResultSpecification + public class CustomerByNameWithStoresSpec : Specification, ISingleResultSpecification + { + public CustomerByNameWithStoresSpec(string name) { - public CustomerByNameWithStoresSpec(string name) - { - Query.Where(x => x.Name == name) - .Include(x => x.Stores) - .EnableCache(nameof(CustomerByNameWithStoresSpec), name); - } + Query.Where(x => x.Name == name) + .Include(x => x.Stores) + .EnableCache(nameof(CustomerByNameWithStoresSpec), name); } + } } diff --git a/sample/Ardalis.SampleApp.Core/Specifications/CustomerSpec.cs b/sample/Ardalis.SampleApp.Core/Specifications/CustomerSpec.cs index 8fee9973..7cfe5522 100644 --- a/sample/Ardalis.SampleApp.Core/Specifications/CustomerSpec.cs +++ b/sample/Ardalis.SampleApp.Core/Specifications/CustomerSpec.cs @@ -4,28 +4,28 @@ namespace Ardalis.SampleApp.Core.Specifications { - public class CustomerSpec : Specification + public class CustomerSpec : Specification + { + public CustomerSpec(CustomerFilter filter) { - public CustomerSpec(CustomerFilter filter) - { - Query.OrderBy(x => x.Name) - .ThenByDescending(x => x.Address); + Query.OrderBy(x => x.Name) + .ThenByDescending(x => x.Address); - if (filter.LoadChildren) - Query.Include(x => x.Stores); + if (filter.LoadChildren) + Query.Include(x => x.Stores); - if (filter.IsPagingEnabled) - Query.Skip(PaginationHelper.CalculateSkip(filter)) - .Take(PaginationHelper.CalculateTake(filter)); + if (filter.IsPagingEnabled) + Query.Skip(PaginationHelper.CalculateSkip(filter)) + .Take(PaginationHelper.CalculateTake(filter)); - if (!string.IsNullOrEmpty(filter.Name)) - Query.Where(x => x.Name == filter.Name); + if (!string.IsNullOrEmpty(filter.Name)) + Query.Where(x => x.Name == filter.Name); - if (!string.IsNullOrEmpty(filter.Email)) - Query.Where(x => x.Email == filter.Email); + if (!string.IsNullOrEmpty(filter.Email)) + Query.Where(x => x.Email == filter.Email); - if (!string.IsNullOrEmpty(filter.Address)) - Query.Search(x => x.Address, "%" + filter.Address + "%"); - } + if (!string.IsNullOrEmpty(filter.Address)) + Query.Search(x => x.Address, "%" + filter.Address + "%"); } + } } diff --git a/sample/Ardalis.SampleApp.Core/Specifications/Filters/BaseFilter.cs b/sample/Ardalis.SampleApp.Core/Specifications/Filters/BaseFilter.cs index 5e753bfc..5cbae747 100644 --- a/sample/Ardalis.SampleApp.Core/Specifications/Filters/BaseFilter.cs +++ b/sample/Ardalis.SampleApp.Core/Specifications/Filters/BaseFilter.cs @@ -4,12 +4,12 @@ namespace Ardalis.SampleApp.Core.Specifications.Filters { - public class BaseFilter - { - public bool LoadChildren { get; set; } - public bool IsPagingEnabled { get; set; } + public class BaseFilter + { + public bool LoadChildren { get; set; } + public bool IsPagingEnabled { get; set; } - public int Page { get; set; } - public int PageSize { get; set; } - } + public int Page { get; set; } + public int PageSize { get; set; } + } } diff --git a/sample/Ardalis.SampleApp.Core/Specifications/Filters/CustomerFilter.cs b/sample/Ardalis.SampleApp.Core/Specifications/Filters/CustomerFilter.cs index 834ef3aa..10c4a13d 100644 --- a/sample/Ardalis.SampleApp.Core/Specifications/Filters/CustomerFilter.cs +++ b/sample/Ardalis.SampleApp.Core/Specifications/Filters/CustomerFilter.cs @@ -4,10 +4,10 @@ namespace Ardalis.SampleApp.Core.Specifications.Filters { - public class CustomerFilter : BaseFilter - { - public string Name { get; set; } - public string Email { get; set; } - public string Address { get; set; } - } + public class CustomerFilter : BaseFilter + { + public string Name { get; set; } + public string Email { get; set; } + public string Address { get; set; } + } } diff --git a/sample/Ardalis.SampleApp.Core/Specifications/PaginationHelper.cs b/sample/Ardalis.SampleApp.Core/Specifications/PaginationHelper.cs index 07895943..19dac0e9 100644 --- a/sample/Ardalis.SampleApp.Core/Specifications/PaginationHelper.cs +++ b/sample/Ardalis.SampleApp.Core/Specifications/PaginationHelper.cs @@ -2,29 +2,29 @@ namespace Ardalis.SampleApp.Core.Specifications { - public static class PaginationHelper - { - public static int DefaultPage => 1; - public static int DefaultPageSize => 10; + public static class PaginationHelper + { + public static int DefaultPage => 1; + public static int DefaultPageSize => 10; - public static int CalculateTake(int pageSize) - { - return pageSize <= 0 ? DefaultPageSize : pageSize; - } - public static int CalculateSkip(int pageSize, int page) - { - page = page <= 0 ? DefaultPage : page; + public static int CalculateTake(int pageSize) + { + return pageSize <= 0 ? DefaultPageSize : pageSize; + } + public static int CalculateSkip(int pageSize, int page) + { + page = page <= 0 ? DefaultPage : page; - return CalculateTake(pageSize) * (page - 1); - } + return CalculateTake(pageSize) * (page - 1); + } - public static int CalculateTake(BaseFilter baseFilter) - { - return CalculateTake(baseFilter.PageSize); - } - public static int CalculateSkip(BaseFilter baseFilter) - { - return CalculateSkip(baseFilter.PageSize, baseFilter.Page); - } + public static int CalculateTake(BaseFilter baseFilter) + { + return CalculateTake(baseFilter.PageSize); + } + public static int CalculateSkip(BaseFilter baseFilter) + { + return CalculateSkip(baseFilter.PageSize, baseFilter.Page); } + } } diff --git a/sample/Ardalis.SampleApp.Infrastructure/Data/CachedCustomerRepository.cs b/sample/Ardalis.SampleApp.Infrastructure/Data/CachedCustomerRepository.cs index 4ff37ab2..e43978a7 100644 --- a/sample/Ardalis.SampleApp.Infrastructure/Data/CachedCustomerRepository.cs +++ b/sample/Ardalis.SampleApp.Infrastructure/Data/CachedCustomerRepository.cs @@ -1,129 +1,128 @@ -using Ardalis.SampleApp.Core.Interfaces; -using Ardalis.Specification; -using Microsoft.Extensions.Caching.Memory; -using Microsoft.Extensions.Logging; -using System; +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Ardalis.SampleApp.Core.Interfaces; +using Ardalis.Specification; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging; -namespace Ardalis.SampleApp.Infrastructure.Data -{ - /// - public class CachedRepository : IReadRepository where T : class, IAggregateRoot - { - private readonly IMemoryCache _cache; - private readonly ILogger> _logger; - private readonly MyRepository _sourceRepository; - private MemoryCacheEntryOptions _cacheOptions; +namespace Ardalis.SampleApp.Infrastructure.Data; - public CachedRepository(IMemoryCache cache, - ILogger> logger, - MyRepository sourceRepository) - { - _cache = cache; - _logger = logger; - _sourceRepository = sourceRepository; +/// +public class CachedRepository : IReadRepository where T : class, IAggregateRoot +{ + private readonly IMemoryCache _cache; + private readonly ILogger> _logger; + private readonly MyRepository _sourceRepository; + private MemoryCacheEntryOptions _cacheOptions; - _cacheOptions = new MemoryCacheEntryOptions() - .SetAbsoluteExpiration(relative: TimeSpan.FromSeconds(10)); - } + public CachedRepository(IMemoryCache cache, + ILogger> logger, + MyRepository sourceRepository) + { + _cache = cache; + _logger = logger; + _sourceRepository = sourceRepository; - /// - public Task AnyAsync(Specification.ISpecification specification, CancellationToken cancellationToken = default) - { - // TODO: Add Caching - return _sourceRepository.AnyAsync(specification, cancellationToken); - } + _cacheOptions = new MemoryCacheEntryOptions() + .SetAbsoluteExpiration(relative: TimeSpan.FromSeconds(10)); + } - /// - public Task AnyAsync(CancellationToken cancellationToken = default) - { - // TODO: Add Caching - return _sourceRepository.AnyAsync(cancellationToken); - } + /// + public Task AnyAsync(Specification.ISpecification specification, CancellationToken cancellationToken = default) + { + // TODO: Add Caching + return _sourceRepository.AnyAsync(specification, cancellationToken); + } - /// - public Task CountAsync(Specification.ISpecification specification, CancellationToken cancellationToken = default) - { - // TODO: Add Caching - return _sourceRepository.CountAsync(specification, cancellationToken); - } + /// + public Task AnyAsync(CancellationToken cancellationToken = default) + { + // TODO: Add Caching + return _sourceRepository.AnyAsync(cancellationToken); + } - /// - public Task CountAsync(CancellationToken cancellationToken = default) - { - // TODO: Add Caching - return _sourceRepository.CountAsync(cancellationToken); - } + /// + public Task CountAsync(Specification.ISpecification specification, CancellationToken cancellationToken = default) + { + // TODO: Add Caching + return _sourceRepository.CountAsync(specification, cancellationToken); + } - /// - public Task GetByIdAsync(int id, CancellationToken cancellationToken = default) - { - return _sourceRepository.GetByIdAsync(id, cancellationToken); - } + /// + public Task CountAsync(CancellationToken cancellationToken = default) + { + // TODO: Add Caching + return _sourceRepository.CountAsync(cancellationToken); + } - /// - public Task GetByIdAsync(TId id, CancellationToken cancellationToken = default) - { - return _sourceRepository.GetByIdAsync(id, cancellationToken); - } + /// + public Task GetByIdAsync(int id, CancellationToken cancellationToken = default) + { + return _sourceRepository.GetByIdAsync(id, cancellationToken); + } - /// - public Task GetBySpecAsync(Spec specification, CancellationToken cancellationToken = default) where Spec : ISingleResultSpecification, ISpecification - { - if(specification.CacheEnabled) - { - string key = $"{specification.CacheKey}-GetBySpecAsync"; - _logger.LogInformation("Checking cache for " + key); - return _cache.GetOrCreate(key, entry => - { - entry.SetOptions(_cacheOptions); - _logger.LogWarning("Fetching source data for " + key); - return _sourceRepository.GetBySpecAsync(specification, cancellationToken); - }); - } - return _sourceRepository.GetBySpecAsync(specification, cancellationToken); - } + /// + public Task GetByIdAsync(TId id, CancellationToken cancellationToken = default) + { + return _sourceRepository.GetByIdAsync(id, cancellationToken); + } - /// - public Task GetBySpecAsync(Specification.ISpecification specification, CancellationToken cancellationToken = default) - { - throw new NotImplementedException(); - } + /// + public Task GetBySpecAsync(Spec specification, CancellationToken cancellationToken = default) where Spec : ISingleResultSpecification, ISpecification + { + if (specification.CacheEnabled) + { + string key = $"{specification.CacheKey}-GetBySpecAsync"; + _logger.LogInformation("Checking cache for " + key); + return _cache.GetOrCreate(key, entry => + { + entry.SetOptions(_cacheOptions); + _logger.LogWarning("Fetching source data for " + key); + return _sourceRepository.GetBySpecAsync(specification, cancellationToken); + }); + } + return _sourceRepository.GetBySpecAsync(specification, cancellationToken); + } - /// - public Task> ListAsync(CancellationToken cancellationToken = default) - { - string key = $"{nameof(T)}-ListAsync"; - return _cache.GetOrCreate(key, entry => - { - entry.SetOptions(_cacheOptions); - return _sourceRepository.ListAsync(cancellationToken); - }); - } + /// + public Task GetBySpecAsync(Specification.ISpecification specification, CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } - /// - public Task> ListAsync(Specification.ISpecification specification, CancellationToken cancellationToken = default) - { - if (specification.CacheEnabled) - { - string key = $"{specification.CacheKey}-ListAsync"; - _logger.LogInformation("Checking cache for " + key); - return _cache.GetOrCreate(key, entry => - { - entry.SetOptions(_cacheOptions); - _logger.LogWarning("Fetching source data for " + key); - return _sourceRepository.ListAsync(specification, cancellationToken); - }); - } - return _sourceRepository.ListAsync(specification, cancellationToken); - } + /// + public Task> ListAsync(CancellationToken cancellationToken = default) + { + string key = $"{nameof(T)}-ListAsync"; + return _cache.GetOrCreate(key, entry => + { + entry.SetOptions(_cacheOptions); + return _sourceRepository.ListAsync(cancellationToken); + }); + } - /// - public Task> ListAsync(Specification.ISpecification specification, CancellationToken cancellationToken = default) - { - throw new NotImplementedException(); - } + /// + public Task> ListAsync(Specification.ISpecification specification, CancellationToken cancellationToken = default) + { + if (specification.CacheEnabled) + { + string key = $"{specification.CacheKey}-ListAsync"; + _logger.LogInformation("Checking cache for " + key); + return _cache.GetOrCreate(key, entry => + { + entry.SetOptions(_cacheOptions); + _logger.LogWarning("Fetching source data for " + key); + return _sourceRepository.ListAsync(specification, cancellationToken); + }); } + return _sourceRepository.ListAsync(specification, cancellationToken); + } + + /// + public Task> ListAsync(Specification.ISpecification specification, CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } } diff --git a/sample/Ardalis.SampleApp.Infrastructure/Data/CustomerRepository.cs b/sample/Ardalis.SampleApp.Infrastructure/Data/CustomerRepository.cs index df3f3430..e30926ee 100644 --- a/sample/Ardalis.SampleApp.Infrastructure/Data/CustomerRepository.cs +++ b/sample/Ardalis.SampleApp.Infrastructure/Data/CustomerRepository.cs @@ -1,29 +1,28 @@ -using Ardalis.SampleApp.Core.Entities.CustomerAggregate; -using Ardalis.SampleApp.Core.Interfaces; -using Microsoft.EntityFrameworkCore; -using Ardalis.SampleApp.Infrastructure.DataAccess; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Ardalis.SampleApp.Core.Entities.CustomerAggregate; +using Ardalis.SampleApp.Core.Interfaces; +using Ardalis.SampleApp.Infrastructure.DataAccess; +using Microsoft.EntityFrameworkCore; + +namespace Ardalis.SampleApp.Infrastructure.Data; -namespace Ardalis.SampleApp.Infrastructure.Data +// This is just to demonstrate that at anytime you can create custom repositories, and use to create some complex queries working directly with EF or your ORM. +public class CustomerRepository : ICustomerRepository { - // This is just to demonstrate that at anytime you can create custom repositories, and use to create some complex queries working directly with EF or your ORM. - public class CustomerRepository : ICustomerRepository - { - private readonly SampleDbContext dbContext; + private readonly SampleDbContext dbContext; - public CustomerRepository(SampleDbContext dbContext) - { - this.dbContext = dbContext; - } + public CustomerRepository(SampleDbContext dbContext) + { + this.dbContext = dbContext; + } - public Task> GetCustomers(string addressSearchTerm) - { - return dbContext.Customers - .Take(10) - .Where(x => EF.Functions.Like(x.Address, "%" + addressSearchTerm + "%")) - .ToListAsync(); - } - } + public Task> GetCustomers(string addressSearchTerm) + { + return dbContext.Customers + .Take(10) + .Where(x => EF.Functions.Like(x.Address, "%" + addressSearchTerm + "%")) + .ToListAsync(); + } } diff --git a/sample/Ardalis.SampleApp.Infrastructure/Data/MyRepository.cs b/sample/Ardalis.SampleApp.Infrastructure/Data/MyRepository.cs index 40e0bd42..c4a26eba 100644 --- a/sample/Ardalis.SampleApp.Infrastructure/Data/MyRepository.cs +++ b/sample/Ardalis.SampleApp.Infrastructure/Data/MyRepository.cs @@ -1,19 +1,18 @@ -using Ardalis.SampleApp.Infrastructure.DataAccess; -using Ardalis.SampleApp.Core.Interfaces; +using Ardalis.SampleApp.Core.Interfaces; +using Ardalis.SampleApp.Infrastructure.DataAccess; using Ardalis.Specification.EntityFrameworkCore; -namespace Ardalis.SampleApp.Infrastructure.Data +namespace Ardalis.SampleApp.Infrastructure.Data; + +/// +public class MyRepository : RepositoryBase, IRepository where T : class, IAggregateRoot { - /// - public class MyRepository : RepositoryBase, IRepository where T : class, IAggregateRoot - { - private readonly SampleDbContext dbContext; + private readonly SampleDbContext dbContext; - public MyRepository(SampleDbContext dbContext) : base(dbContext) - { - this.dbContext = dbContext; - } + public MyRepository(SampleDbContext dbContext) : base(dbContext) + { + this.dbContext = dbContext; + } - // Not required to implement anything. Add additional functionalities if required. - } + // Not required to implement anything. Add additional functionalities if required. } diff --git a/sample/Ardalis.SampleApp.Infrastructure/DataAccess/Configurations/CustomerConfiguration.cs b/sample/Ardalis.SampleApp.Infrastructure/DataAccess/Configurations/CustomerConfiguration.cs index 1238169a..7ccd7c8b 100644 --- a/sample/Ardalis.SampleApp.Infrastructure/DataAccess/Configurations/CustomerConfiguration.cs +++ b/sample/Ardalis.SampleApp.Infrastructure/DataAccess/Configurations/CustomerConfiguration.cs @@ -1,22 +1,21 @@ -using Ardalis.SampleApp.Core.Entities.CustomerAggregate; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.SampleApp.Core.Entities.CustomerAggregate; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Ardalis.SampleApp.Infrastructure.DataAccess.Configurations; -namespace Ardalis.SampleApp.Infrastructure.DataAccess.Configurations +public class CustomerConfiguration : IEntityTypeConfiguration { - public class CustomerConfiguration : IEntityTypeConfiguration - { - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable(nameof(Customer)); + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable(nameof(Customer)); - builder.Metadata.FindNavigation(nameof(Customer.Stores)) - .SetPropertyAccessMode(PropertyAccessMode.Field); + builder.Metadata.FindNavigation(nameof(Customer.Stores)) + .SetPropertyAccessMode(PropertyAccessMode.Field); - builder.HasKey(x => x.Id); - } - } + builder.HasKey(x => x.Id); + } } diff --git a/sample/Ardalis.SampleApp.Infrastructure/DataAccess/Configurations/StoreConfiguration.cs b/sample/Ardalis.SampleApp.Infrastructure/DataAccess/Configurations/StoreConfiguration.cs index 9f79bc08..d847a1f2 100644 --- a/sample/Ardalis.SampleApp.Infrastructure/DataAccess/Configurations/StoreConfiguration.cs +++ b/sample/Ardalis.SampleApp.Infrastructure/DataAccess/Configurations/StoreConfiguration.cs @@ -1,19 +1,18 @@ -using Ardalis.SampleApp.Core.Entities.CustomerAggregate; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; -using System; +using System; using System.Collections.Generic; using System.Text; +using Ardalis.SampleApp.Core.Entities.CustomerAggregate; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Ardalis.SampleApp.Infrastructure.DataAccess.Configurations; -namespace Ardalis.SampleApp.Infrastructure.DataAccess.Configurations +public class StoreConfiguration : IEntityTypeConfiguration { - public class StoreConfiguration : IEntityTypeConfiguration - { - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable(nameof(Store)); + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable(nameof(Store)); - builder.HasKey(x => x.Id); - } - } + builder.HasKey(x => x.Id); + } } diff --git a/sample/Ardalis.SampleApp.Infrastructure/DataAccess/SampleDbContext.cs b/sample/Ardalis.SampleApp.Infrastructure/DataAccess/SampleDbContext.cs index a3fb95b8..7333d199 100644 --- a/sample/Ardalis.SampleApp.Infrastructure/DataAccess/SampleDbContext.cs +++ b/sample/Ardalis.SampleApp.Infrastructure/DataAccess/SampleDbContext.cs @@ -1,24 +1,23 @@ -using Microsoft.EntityFrameworkCore; +using Ardalis.SampleApp.Core.Entities.CustomerAggregate; using Ardalis.SampleApp.Infrastructure.DataAccess.Configurations; -using Ardalis.SampleApp.Core.Entities.CustomerAggregate; +using Microsoft.EntityFrameworkCore; -namespace Ardalis.SampleApp.Infrastructure.DataAccess +namespace Ardalis.SampleApp.Infrastructure.DataAccess; + +public class SampleDbContext : DbContext { - public class SampleDbContext : DbContext - { - public DbSet Customers { get; set; } + public DbSet Customers { get; set; } - public SampleDbContext(DbContextOptions options) - : base(options) - { - } + public SampleDbContext(DbContextOptions options) + : base(options) + { + } - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); - builder.ApplyConfiguration(new CustomerConfiguration()); - builder.ApplyConfiguration(new StoreConfiguration()); - } - } + builder.ApplyConfiguration(new CustomerConfiguration()); + builder.ApplyConfiguration(new StoreConfiguration()); + } } diff --git a/sample/Ardalis.SampleApp.Infrastructure/DataAccess/SampleDbContextSeed.cs b/sample/Ardalis.SampleApp.Infrastructure/DataAccess/SampleDbContextSeed.cs index 2f200ec5..ed0f400d 100644 --- a/sample/Ardalis.SampleApp.Infrastructure/DataAccess/SampleDbContextSeed.cs +++ b/sample/Ardalis.SampleApp.Infrastructure/DataAccess/SampleDbContextSeed.cs @@ -1,45 +1,44 @@ -using Ardalis.SampleApp.Core.Entities.Seeds; -using Microsoft.EntityFrameworkCore; -using System; +using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; +using Ardalis.SampleApp.Core.Entities.Seeds; +using Microsoft.EntityFrameworkCore; + +namespace Ardalis.SampleApp.Infrastructure.DataAccess; -namespace Ardalis.SampleApp.Infrastructure.DataAccess +public class SampleDbContextSeed { - public class SampleDbContextSeed + private readonly SampleDbContext dbContext; + + public SampleDbContextSeed(SampleDbContext dbContext) + { + this.dbContext = dbContext; + } + + public async Task SeedAsync(int retry = 0) + { + try { - private readonly SampleDbContext dbContext; + dbContext.Database.Migrate(); - public SampleDbContextSeed(SampleDbContext dbContext) + if (await dbContext.Customers.CountAsync() == 0) + { + foreach (var customer in CustomerSeed.Seed()) { - this.dbContext = dbContext; + dbContext.Customers.Add(customer); } + } - public async Task SeedAsync(int retry = 0) - { - try - { - dbContext.Database.Migrate(); + await dbContext.SaveChangesAsync(); - if (await dbContext.Customers.CountAsync() == 0) - { - foreach (var customer in CustomerSeed.Seed()) - { - dbContext.Customers.Add(customer); - } - } - - await dbContext.SaveChangesAsync(); - - } - catch (Exception) - { - if (retry > 0) - { - await SeedAsync(retry - 1); - } - } - } } + catch (Exception) + { + if (retry > 0) + { + await SeedAsync(retry - 1); + } + } + } } diff --git a/sample/Ardalis.SampleApp.Infrastructure/Migrations/20201102224526_SampleDB-v1.cs b/sample/Ardalis.SampleApp.Infrastructure/Migrations/20201102224526_SampleDB-v1.cs index ff1feaec..905c6a77 100644 --- a/sample/Ardalis.SampleApp.Infrastructure/Migrations/20201102224526_SampleDB-v1.cs +++ b/sample/Ardalis.SampleApp.Infrastructure/Migrations/20201102224526_SampleDB-v1.cs @@ -1,60 +1,59 @@ using Microsoft.EntityFrameworkCore.Migrations; -namespace Ardalis.SampleApp.Infrastructure.Migrations +namespace Ardalis.SampleApp.Infrastructure.Migrations; + +public partial class SampleDBv1 : Migration { - public partial class SampleDBv1 : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Customer", + columns: table => new + { + Id = table.Column(nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(nullable: true), + Email = table.Column(nullable: true), + Address = table.Column(nullable: true) + }, + constraints: table => { - migrationBuilder.CreateTable( - name: "Customer", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - Name = table.Column(nullable: true), - Email = table.Column(nullable: true), - Address = table.Column(nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Customer", x => x.Id); - }); + table.PrimaryKey("PK_Customer", x => x.Id); + }); - migrationBuilder.CreateTable( - name: "Store", - columns: table => new - { - Id = table.Column(nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - Name = table.Column(nullable: true), - Address = table.Column(nullable: true), - CustomerId = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Store", x => x.Id); - table.ForeignKey( - name: "FK_Store_Customer_CustomerId", - column: x => x.CustomerId, - principalTable: "Customer", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); + migrationBuilder.CreateTable( + name: "Store", + columns: table => new + { + Id = table.Column(nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(nullable: true), + Address = table.Column(nullable: true), + CustomerId = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Store", x => x.Id); + table.ForeignKey( + name: "FK_Store_Customer_CustomerId", + column: x => x.CustomerId, + principalTable: "Customer", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); - migrationBuilder.CreateIndex( - name: "IX_Store_CustomerId", - table: "Store", - column: "CustomerId"); - } + migrationBuilder.CreateIndex( + name: "IX_Store_CustomerId", + table: "Store", + column: "CustomerId"); + } - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Store"); + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Store"); - migrationBuilder.DropTable( - name: "Customer"); - } - } + migrationBuilder.DropTable( + name: "Customer"); + } } diff --git a/sample/Ardalis.SampleApp.Web/AutomapperMaps.cs b/sample/Ardalis.SampleApp.Web/AutomapperMaps.cs index 9204b412..28f86310 100644 --- a/sample/Ardalis.SampleApp.Web/AutomapperMaps.cs +++ b/sample/Ardalis.SampleApp.Web/AutomapperMaps.cs @@ -1,24 +1,23 @@ -using AutoMapper; -using Ardalis.SampleApp.Web.Models; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Ardalis.SampleApp.Core.Specifications.Filters; using Ardalis.SampleApp.Core.Entities.CustomerAggregate; +using Ardalis.SampleApp.Core.Specifications.Filters; +using Ardalis.SampleApp.Web.Models; +using AutoMapper; + +namespace Ardalis.SampleApp.Web; -namespace Ardalis.SampleApp.Web +public class AutomapperMaps : Profile { - public class AutomapperMaps : Profile - { - public AutomapperMaps() - { - CreateMap().IncludeAllDerived().ReverseMap(); - CreateMap().ReverseMap(); - - CreateMap(); - CreateMap(); - } - } + public AutomapperMaps() + { + CreateMap().IncludeAllDerived().ReverseMap(); + CreateMap().ReverseMap(); + + CreateMap(); + CreateMap(); + } } diff --git a/sample/Ardalis.SampleApp.Web/Controllers/CustomersController.cs b/sample/Ardalis.SampleApp.Web/Controllers/CustomersController.cs index 96b7716b..967a480d 100644 --- a/sample/Ardalis.SampleApp.Web/Controllers/CustomersController.cs +++ b/sample/Ardalis.SampleApp.Web/Controllers/CustomersController.cs @@ -1,45 +1,44 @@ -using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using System.Threading.Tasks; using Ardalis.SampleApp.Web.Interfaces; using Ardalis.SampleApp.Web.Models; -using System.Collections.Generic; -using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; + +namespace Ardalis.SampleApp.Web.Controllers; -namespace Ardalis.SampleApp.Web.Controllers +[ApiController] +[Route("[controller]")] +public class CustomersController : ControllerBase { - [ApiController] - [Route("[controller]")] - public class CustomersController : ControllerBase - { - private readonly ICustomerUiService customerUiService; - - public CustomersController(ICustomerUiService customerUiService) - { - this.customerUiService = customerUiService; - } - - [HttpGet("{Id}")] - public Task Get(int Id) - { - return customerUiService.GetCustomer(Id); - } - - [HttpGet("{name}")] - public Task Get(string name) - { - return customerUiService.GetCustomer(name); - } - - [HttpGet] - public Task> Get([FromQuery] CustomerFilterDto filter) - { - filter = filter ?? new CustomerFilterDto(); - - // Here you can decide if you want the collections as well - - filter.LoadChildren = true; - filter.IsPagingEnabled = true; - - return customerUiService.GetCustomers(filter); - } - } + private readonly ICustomerUiService customerUiService; + + public CustomersController(ICustomerUiService customerUiService) + { + this.customerUiService = customerUiService; + } + + [HttpGet("{Id}")] + public Task Get(int Id) + { + return customerUiService.GetCustomer(Id); + } + + [HttpGet("{name}")] + public Task Get(string name) + { + return customerUiService.GetCustomer(name); + } + + [HttpGet] + public Task> Get([FromQuery] CustomerFilterDto filter) + { + filter = filter ?? new CustomerFilterDto(); + + // Here you can decide if you want the collections as well + + filter.LoadChildren = true; + filter.IsPagingEnabled = true; + + return customerUiService.GetCustomers(filter); + } } diff --git a/sample/Ardalis.SampleApp.Web/Interfaces/ICustomerUiService.cs b/sample/Ardalis.SampleApp.Web/Interfaces/ICustomerUiService.cs index d36914a7..7dcff9ec 100644 --- a/sample/Ardalis.SampleApp.Web/Interfaces/ICustomerUiService.cs +++ b/sample/Ardalis.SampleApp.Web/Interfaces/ICustomerUiService.cs @@ -1,15 +1,14 @@ -using Ardalis.SampleApp.Web.Models; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using Ardalis.SampleApp.Web.Models; -namespace Ardalis.SampleApp.Web.Interfaces +namespace Ardalis.SampleApp.Web.Interfaces; + +public interface ICustomerUiService { - public interface ICustomerUiService - { - Task GetCustomer(int customerId); - Task GetCustomer(string customerName); - Task GetCustomerWithStores(string customerName); + Task GetCustomer(int customerId); + Task GetCustomer(string customerName); + Task GetCustomerWithStores(string customerName); - Task> GetCustomers(CustomerFilterDto filterDto); - } + Task> GetCustomers(CustomerFilterDto filterDto); } diff --git a/sample/Ardalis.SampleApp.Web/Models/BaseFilterDto.cs b/sample/Ardalis.SampleApp.Web/Models/BaseFilterDto.cs index db077f23..e66cb42d 100644 --- a/sample/Ardalis.SampleApp.Web/Models/BaseFilterDto.cs +++ b/sample/Ardalis.SampleApp.Web/Models/BaseFilterDto.cs @@ -5,19 +5,18 @@ using System.Text.Json.Serialization; using System.Threading.Tasks; -namespace Ardalis.SampleApp.Web.Models +namespace Ardalis.SampleApp.Web.Models; + +public class BaseFilterDto { - public class BaseFilterDto - { - [Browsable(false)] - [JsonIgnore] - public bool LoadChildren { get; set; } = false; + [Browsable(false)] + [JsonIgnore] + public bool LoadChildren { get; set; } = false; - [Browsable(false)] - [JsonIgnore] - public bool IsPagingEnabled { get; set; } = true; + [Browsable(false)] + [JsonIgnore] + public bool IsPagingEnabled { get; set; } = true; - public int Page { get; set; } = 1; - public int PageSize { get; set; } = 10; - } + public int Page { get; set; } = 1; + public int PageSize { get; set; } = 10; } diff --git a/sample/Ardalis.SampleApp.Web/Models/CustomerDto.cs b/sample/Ardalis.SampleApp.Web/Models/CustomerDto.cs index 88da2e61..ef030aed 100644 --- a/sample/Ardalis.SampleApp.Web/Models/CustomerDto.cs +++ b/sample/Ardalis.SampleApp.Web/Models/CustomerDto.cs @@ -3,15 +3,14 @@ using System.Linq; using System.Threading.Tasks; -namespace Ardalis.SampleApp.Web.Models +namespace Ardalis.SampleApp.Web.Models; + +public class CustomerDto { - public class CustomerDto - { - public int Id { get; set; } - public string Name { get; set; } - public string Email { get; set; } - public string Address { get; set; } + public int Id { get; set; } + public string Name { get; set; } + public string Email { get; set; } + public string Address { get; set; } - public List Stores { get; set; } = new List(); - } + public List Stores { get; set; } = new List(); } diff --git a/sample/Ardalis.SampleApp.Web/Models/CustomerFilterDto.cs b/sample/Ardalis.SampleApp.Web/Models/CustomerFilterDto.cs index c2ec64e5..c2bcc00c 100644 --- a/sample/Ardalis.SampleApp.Web/Models/CustomerFilterDto.cs +++ b/sample/Ardalis.SampleApp.Web/Models/CustomerFilterDto.cs @@ -5,12 +5,11 @@ using System.Text.Json.Serialization; using System.Threading.Tasks; -namespace Ardalis.SampleApp.Web.Models +namespace Ardalis.SampleApp.Web.Models; + +public class CustomerFilterDto : BaseFilterDto { - public class CustomerFilterDto : BaseFilterDto - { - public string Name { get; set; } - public string Email { get; set; } - public string Address { get; set; } - } + public string Name { get; set; } + public string Email { get; set; } + public string Address { get; set; } } diff --git a/sample/Ardalis.SampleApp.Web/Models/StoreDto.cs b/sample/Ardalis.SampleApp.Web/Models/StoreDto.cs index 17ca297f..cfd8cdb5 100644 --- a/sample/Ardalis.SampleApp.Web/Models/StoreDto.cs +++ b/sample/Ardalis.SampleApp.Web/Models/StoreDto.cs @@ -3,12 +3,11 @@ using System.Linq; using System.Threading.Tasks; -namespace Ardalis.SampleApp.Web.Models +namespace Ardalis.SampleApp.Web.Models; + +public class StoreDto { - public class StoreDto - { - public int Id { get; set; } - public string Name { get; set; } - public string Address { get; set; } - } + public int Id { get; set; } + public string Name { get; set; } + public string Address { get; set; } } diff --git a/sample/Ardalis.SampleApp.Web/Pages/Index.cshtml.cs b/sample/Ardalis.SampleApp.Web/Pages/Index.cshtml.cs index 9a84bf7b..42678637 100644 --- a/sample/Ardalis.SampleApp.Web/Pages/Index.cshtml.cs +++ b/sample/Ardalis.SampleApp.Web/Pages/Index.cshtml.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Ardalis.SampleApp.Core.Entities.CustomerAggregate; @@ -7,30 +7,29 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; -namespace Ardalis.SampleApp.Web.Pages +namespace Ardalis.SampleApp.Web.Pages; + +public class IndexModel : PageModel { - public class IndexModel : PageModel - { - private readonly IReadRepository _customerRepository; - private readonly ILogger _logger; + private readonly IReadRepository _customerRepository; + private readonly ILogger _logger; - public IndexModel(IReadRepository customerRepository, - ILogger logger) - { - _customerRepository = customerRepository; - _logger = logger; - } + public IndexModel(IReadRepository customerRepository, + ILogger logger) + { + _customerRepository = customerRepository; + _logger = logger; + } - public List Customers { get; set; } - public long ElapsedTimeMilliseconds { get; set; } + public List Customers { get; set; } + public long ElapsedTimeMilliseconds { get; set; } - public async Task OnGet() - { - var timer = Stopwatch.StartNew(); - var spec = new CustomerByNameWithStoresSpec(name: "Customer66"); - Customers = await _customerRepository.ListAsync(spec); - timer.Stop(); - ElapsedTimeMilliseconds = timer.ElapsedMilliseconds; - } - } + public async Task OnGet() + { + var timer = Stopwatch.StartNew(); + var spec = new CustomerByNameWithStoresSpec(name: "Customer66"); + Customers = await _customerRepository.ListAsync(spec); + timer.Stop(); + ElapsedTimeMilliseconds = timer.ElapsedMilliseconds; + } } diff --git a/sample/Ardalis.SampleApp.Web/Program.cs b/sample/Ardalis.SampleApp.Web/Program.cs index 94b9e79a..42c02c07 100644 --- a/sample/Ardalis.SampleApp.Web/Program.cs +++ b/sample/Ardalis.SampleApp.Web/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using Ardalis.SampleApp.Infrastructure.DataAccess; using Microsoft.AspNetCore.Hosting; @@ -6,38 +6,37 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -namespace Ardalis.SampleApp.Web +namespace Ardalis.SampleApp.Web; + +public class Program { - public class Program - { - public static async Task Main(string[] args) - { - var host = CreateHostBuilder(args).Build(); + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); - using (var scope = host.Services.CreateScope()) - { - var services = scope.ServiceProvider; - try - { - var dbContext = services.GetRequiredService(); + using (var scope = host.Services.CreateScope()) + { + var services = scope.ServiceProvider; + try + { + var dbContext = services.GetRequiredService(); - await new SampleDbContextSeed(dbContext).SeedAsync(); - } - catch (Exception) - { - } - } + await new SampleDbContextSeed(dbContext).SeedAsync(); + } + catch (Exception) + { + } + } - host.Run(); - } + host.Run(); + } - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.ConfigureLogging(config => - config.AddConsole()); - webBuilder.UseStartup(); - }); - } + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.ConfigureLogging(config => + config.AddConsole()); + webBuilder.UseStartup(); + }); } diff --git a/sample/Ardalis.SampleApp.Web/Services/CustomerUiService.cs b/sample/Ardalis.SampleApp.Web/Services/CustomerUiService.cs index 5e98c967..018be348 100644 --- a/sample/Ardalis.SampleApp.Web/Services/CustomerUiService.cs +++ b/sample/Ardalis.SampleApp.Web/Services/CustomerUiService.cs @@ -1,64 +1,63 @@ -using AutoMapper; -using Ardalis.SampleApp.Web.Interfaces; -using Ardalis.SampleApp.Web.Models; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; -using Ardalis.SampleApp.Core.Specifications; -using Ardalis.SampleApp.Core.Interfaces; -using Ardalis.SampleApp.Core.Entities.CustomerAggregate; using Ardalis.GuardClauses; +using Ardalis.SampleApp.Core.Entities.CustomerAggregate; +using Ardalis.SampleApp.Core.Interfaces; +using Ardalis.SampleApp.Core.Specifications; using Ardalis.SampleApp.Core.Specifications.Filters; +using Ardalis.SampleApp.Web.Interfaces; +using Ardalis.SampleApp.Web.Models; +using AutoMapper; + +namespace Ardalis.SampleApp.Web.Services; -namespace Ardalis.SampleApp.Web.Services +public class CustomerUiService : ICustomerUiService { - public class CustomerUiService : ICustomerUiService - { - private readonly IMapper mapper; - private readonly IReadRepository customerRepository; + private readonly IMapper mapper; + private readonly IReadRepository customerRepository; - public CustomerUiService(IMapper mapper, - IReadRepository customerRepository) - { - this.mapper = mapper; - this.customerRepository = customerRepository; - } + public CustomerUiService(IMapper mapper, + IReadRepository customerRepository) + { + this.mapper = mapper; + this.customerRepository = customerRepository; + } - // Here I'm just writing various usages, not necessarily you'll need all of them. + // Here I'm just writing various usages, not necessarily you'll need all of them. - public async Task GetCustomer(int customerId) - { - var customer = await customerRepository.GetByIdAsync(customerId); + public async Task GetCustomer(int customerId) + { + var customer = await customerRepository.GetByIdAsync(customerId); - Guard.Against.Null(customer, nameof(customer)); + Guard.Against.Null(customer, nameof(customer)); - return mapper.Map(customer); - } + return mapper.Map(customer); + } - public async Task GetCustomer(string customerName) - { - var customer = await customerRepository.GetBySpecAsync(new CustomerByNameSpec(customerName)); + public async Task GetCustomer(string customerName) + { + var customer = await customerRepository.GetBySpecAsync(new CustomerByNameSpec(customerName)); - Guard.Against.Null(customer, nameof(customer)); + Guard.Against.Null(customer, nameof(customer)); - return mapper.Map(customer); - } + return mapper.Map(customer); + } - public async Task GetCustomerWithStores(string customerName) - { - var customer = await customerRepository.GetBySpecAsync(new CustomerByNameWithStoresSpec(customerName)); + public async Task GetCustomerWithStores(string customerName) + { + var customer = await customerRepository.GetBySpecAsync(new CustomerByNameWithStoresSpec(customerName)); - Guard.Against.Null(customer, nameof(customer)); + Guard.Against.Null(customer, nameof(customer)); - return mapper.Map(customer); - } + return mapper.Map(customer); + } - public async Task> GetCustomers(CustomerFilterDto filterDto) - { - var spec = new CustomerSpec(mapper.Map(filterDto)); - var customers = await customerRepository.ListAsync(spec); + public async Task> GetCustomers(CustomerFilterDto filterDto) + { + var spec = new CustomerSpec(mapper.Map(filterDto)); + var customers = await customerRepository.ListAsync(spec); - return mapper.Map>(customers); - } - } + return mapper.Map>(customers); + } } diff --git a/sample/Ardalis.SampleApp.Web/Startup.cs b/sample/Ardalis.SampleApp.Web/Startup.cs index 36dad77d..a1b2b70f 100644 --- a/sample/Ardalis.SampleApp.Web/Startup.cs +++ b/sample/Ardalis.SampleApp.Web/Startup.cs @@ -1,4 +1,4 @@ -using Ardalis.SampleApp.Core.Interfaces; +using Ardalis.SampleApp.Core.Interfaces; using Ardalis.SampleApp.Infrastructure.Data; using Ardalis.SampleApp.Infrastructure.DataAccess; using Ardalis.SampleApp.Web.Interfaces; @@ -10,52 +10,51 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -namespace Ardalis.SampleApp.Web +namespace Ardalis.SampleApp.Web; + +public class Startup { - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("MyDbConnection"))); + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("MyDbConnection"))); - services.AddAutoMapper(typeof(AutomapperMaps)); + services.AddAutoMapper(typeof(AutomapperMaps)); - services.AddScoped(typeof(IReadRepository<>), typeof(CachedRepository<>)); - services.AddScoped(typeof(MyRepository<>)); - services.AddScoped(); + services.AddScoped(typeof(IReadRepository<>), typeof(CachedRepository<>)); + services.AddScoped(typeof(MyRepository<>)); + services.AddScoped(); -// services.AddControllers(); - services.AddMvc(); - services.AddLogging(); - } + // services.AddControllers(); + services.AddMvc(); + services.AddLogging(); + } - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } - app.UseHttpsRedirection(); + app.UseHttpsRedirection(); - app.UseRouting(); + app.UseRouting(); - app.UseAuthorization(); + app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - endpoints.MapRazorPages(); - }); - } - } + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + endpoints.MapRazorPages(); + }); + } }