实体框架核心:属性表达式"xx"无效.该表达式应表示属性访问:'t => t.MyProperty' [英] Entity framework core: The property expression 'xx' is not valid. The expression should represent a property access: 't => t.MyProperty'
问题描述
尝试在实体框架核心的叶级别使用where子句查询,但出现此错误:
Trying to query with where clause at the leaf level in entity framework core but getting this error:
Unhandled Exception: System.ArgumentException: The property expression 'c => {from Child t in c.Children where ([t].Name != "NoInc
lude") select [t]}' is not valid. The expression should represent a property access: 't => t.MyProperty'. For more information on
including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.
at Microsoft.EntityFrameworkCore.Internal.ExpressionExtensions.GetComplexPropertyAccess(LambdaExpression propertyAccessExpressi
on)
at Microsoft.EntityFrameworkCore.Query.ResultOperators.Internal.ThenIncludeExpressionNode.ApplyNodeSpecificSemantics(QueryModel
queryModel, ClauseGenerationContext clauseGenerationContext)
at Remotion.Linq.Parsing.Structure.IntermediateModel.MethodCallExpressionNodeBase.Apply(QueryModel queryModel, ClauseGeneration
Context clauseGenerationContext)
at Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](Expression query, INodeTypeProvider nod
eTypeProvider, IDatabase database, ILogger logger, Type contextType)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass19_0`1.<CompileQuery>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Remotion.Linq.QueryableBase`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at dotnetsql.Demo.Main(String[] args) in C:\Users\asad\dev\dotnetsql\Program.cs:line 15
这是可以在控制台应用程序中复制此代码的完整代码:
Here is the complete code which can be used in a console application to replicate this:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace dotnetsql
{
class Demo
{
static void Main(string[] args)
{
using (var context = new FamilyContext())
{
var seed = new SeedData(context);
var result = context.GrandParent
.Include(p => p.Parents)
.ThenInclude(c => c.Children.Where(t => t.Name != "NoInclude"))
.ToList();
Console.WriteLine(result.Count);
}
}
}
public class FamilyContext : DbContext
{
public FamilyContext()
{
Database.EnsureCreated();
}
public DbSet<GrandParent> GrandParent { get; set; }
public DbSet<Parent> Parent { get; set; }
public DbSet<Child> Child { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase();
}
}
public class GrandParent
{
public int Id { get; set; }
public string Name { get; set; }
public List<Parent> Parents { get; set; }
}
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public int GrandParentId { get; set; }
public GrandParent GrandParent { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public Parent Parent { get; set; }
}
// Seed Data
public class SeedData
{
public SeedData(FamilyContext context)
{
if (!context.GrandParent.Any())
{
context.GrandParent.AddRange(
new List<GrandParent>
{
new GrandParent{Name = "Grandparent 1", },
new GrandParent{Name = "Grandparent 2", },
}
);
context.SaveChanges();
context.Parent.AddRange(
new List<Parent> {
new Parent{Name = "Parent 1", GrandParentId = 1},
new Parent{Name = "Parent 2", GrandParentId = 1},
}
);
context.SaveChanges();
context.Child.AddRange(
new List<Child> {
new Child{Name = "Child 1", ParentId = 1},
new Child{Name = "Child 2", ParentId = 1},
new Child{Name = "NoInclude", ParentId = 1}
}
);
context.SaveChanges();
}
}
}
}
阅读这篇文章,但延迟加载示例很简单,希望在过滤没有帮助的子记录之前先加载单个实体.
Read this article but lazy loading example is simple and expect to load a single entity before filtering its children records which isn't helping.
此处是可以快速复制此内容的完整控制台应用程序.
Here is the complete console application to quickly replicate this.
谢谢.
推荐答案
假定您要执行过滤的包含-一种功能,该功能已被要求多次,并且在包括Core在内的任何EF版本中均不受支持.在AFAIK中,有计划将其添加到EF Core中,但是在此之前,您必须手动解决它.
Assuming you want to perform a filtered include - a feature requested many times and not supported in any EF version including Core. AFAIK there is a plan to add it to EF Core, but until then you have to resolve it manually.
该技术与加载相关数据-显式加载部分,过滤哪些相关实体已加载到内存示例,但适用于任何查询.
The technique is basically the same as explained in the Loading Related Data - Explicit loading section, filter which related entities are loaded into memory example, but applied to any query.
首先,通过应用所有必要的过滤来提取(但不执行)聚合根查询(在您的示例中为GrandParents
):
You start by extracting (but not executing) the aggregate root query (GrandParents
in your example) applying all necessary filtering:
var query = context.GrandParent.AsQueryable();
然后执行并具体化主查询,应用未过滤的内容包括:
Then execute and materialize the main query, applying non filtered includes:
var result = query
.Include(p => p.Parents)
.ToList();
最后显式加载预期的过滤对象:
Finally explicitly load the intended filtered includes:
query.SelectMany(p => p.Parents)
.SelectMany(c => c.Children)
.Where(t => t.Name != "NoInclude")
.Load();
这篇关于实体框架核心:属性表达式"xx"无效.该表达式应表示属性访问:'t => t.MyProperty'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!