├── .gitattributes ├── .gitignore ├── EntityFrameworkCore.IncludeFilter.sln ├── EntityFrameworkCore.IncludeFilter ├── DbContextOptionsBuilderExtensions.cs ├── EntityFrameworkCore.IncludeFilter.csproj ├── ExpressionExtensions.cs ├── QueryableExtensions.cs ├── ReplaceIncludeExpressionNode.cs ├── ReplaceMethodInfoBasedNodeTypeRegistryFactory.cs ├── ReplaceModelExpressionApplyingExpressionVisitor.cs ├── ReplaceRelationalQueryModelVisitor.cs ├── ReplaceRelationalQueryModelVisitorFactory.cs └── ReplaceThenIncludeExpressionNode.cs ├── LICENSE.txt ├── NOTICE.txt ├── README.md └── global.json /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | 85 | # Visual Studio profiler 86 | *.psess 87 | *.vsp 88 | *.vspx 89 | *.sap 90 | 91 | # TFS 2012 Local Workspace 92 | $tf/ 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | *.DotSettings.user 101 | 102 | # JustCode is a .NET coding add-in 103 | .JustCode 104 | 105 | # TeamCity is a build add-in 106 | _TeamCity* 107 | 108 | # DotCover is a Code Coverage Tool 109 | *.dotCover 110 | 111 | # NCrunch 112 | _NCrunch_* 113 | .*crunch*.local.xml 114 | nCrunchTemp_* 115 | 116 | # MightyMoose 117 | *.mm.* 118 | AutoTest.Net/ 119 | 120 | # Web workbench (sass) 121 | .sass-cache/ 122 | 123 | # Installshield output folder 124 | [Ee]xpress/ 125 | 126 | # DocProject is a documentation generator add-in 127 | DocProject/buildhelp/ 128 | DocProject/Help/*.HxT 129 | DocProject/Help/*.HxC 130 | DocProject/Help/*.hhc 131 | DocProject/Help/*.hhk 132 | DocProject/Help/*.hhp 133 | DocProject/Help/Html2 134 | DocProject/Help/html 135 | 136 | # Click-Once directory 137 | publish/ 138 | 139 | # Publish Web Output 140 | *.[Pp]ublish.xml 141 | *.azurePubxml 142 | 143 | # TODO: Un-comment the next line if you do not want to checkin 144 | # your web deploy settings because they may include unencrypted 145 | # passwords 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # NuGet Packages 150 | *.nupkg 151 | # The packages folder can be ignored because of Package Restore 152 | **/packages/* 153 | # except build/, which is used as an MSBuild target. 154 | !**/packages/build/ 155 | # Uncomment if necessary however generally it will be regenerated when needed 156 | #!**/packages/repositories.config 157 | # NuGet v3's project.json files produces more ignoreable files 158 | *.nuget.props 159 | *.nuget.targets 160 | 161 | # Microsoft Azure Build Output 162 | csx/ 163 | *.build.csdef 164 | 165 | # Microsoft Azure Emulator 166 | ecf/ 167 | rcf/ 168 | 169 | # Windows Store app package directory 170 | AppPackages/ 171 | BundleArtifacts/ 172 | 173 | # Visual Studio cache files 174 | # files ending in .cache can be ignored 175 | *.[Cc]ache 176 | # but keep track of directories ending in .cache 177 | !*.[Cc]ache/ 178 | 179 | # Others 180 | ClientBin/ 181 | [Ss]tyle[Cc]op.* 182 | ~$* 183 | *~ 184 | *.dbmdl 185 | *.dbproj.schemaview 186 | *.pfx 187 | *.publishsettings 188 | node_modules/ 189 | orleans.codegen.cs 190 | 191 | # RIA/Silverlight projects 192 | Generated_Code/ 193 | 194 | # Backup & report files from converting an old project file 195 | # to a newer Visual Studio version. Backup files are not needed, 196 | # because we have git ;-) 197 | _UpgradeReport_Files/ 198 | Backup*/ 199 | UpgradeLog*.XML 200 | UpgradeLog*.htm 201 | 202 | # SQL Server files 203 | *.mdf 204 | *.ldf 205 | 206 | # Business Intelligence projects 207 | *.rdl.data 208 | *.bim.layout 209 | *.bim_*.settings 210 | 211 | # Microsoft Fakes 212 | FakesAssemblies/ 213 | 214 | # GhostDoc plugin setting file 215 | *.GhostDoc.xml 216 | 217 | # Node.js Tools for Visual Studio 218 | .ntvs_analysis.dat 219 | 220 | # Visual Studio 6 build log 221 | *.plg 222 | 223 | # Visual Studio 6 workspace options file 224 | *.opt 225 | 226 | # Visual Studio LightSwitch build output 227 | **/*.HTMLClient/GeneratedArtifacts 228 | **/*.DesktopClient/GeneratedArtifacts 229 | **/*.DesktopClient/ModelManifest.xml 230 | **/*.Server/GeneratedArtifacts 231 | **/*.Server/ModelManifest.xml 232 | _Pvt_Extensions 233 | 234 | # LightSwitch generated files 235 | GeneratedArtifacts/ 236 | ModelManifest.xml 237 | 238 | # Paket dependency manager 239 | .paket/paket.exe 240 | 241 | # FAKE - F# Make 242 | .fake/ 243 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27703.2035 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EntityFrameworkCore.IncludeFilter", "EntityFrameworkCore.IncludeFilter\EntityFrameworkCore.IncludeFilter.csproj", "{142A08D4-2955-42BE-87D0-BFB38BE0ADBC}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {142A08D4-2955-42BE-87D0-BFB38BE0ADBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {142A08D4-2955-42BE-87D0-BFB38BE0ADBC}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {142A08D4-2955-42BE-87D0-BFB38BE0ADBC}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {142A08D4-2955-42BE-87D0-BFB38BE0ADBC}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {775A34E0-E7B5-4B49-B1FF-6CEF0E63EC7C} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter/DbContextOptionsBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Query; 3 | using Microsoft.EntityFrameworkCore.Query.Internal; 4 | 5 | namespace EntityFrameworkCore.IncludeFilter 6 | { 7 | public static class DbContextOptionsBuilderExtensions 8 | { 9 | public static DbContextOptionsBuilder AddIncludeWithFilterMethods(this DbContextOptionsBuilder builder) 10 | { 11 | return builder.ReplaceService() 12 | .ReplaceService(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter/EntityFrameworkCore.IncludeFilter.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | SAK 5 | SAK 6 | SAK 7 | SAK 8 | 9 | 10 | 11 | netcoreapp2.1 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter/ExpressionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | using System.Reflection; 7 | using System.Text; 8 | 9 | namespace EntityFrameworkCore.IncludeFilter 10 | { 11 | public static class ExpressionExtensions 12 | { 13 | public static bool TryGetComplexPropertyAccess(this LambdaExpression propertyAccessExpression, out IReadOnlyList propertyPath) 14 | { 15 | Debug.Assert(propertyAccessExpression.Parameters.Count == 1); 16 | 17 | propertyPath 18 | = propertyAccessExpression 19 | .Parameters 20 | .Single() 21 | .MatchPropertyAccess(propertyAccessExpression.Body); 22 | 23 | return propertyPath != null; 24 | } 25 | 26 | private static IReadOnlyList MatchPropertyAccess( 27 | this Expression parameterExpression, Expression propertyAccessExpression) 28 | { 29 | var propertyInfos = new List(); 30 | 31 | MemberExpression memberExpression; 32 | 33 | do 34 | { 35 | memberExpression = RemoveTypeAs(RemoveConvert(propertyAccessExpression)) as MemberExpression; 36 | 37 | var propertyInfo = memberExpression?.Member as PropertyInfo; 38 | 39 | if (propertyInfo == null) 40 | { 41 | return null; 42 | } 43 | 44 | propertyInfos.Insert(0, propertyInfo); 45 | 46 | propertyAccessExpression = memberExpression.Expression; 47 | } 48 | 49 | while (RemoveTypeAs(RemoveConvert(memberExpression.Expression)) != parameterExpression); 50 | 51 | return propertyInfos; 52 | } 53 | 54 | public static Expression RemoveTypeAs(this Expression expression) 55 | { 56 | while (expression != null 57 | && (expression.NodeType == ExpressionType.TypeAs)) 58 | { 59 | expression = RemoveConvert(((UnaryExpression)expression).Operand); 60 | } 61 | 62 | return expression; 63 | } 64 | 65 | public static Expression RemoveConvert(this Expression expression) 66 | { 67 | while (expression != null 68 | && (expression.NodeType == ExpressionType.Convert 69 | || expression.NodeType == ExpressionType.ConvertChecked)) 70 | { 71 | expression = RemoveConvert(((UnaryExpression)expression).Operand); 72 | } 73 | 74 | return expression; 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter/QueryableExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | using System.Reflection; 7 | using Microsoft.EntityFrameworkCore.Query; 8 | 9 | namespace EntityFrameworkCore.IncludeFilter 10 | { 11 | public static class QueryableExtensions 12 | { 13 | internal static readonly MethodInfo IncludeMethodInfo = 14 | typeof(QueryableExtensions).GetTypeInfo().GetDeclaredMethods(nameof(IncludeWithFilter)).Single(mi => mi.GetParameters().Any(pi => pi.Name == "navigationPropertyPath")); 15 | 16 | public static IIncludableQueryable> IncludeWithFilter(this IQueryable source 17 | , Expression>> navigationPropertyPath 18 | , Expression> filter) 19 | where TEntity : class 20 | { 21 | return new IncludableQueryable>( 22 | source.Provider.CreateQuery( 23 | Expression.Call( 24 | null, 25 | IncludeMethodInfo.MakeGenericMethod(typeof(TEntity), typeof(TProperty)), 26 | new[] { source.Expression, Expression.Quote(navigationPropertyPath), filter }))); 27 | } 28 | 29 | public static IIncludableQueryable> ThenIncludeWithFilter(this IIncludableQueryable> source 31 | , Expression>> navigationPropertyPath 32 | , Expression> filter) 33 | where TEntity : class 34 | { 35 | return new IncludableQueryable>( 36 | source.Provider.CreateQuery( 37 | Expression.Call( 38 | null, 39 | ThenIncludeAfterEnumerableMethodInfo.MakeGenericMethod(typeof(TEntity), typeof(TPreviousProperty), typeof(TProperty)), 40 | new[] { source.Expression, Expression.Quote(navigationPropertyPath), filter }))); 41 | } 42 | 43 | public static IIncludableQueryable> ThenIncludeWithFilter(this IIncludableQueryable source 45 | , Expression>> navigationPropertyPath 46 | , Expression> filter) 47 | where TEntity : class 48 | { 49 | return new IncludableQueryable>( 50 | source.Provider.CreateQuery( 51 | Expression.Call( 52 | null, 53 | ThenIncludeAfterReferenceMethodInfo.MakeGenericMethod(typeof(TEntity), typeof(TPreviousProperty), typeof(TProperty)), 54 | new[] { source.Expression, Expression.Quote(navigationPropertyPath), filter }))); 55 | } 56 | 57 | internal static readonly MethodInfo ThenIncludeAfterEnumerableMethodInfo 58 | = typeof(QueryableExtensions) 59 | .GetTypeInfo().GetDeclaredMethods(nameof(ThenIncludeWithFilter)) 60 | .Single(mi => !mi.GetParameters()[0].ParameterType.GenericTypeArguments[1].IsGenericParameter); 61 | 62 | internal static readonly MethodInfo ThenIncludeAfterReferenceMethodInfo 63 | = typeof(QueryableExtensions) 64 | .GetTypeInfo().GetDeclaredMethods(nameof(ThenIncludeWithFilter)) 65 | .Single(mi => mi.GetParameters()[0].ParameterType.GenericTypeArguments[1].IsGenericParameter); 66 | 67 | 68 | private class IncludableQueryable : IIncludableQueryable, IAsyncEnumerable 69 | { 70 | private readonly IQueryable _queryable; 71 | 72 | public IncludableQueryable(IQueryable queryable) 73 | { 74 | _queryable = queryable; 75 | } 76 | 77 | public Expression Expression => _queryable.Expression; 78 | public Type ElementType => _queryable.ElementType; 79 | public IQueryProvider Provider => _queryable.Provider; 80 | 81 | public IEnumerator GetEnumerator() => _queryable.GetEnumerator(); 82 | 83 | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); 84 | 85 | IAsyncEnumerator IAsyncEnumerable.GetEnumerator() 86 | => ((IAsyncEnumerable)_queryable).GetEnumerator(); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter/ReplaceIncludeExpressionNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.EntityFrameworkCore.Internal; 8 | using Microsoft.EntityFrameworkCore.Query.ResultOperators.Internal; 9 | using Remotion.Linq.Clauses; 10 | using Remotion.Linq.Parsing.Structure.IntermediateModel; 11 | 12 | namespace EntityFrameworkCore.IncludeFilter 13 | { 14 | public class ReplaceIncludeExpressionNode : IncludeExpressionNodeBase 15 | { 16 | public static readonly IReadOnlyCollection SupportedMethods = new[] 17 | { 18 | QueryableExtensions.IncludeMethodInfo, 19 | 20 | typeof(EntityFrameworkQueryableExtensions) 21 | .GetTypeInfo().GetDeclaredMethods("Include") 22 | .Single(mi => mi.GetGenericArguments().Count() == 2 23 | && mi.GetParameters() 24 | .Any(pi => pi.Name == "navigationPropertyPath" && pi.ParameterType != typeof(string))) 25 | }; 26 | 27 | private readonly LambdaExpression _filter; 28 | 29 | public ReplaceIncludeExpressionNode(MethodCallExpressionParseInfo parseInfo, LambdaExpression navigationPropertyPathLambda, LambdaExpression filter = null) 30 | : base(parseInfo, navigationPropertyPathLambda) 31 | { 32 | _filter = filter; 33 | } 34 | 35 | protected override ResultOperatorBase CreateResultOperator(ClauseGenerationContext clauseGenerationContext) 36 | { 37 | var prm = Expression.Parameter(typeof(object)); 38 | var pathFromQuerySource = Resolve(prm, prm, clauseGenerationContext); 39 | 40 | if (!NavigationPropertyPathLambda.TryGetComplexPropertyAccess(out var propertyPath)) 41 | { 42 | throw new InvalidOperationException( 43 | CoreStrings.InvalidIncludeLambdaExpression( 44 | nameof(EntityFrameworkQueryableExtensions.Include), 45 | NavigationPropertyPathLambda)); 46 | } 47 | 48 | Dictionary> filters; 49 | 50 | if (_filter == null) 51 | { 52 | filters = new Dictionary>(); 53 | } 54 | else 55 | { 56 | var type = _filter.Parameters[0].Type; 57 | filters = new Dictionary> 58 | { 59 | {type, new List() {_filter}} 60 | }; 61 | } 62 | 63 | var includeResultOperator = new ReplaceIncludeResultOperator(propertyPath.Select(p => p.Name), pathFromQuerySource, filters); 64 | clauseGenerationContext.AddContextInfo(this, includeResultOperator); 65 | return includeResultOperator; 66 | } 67 | } 68 | 69 | public class ReplaceIncludeResultOperator : IncludeResultOperator 70 | { 71 | public KeyValuePair Expression { get; set; } 72 | public Dictionary> Filters { get; set; } 73 | 74 | public ReplaceIncludeResultOperator(IEnumerable navigationPropertyPaths, Expression pathFromQuerySource, Dictionary> filters) 75 | : base(navigationPropertyPaths, pathFromQuerySource) 76 | { 77 | Filters = filters; 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter/ReplaceMethodInfoBasedNodeTypeRegistryFactory.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Query.Internal; 2 | using Remotion.Linq.Parsing.Structure; 3 | 4 | namespace EntityFrameworkCore.IncludeFilter 5 | { 6 | public class ReplaceMethodInfoBasedNodeTypeRegistryFactory : DefaultMethodInfoBasedNodeTypeRegistryFactory 7 | { 8 | public override INodeTypeProvider Create() 9 | { 10 | // Summary: 11 | // Registers the specific methods with the given nodeType. The given methods must 12 | // either be non-generic or open generic method definitions. If a method has already 13 | // been registered before, the later registration overwrites the earlier one. 14 | var provider = base.Create(); 15 | RegisterMethods(ReplaceIncludeExpressionNode.SupportedMethods, typeof(ReplaceIncludeExpressionNode)); 16 | RegisterMethods(ReplaceThenIncludeExpressionNode.SupportedMethods, typeof(ReplaceThenIncludeExpressionNode)); 17 | return provider; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter/ReplaceModelExpressionApplyingExpressionVisitor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | using System.Text; 7 | using Microsoft.EntityFrameworkCore; 8 | using Microsoft.EntityFrameworkCore.Internal; 9 | using Microsoft.EntityFrameworkCore.Query; 10 | using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal; 11 | using Microsoft.EntityFrameworkCore.Query.Internal; 12 | using Remotion.Linq; 13 | using Remotion.Linq.Clauses; 14 | using Remotion.Linq.Clauses.Expressions; 15 | using Remotion.Linq.Parsing; 16 | using Remotion.Linq.Parsing.ExpressionVisitors; 17 | 18 | namespace EntityFrameworkCore.IncludeFilter 19 | { 20 | public class ReplaceModelExpressionApplyingExpressionVisitor : ModelExpressionApplyingExpressionVisitor 21 | { 22 | private readonly QueryCompilationContext _queryCompilationContext; 23 | private readonly IQueryModelGenerator _queryModelGenerator; 24 | private readonly EntityQueryModelVisitor _entityQueryModelVisitor; 25 | 26 | private readonly Parameters _parameters = new Parameters(); 27 | 28 | private IQuerySource _querySource; 29 | 30 | public ReplaceModelExpressionApplyingExpressionVisitor( 31 | QueryCompilationContext queryCompilationContext, 32 | IQueryModelGenerator queryModelGenerator, 33 | EntityQueryModelVisitor entityQueryModelVisitor) : base(queryCompilationContext, queryModelGenerator, entityQueryModelVisitor) 34 | { 35 | _queryCompilationContext = queryCompilationContext; 36 | _queryModelGenerator = queryModelGenerator; 37 | _entityQueryModelVisitor = entityQueryModelVisitor; 38 | } 39 | 40 | public virtual bool IsViewTypeQuery { get; private set; } 41 | 42 | private static readonly MethodInfo _whereMethod 43 | = typeof(Queryable) 44 | .GetTypeInfo() 45 | .GetDeclaredMethods(nameof(Queryable.Where)) 46 | .Single( 47 | mi => mi.GetParameters().Length == 2 48 | && mi.GetParameters()[1].ParameterType 49 | .GetGenericArguments()[0] 50 | .GetGenericArguments().Length == 2); 51 | 52 | public override void ApplyModelExpressions(QueryModel queryModel) 53 | { 54 | _querySource = queryModel.MainFromClause; 55 | 56 | queryModel.TransformExpressions(Visit); 57 | } 58 | 59 | protected override Expression VisitConstant(ConstantExpression constantExpression) 60 | { 61 | if (constantExpression.IsEntityQueryable()) 62 | { 63 | var type = ((IQueryable)constantExpression.Value).ElementType; 64 | var entityType = _queryCompilationContext.Model.FindEntityType(type)?.RootType(); 65 | 66 | var typeExpressions 67 | = _queryCompilationContext.QueryAnnotations 68 | .OfType() 69 | .SelectMany(op => op.Filters) 70 | .GroupBy(pair => pair.Key) 71 | .Select(g => 72 | { 73 | var values = g.SelectMany(gg => gg.Value).ToList(); 74 | return new KeyValuePair>(g.Key, values); 75 | }) 76 | .ToDictionary(pair => pair.Key, pair => pair.Value); 77 | 78 | 79 | if (entityType != null) 80 | { 81 | Expression newExpression = constantExpression; 82 | 83 | if (entityType.IsQueryType) 84 | { 85 | IsViewTypeQuery = true; 86 | 87 | var query = entityType.DefiningQuery; 88 | 89 | if (query != null 90 | && _entityQueryModelVisitor.ShouldApplyDefiningQuery(entityType, _querySource)) 91 | { 92 | var parameterizedQuery 93 | = _queryModelGenerator 94 | .ExtractParameters( 95 | _queryCompilationContext.Logger, 96 | query.Body, 97 | _parameters, 98 | parameterize: false, 99 | generateContextAccessors: true); 100 | 101 | var subQueryModel = _queryModelGenerator.ParseQuery(Visit(parameterizedQuery)); 102 | 103 | newExpression = new SubQueryExpression(subQueryModel); 104 | } 105 | } 106 | 107 | if (!_queryCompilationContext.IgnoreQueryFilters 108 | && entityType.QueryFilter != null) 109 | { 110 | var parameterizedFilter 111 | = (LambdaExpression)_queryModelGenerator 112 | .ExtractParameters( 113 | _queryCompilationContext.Logger, 114 | entityType.QueryFilter, 115 | _parameters, 116 | parameterize: false, 117 | generateContextAccessors: true); 118 | 119 | var oldParameterExpression = parameterizedFilter.Parameters[0]; 120 | var newParameterExpression = Expression.Parameter(type, oldParameterExpression.Name); 121 | 122 | var predicateExpression 123 | = ReplacingExpressionVisitor 124 | .Replace( 125 | oldParameterExpression, 126 | newParameterExpression, 127 | Visit(parameterizedFilter.Body)); 128 | 129 | var whereExpression 130 | = Expression.Call( 131 | _whereMethod.MakeGenericMethod(type), 132 | newExpression, 133 | Expression.Lambda( 134 | predicateExpression, 135 | newParameterExpression)); 136 | 137 | var subQueryModel = _queryModelGenerator.ParseQuery(whereExpression); 138 | 139 | newExpression = new SubQueryExpression(subQueryModel); 140 | } 141 | 142 | if (typeExpressions.ContainsKey(type)) 143 | { 144 | foreach (var lambdaExpression in typeExpressions[type]) 145 | { 146 | var parameterizedFilter 147 | = (LambdaExpression)_queryModelGenerator 148 | .ExtractParameters( 149 | _queryCompilationContext.Logger, 150 | lambdaExpression, 151 | _parameters, 152 | parameterize: false, 153 | generateContextAccessors: true); 154 | 155 | var oldParameterExpression = parameterizedFilter.Parameters[0]; 156 | var newParameterExpression = Expression.Parameter(type, oldParameterExpression.Name); 157 | 158 | var predicateExpression 159 | = ReplacingExpressionVisitor 160 | .Replace( 161 | oldParameterExpression, 162 | newParameterExpression, 163 | Visit(parameterizedFilter.Body)); 164 | 165 | var whereExpression 166 | = Expression.Call( 167 | _whereMethod.MakeGenericMethod(type), 168 | newExpression, 169 | Expression.Lambda( 170 | predicateExpression, 171 | newParameterExpression)); 172 | 173 | var subQueryModel = _queryModelGenerator.ParseQuery(whereExpression); 174 | 175 | newExpression = new SubQueryExpression(subQueryModel); 176 | } 177 | } 178 | 179 | return newExpression; 180 | } 181 | } 182 | 183 | return constantExpression; 184 | } 185 | 186 | private sealed class Parameters : IParameterValues 187 | { 188 | private readonly IDictionary _parameterValues = new Dictionary(); 189 | 190 | public IReadOnlyDictionary ParameterValues 191 | => (IReadOnlyDictionary)_parameterValues; 192 | 193 | public void AddParameter(string name, object value) 194 | { 195 | _parameterValues.Add(name, value); 196 | } 197 | 198 | public object RemoveParameter(string name) 199 | { 200 | var value = _parameterValues[name]; 201 | 202 | _parameterValues.Remove(name); 203 | 204 | return value; 205 | } 206 | 207 | public void SetParameter(string name, object value) 208 | { 209 | _parameterValues[name] = value; 210 | } 211 | } 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter/ReplaceRelationalQueryModelVisitor.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using Microsoft.EntityFrameworkCore.Query; 3 | 4 | namespace EntityFrameworkCore.IncludeFilter 5 | { 6 | public class ReplaceRelationalQueryModelVisitor : RelationalQueryModelVisitor 7 | { 8 | public ReplaceRelationalQueryModelVisitor(EntityQueryModelVisitorDependencies dependencies, RelationalQueryModelVisitorDependencies relationalDependencies, RelationalQueryCompilationContext queryCompilationContext, RelationalQueryModelVisitor parentQueryModelVisitor) : base(dependencies, relationalDependencies, queryCompilationContext, parentQueryModelVisitor) 9 | { 10 | var modelExpressionApplyingExpressionVisitor 11 | = new ReplaceModelExpressionApplyingExpressionVisitor( 12 | queryCompilationContext, 13 | dependencies.QueryModelGenerator, 14 | this); 15 | 16 | var field = typeof(EntityQueryModelVisitor).GetField("_modelExpressionApplyingExpressionVisitor", 17 | BindingFlags.NonPublic | BindingFlags.Instance); 18 | 19 | field.SetValue(this, modelExpressionApplyingExpressionVisitor); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter/ReplaceRelationalQueryModelVisitorFactory.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Query; 2 | 3 | namespace EntityFrameworkCore.IncludeFilter 4 | { 5 | public class ReplaceRelationalQueryModelVisitorFactory : RelationalQueryModelVisitorFactory 6 | { 7 | public ReplaceRelationalQueryModelVisitorFactory(EntityQueryModelVisitorDependencies dependencies, RelationalQueryModelVisitorDependencies relationalDependencies) : base(dependencies, relationalDependencies) 8 | { 9 | } 10 | 11 | public override EntityQueryModelVisitor Create( 12 | QueryCompilationContext queryCompilationContext, 13 | EntityQueryModelVisitor parentEntityQueryModelVisitor) 14 | => new ReplaceRelationalQueryModelVisitor( 15 | Dependencies, 16 | RelationalDependencies, 17 | (RelationalQueryCompilationContext)queryCompilationContext, 18 | (ReplaceRelationalQueryModelVisitor)parentEntityQueryModelVisitor); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /EntityFrameworkCore.IncludeFilter/ReplaceThenIncludeExpressionNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Internal; 7 | using Microsoft.EntityFrameworkCore.Query.ResultOperators.Internal; 8 | using Remotion.Linq; 9 | using Remotion.Linq.Clauses; 10 | using Remotion.Linq.Parsing.Structure.IntermediateModel; 11 | 12 | namespace EntityFrameworkCore.IncludeFilter 13 | { 14 | public class ReplaceThenIncludeExpressionNode : IncludeExpressionNodeBase 15 | { 16 | private readonly LambdaExpression _filter; 17 | 18 | public static readonly IReadOnlyCollection SupportedMethods = new[] 19 | { 20 | QueryableExtensions.ThenIncludeAfterReferenceMethodInfo, 21 | QueryableExtensions.ThenIncludeAfterEnumerableMethodInfo 22 | }; 23 | 24 | public ReplaceThenIncludeExpressionNode(MethodCallExpressionParseInfo parseInfo, LambdaExpression navigationPropertyPathLambda, LambdaExpression filter) 25 | : base(parseInfo, navigationPropertyPathLambda) 26 | { 27 | _filter = filter; 28 | } 29 | 30 | protected override void ApplyNodeSpecificSemantics(QueryModel queryModel, ClauseGenerationContext clauseGenerationContext) 31 | { 32 | var includeResultOperator 33 | = (IncludeResultOperator)clauseGenerationContext.GetContextInfo(Source); 34 | 35 | if (!NavigationPropertyPathLambda.TryGetComplexPropertyAccess(out var propertyPath)) 36 | { 37 | throw new InvalidOperationException( 38 | CoreStrings.InvalidIncludeLambdaExpression( 39 | nameof(EntityFrameworkQueryableExtensions.ThenInclude), 40 | NavigationPropertyPathLambda)); 41 | } 42 | 43 | if (includeResultOperator is ReplaceIncludeResultOperator replace) 44 | { 45 | var type = _filter.Parameters[0].Type; 46 | 47 | if (!replace.Filters.ContainsKey(type)) 48 | { 49 | replace.Filters.Add(type, new List()); 50 | } 51 | 52 | replace.Filters[type].Add(_filter); 53 | } 54 | 55 | includeResultOperator.AppendToNavigationPath(propertyPath); 56 | 57 | clauseGenerationContext.AddContextInfo(this, includeResultOperator); 58 | } 59 | 60 | protected override ResultOperatorBase CreateResultOperator(ClauseGenerationContext clauseGenerationContext) 61 | => null; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017, Qinglin (Max) Meng 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | 23 | #### 24 | 25 | Copyright (c) .NET Foundation. All rights reserved. 26 | 27 | Modified by Qinglin (Max) Meng 28 | 29 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 30 | these files except in compliance with the License. You may obtain a copy of the 31 | License at 32 | 33 | http://www.apache.org/licenses/LICENSE-2.0 34 | 35 | Unless required by applicable law or agreed to in writing, software distributed 36 | under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 37 | CONDITIONS OF ANY KIND, either express or implied. See the License for the 38 | specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | This product includes code from EntityFrameworkCore under Apache License 2 | https://github.com/aspnet/EntityFrameworkCore 3 | 4 | Copyright (c) .NET Foundation. All rights reserved. 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 7 | these files except in compliance with the License. You may obtain a copy of the 8 | License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software distributed 13 | under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 14 | CONDITIONS OF ANY KIND, either express or implied. See the License for the 15 | specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EntityFrameworkCore.IncludeFilter 2 | 3 | Modified base on EntityFrameworkCore 2.1.0 4 | 5 | 6 | How to use: 7 | 8 | ```csharp 9 | public void ConfigureServices(IServiceCollection services) 10 | { 11 | ... 12 | 13 | services.AddDbContext(options => options.UseSqlServer("connection_string") 14 | .AddIncludeWithFilterMethods()); 15 | 16 | ... 17 | } 18 | ``` 19 | 20 | ```csharp 21 | var children = dbContext.Parent.IncludeWithFilter(p=>p.Children, c=>c.Active) 22 | .ThenIncludeWithFilter(c=>c.Items, i=>i.ID > 100); 23 | ``` 24 | 25 | NOTE: EF still performs identity resolution, results will be overwrite on next IncludeWithFilter call 26 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "projects": [ "src", "test" ], 3 | "sdk": { 4 | "version": "1.0.0-preview2-003131" 5 | } 6 | } 7 | --------------------------------------------------------------------------------