In the context of a inherited entities, I want to get the full structure, given the fact a sub element has a type that is a super type.
In this example, I want to get the full list of historical values, with their dependencies: if the dependency is a shareclass, I want to get the related subfund on the go
var tmp = _dbContext.Set<Security>()
.Include(i => (i as ShareClass).SubFund)
.ToList();
FYI: It worked in EF and EF Core prior 3.0
var tmp = _dbContext.Set<SecurityHistoricalValue>()
.Include(i => i.Security as ShareClass).ThenInclude(i => i.SubFund)
.ToList();
Typically, here is the regex pattern that permits me to find what will raise an exception on my code after my migration to EF core 3.0:
as\s+[^\s]+[)]\s*[.]ThenInclude\s*[(]
Exception raised:
Exception thrown: 'System.InvalidOperationException' in Microsoft.EntityFrameworkCore.dll: 'Lambda expression used inside Include is not valid.'
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.ProcessInclude(NavigationExpansionExpression source, Expression expression, Boolean thenInclude)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.ExpandAndReduce(Expression query, Boolean applyInclude)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.Expand(Expression query)
at Microsoft.EntityFrameworkCore.Query.QueryTranslationPreprocessor.Process(Expression query)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.IncludableQueryable`2.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at FundProcess.Pms.Services.PortfolioService.<SearchHistoricalValuesAsync>d__5.MoveNext() in /home/stephane/Documents/Sources/PMS/src/FundProcess.Pms.Services/PortfolioService.cs:line 93
public class SubFund
{
}
public class SubFundConfiguration : IEntityTypeConfiguration<SubFund>
{
public void Configure(EntityTypeBuilder<SubFund> builder)
{
builder.HasBaseType<Portfolio>();
}
}
public abstract class Security : IBelongsToEntity, IAnySecurity
{
public int Id { get; set; }
public List<SecurityHistoricalValue> HistoricalValues { get; set; }
}
public class SecurityConfiguration : IEntityTypeConfiguration<Security>
{
public void Configure(EntityTypeBuilder<Security> builder)
{
builder.ToTable(nameof(Security));
builder.HasKey(i => i.Id);
builder.Property(i => i.Id).UseIdentityColumn();
}
}
public class ShareClass : Security
{
public int? SubFundId { get; set; }
public SubFund SubFund { get; set; }
}
public class ShareClassConfiguration : IEntityTypeConfiguration<ShareClass>
{
public void Configure(EntityTypeBuilder<ShareClass> builder)
{
builder.HasBaseType<Security>();
builder.HasOne(i => i.SubFund).WithMany(i=>i.ShareClasses).OnDelete(DeleteBehavior.Restrict).HasForeignKey(i => i.SubFundId);
}
}
public class Future : Security
{
}
public class ShareClassConfiguration : IEntityTypeConfiguration<Future>
{
public void Configure(EntityTypeBuilder<Future> builder)
{
}
}
public class SecurityHistoricalValue
{
public int SecurityId { get; set; }
public Security Security { get; set; }
public DateTime Date { get; set; }
}
public class SecurityHistoricalValueConfiguration : IEntityTypeConfiguration<SecurityHistoricalValue>
{
public void Configure(EntityTypeBuilder<SecurityHistoricalValue> builder)
{
builder.ToTable(nameof(SecurityHistoricalValue));
builder.Property(i => i.Date).HasColumnType("DATE");
builder.HasKey(i => new { i.Date, i.SecurityId});
builder.HasOne(i => i.Security).WithMany(i => i.HistoricalValues).OnDelete(DeleteBehavior.Restrict).HasForeignKey(i => i.SecurityId);
}
}
EF Core version: 3.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET Core 3.0
Operating system: ubuntu 19.04
IDE: VIsual Studio Code
Notes from triage: to clarify (without changing types in the query) this works:
```C#
var tmp2 = context.Set
.Include(i => i.Security).ThenInclude(i => (i as ShareClass).SubFund)
.ToList();
This does not:
```C#
var tmp2 = context.Set<SecurityHistoricalValue>()
.Include(i => i.Security as ShareClass).ThenInclude(i => i.SubFund)
.ToList();
We will consider making this work again in a future release.
Notes from triage: to clarify (without changing types in the query) this works:
var tmp2 = context.Set<SecurityHistoricalValue>() .Include(i => i.Security).ThenInclude(i => (i as ShareClass).SubFund) .ToList();
This does not:
var tmp2 = context.Set<SecurityHistoricalValue>() .Include(i => i.Security as ShareClass).ThenInclude(i => i.SubFund) .ToList();
We will consider making this work again in a future release.
For me no version does work. I just migrated from EF Core 2.2 to EF Core 3.0. Following code where Values is List ofSectionType causes a similar exception and I did not find a way to make that include work:
var test = await _context.Set<ReportCategory>()
.Include(x => x.Sections)
.ThenInclude(x => (x as ReportSection<SectionType>).Values)
.ToListAsync();
Exception:
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Invalid include.
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.PopulateIncludeTree(IncludeTreeNode includeTreeNode, Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.ProcessInclude(NavigationExpansionExpression source, Expression expression, Boolean thenInclude)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.ExpandAndReduce(Expression query, Boolean applyInclude)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.Expand(Expression query)
at Microsoft.EntityFrameworkCore.Query.QueryTranslationPreprocessor.Process(Expression query)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0
1.
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCoreTFunc
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsyncTResult
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsyncTResult
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable1.GetAsyncEnumerator(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.IncludableQueryable
2.GetAsyncEnumerator(CancellationToken cancellationToken)
at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable1.GetAsyncEnumerator()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable
1 source, CancellationToken cancellationToken)
at Stego.ReportPortal.Data.Services.Sections.OverdueAccountDataRepository.ListAsync(IUserInformation user, Nullable1 parentId) in C:\git\reportportal.api\Stego.ReportPortal.Data\Services\Sections\Financial\OverdueAccountDataRepository.cs:line 90
at Stego.ReportPortal.Controllers.Report.Sections.OverdueAcountController.Get(Int32 reportId) in C:\git\reportportal.api\Stego.MonthlyReports\Controllers\Report\Sections\OverdueAcountController.cs:line 45
at lambda_method(Closure , Object )
at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask
1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.
at Microsoft.AspNetCore.Routing.EndpointMiddleware.
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Stego.ReportPortal.Common.Filters.ExceptionFilterMiddleware.Invoke(HttpContext httpContext) in C:gitreportportal.apiStego.MonthlyReportsCommonFiltersExceptionFilterMiddleware.cs:line 24
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)`
Having the same problem here, any solution yet?
@amacado - Rewrite your query as per supported LINQ. See https://github.com/aspnet/EntityFrameworkCore/issues/18248#issuecomment-540137593
@smitpatel i already tried that. Have the same problem as @domdeger that it still not work.
@smitpatel I can confirm that both versions provided by @ajcvickers do not work for me. This is currently preventing me from upgrading to 3.0.
There is no doubt that our use cases are more like corner cases. But it is somehow a regression since the aforementioned worked in v2.2. and also it is a feature that I would suspect to be working when inheritance is supported by the Framework.
@amacado @domdeger - Use 3.1 release. That is latest LTS release out there. If it does not work then share runnable repro code which demonstrate error you are hitting.
@smitpatel when i remember it correctly I think I also tried it in 3.1, but will verify it on monday and report back.
It did not worked out for me, my solution is to concat the results like this:
// fetching results of child class StockBatchProcessingSalesOrderItem
var resultOfStockBatchProcessingSalesOrderItem = this._stockBatchProcessingItemContext.StockBatchProcessingItems
.OfType<StockBatchProcessingSalesOrderItem>()
.Where(p => p.BatchId == id)
.ToList();
// fetching result of main class, seems required for a corrent return type List<StockBatchProcessingItem>
var resultOfStockBatchProcessingItems = this._stockBatchProcessingItemContext.StockBatchProcessingItems
.Where(p => p.BatchId == id)
.ToList();
// combine results for subclasses and parent class
return resultOfStockBatchProcessingSalesOrderItem
.Concat(resultOfStockBatchProcessingItems).ToList();
I know it's not very elegant, but for me it works for the moment.
Same problem here. Is there any news about this issue?
I have similar issue that works in ef core 2.2.6, but it is not working in 3.1.1
//Works in 2.2.6, but in 3.1.1 it throws the same exception as issue title
context.Users
.Include(n => (object)n.RelatedProp)
.Where(n => n.Name == "test")
.ToList();
public class Related
{
public int Id { get; set; }
public string Name { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public Related RelatedProp { get; set; }
}
query = query.Include(x => x.Items).ThenInclude(y => y.Select(z => z.Prodct));
this ex won't work, how do this?
@jpnobrega - Please refer to documentation
I fix with this:
query = query.Include(x => x.Items).ThenInclude(y => y.Product);
query = query.Include(x => x.Items).ThenInclude(y => y.IngredientItems).ThenInclude(z => z.Ingredient);
But, the Visual Studio 2019 can't detect the entity Ingredient in ThenInclude
, but work's.
Same for EF Core 3.1.2
Edit:
Solved my problem.
The problem was a property that had only a getter and not a setter. I added a private setter and now .ThenInclude works fine.
The
Exception thrown: 'System.InvalidOperationException' in Microsoft.EntityFrameworkCore.dll: 'Lambda expression used inside Include is not valid.'
was really confusing
Same problem here, subscribed.
I've been dealing with the same issue. Subscribed.
same problem
The solution for me was adding the relationship to the modelbuilder.
So for example, my query includes an City.
My Property that i use in my include looks like:
And i define the relationship in the modelbuilder, and that solved the problem with the invalid lambda expression.
It looks like that Entity Framework can't resolve the relationship at his own, so with the Modelbuilder you define the relations at your own.
I know this is a simple example, but this also should work with bigger relationships.
I hope this is the solution for you all!
PS: I don't use lazy loading, i use eager loading.
When using the name of the property with the same name of your entity, do you have this problem because in EntityFramework Core 3.0 is removed relation of the foreign key by convention. Look this the breaking changes on the new version after 2.2.
https://docs.microsoft.com/pt-br/ef/core/what-is-new/ef-core-3.0/breaking-changes#the-foreign-key-property-convention-no-longer-matches-same-name-as-the-principal-property
Any update on this?
@rochapablo and others commenting on this issue: can you provide some more details on why you cannot or it is hard to use the form of Include that is supported?
To add to above,
Select
inside include is not supported.Also anyone seeing the same exception, make sure that the navigation you are trying to include is actually mapped in your model.
@ajcvickers this happens when the attribute in my model it's [NotMapped]
and I try to add it in the dbcontext.Users.Include(x => Logs).
class User {
[NotMapped]
public List<Log> Logs
}
@rochapablo Include can only be used with navigation properties configured in the model. [NotMapped]
explicitly excludes this property from the model, so Include cannot be used here. This is because without a mapping for the navigation property in the model, EF would not know which related entities to include.
The repro for me is quite simple, and shows the same code leading to error or not
Fails
return source =>
source.Include(d => d.positions as ICollection<DronePosition>);
Works
return source =>
source.Include(d => d.positions);
The Model is
public class A {
public long Id {get; set;}
public ICollection<DronePosition> positions { get; set; }
}
The code that fails with the casting is even signaled as redundant by resharper.
My idea is that for some reason there is some an internal specialisation of ICollection that we are not aware of, and only the compiler knows and produces good code.
@ptsneves - That is not valid include. You cannot use cast on navigation.
@smitpatel Thanks for the fast answer. Can you point out to the rationale and where i can find it documented? Could you also point out how this differs from the top post issue?
Also, given this restriction, how could i use reflection or constrained template parameters with EF include?
Grateful for your patience.
ptsneves
@ptsneves It's not clear to me what you mean by, "Also, given this restriction, how could i use reflection or constrained template parameters with EF include?" Can you give some more details on what you mean by this and why you need to use the cast?
Hello @ajcvickers. I had a PropertyInfo from a model, and when i want to include a given property in the query i would do: [...].Include(d => prop_info.getValue(d, null) as T) [...]
.
Does this make sense? I completely abandoned the code where i wanted to do this, this is why i may have lost some important detail useful for the explanation. Let me know if you require clarification
Include(e => EF.Property<T>(e, propertyInfo.Name))
would be much simpler. (This assumes the navigation name is same as propertyInfo.Name)
or string based include Include(propertyInfo.Name)
May be related with #23048 (sample repo is included)
Like domdeger, I got the "Invalid include." error message when trying to include a list that is defined in a derived class (it worked fine in EF 2.2.6 but failed in 3.1.9):
System.InvalidOperationException
HResult=0x80131509
Message=Invalid include.
Source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.PopulateIncludeTree(IncludeTreeNode includeTreeNode, Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.ProcessInclude(NavigationExpansionExpression source, Expression expression, Boolean thenInclude)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.Expand(Expression query)
at Microsoft.EntityFrameworkCore.Query.QueryTranslationPreprocessor.Process(Expression query)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at ...
I have a four level inheritance hierarchy and in some cases builder.HasBaseType Another interesting note: The above exception was only thrown when all leaf classes where incorrect as specified above. When some but not all where incorrect, the following exception was thrown instead which is a lot more helpful:System.InvalidOperationException
HResult=0x80131509
Message=The entity type 'MyClassD' should derive from 'MyClassC' to reflect the hierarchy of the corresponding CLR types.
Source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateClrInheritance(IModel model, IEntityType entityType, HashSet`1 validEntityTypes)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateClrInheritance(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.SqlServer.Internal.SqlServerModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.ValidatingConvention.ProcessModelFinalized(IConventionModelBuilder modelBuilder, IConventionContext`1 context)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelFinalized(IConventionModelBuilder modelBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelFinalized(IConventionModelBuilder modelBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel()
at Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel()
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_3(IServiceProvider p)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_Dependencies()
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.Microsoft.EntityFrameworkCore.Internal.IDatabaseFacadeDependenciesAccessor.get_Dependencies()
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetFacadeDependencies(DatabaseFacade databaseFacade)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.SetCommandTimeout(DatabaseFacade databaseFacade, Nullable`1 timeout)
at ...
I would like to be able to do something like this:
.Include(cos => cos.Conversation).ThenInclude(c => c.Actions.OrderByDescending(a => a.Id).Take(1))
Note from triage: @maumar to cleanup and file other issues as needed, since some of these cases are now covered by filtered Include.
@PeterLAxakon See https://docs.microsoft.com/en-us/ef/core/querying/related-data/eager#filtered-include
Note from triage: @maumar to cleanup and file other issues as needed, since some of these cases are now covered by filtered Include.
@PeterLAxakon See https://docs.microsoft.com/en-us/ef/core/querying/related-data/eager#filtered-include
Problem is that its not working. I get "Lambda expression used inside Include is not valid" when trying to write:
.Include(cos => cos.Conversation).ThenInclude(c => c.Actions.OrderByDescending(a => a.Id).Take(1))
Ended up using: https://entityframework-plus.net/tutorial-query#query-includefilter
@PeterLAxakon - The feature was added in EF Core 5.0. If it is not working on EF Core 5.0 then please file a new issue with repro steps.
filed https://github.com/dotnet/efcore/issues/23237, everything else either works or is by design
Most helpful comment
I have similar issue that works in ef core 2.2.6, but it is not working in 3.1.1