实体框架核心:属性表达式'xx'无效。表达式应代表属性访问:'t => t.MyProperty”

时间:2017-05-17 20:23:57

标签: c# sql-server entity-framework linq entity-framework-core

尝试在实体框架核心的叶级别查询where子句,但收到此错误:

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

以下是可在控制台应用程序中使用的完整代码:

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();
            }
        }


    }



}

阅读this文章,但延迟加载示例很简单,并且希望在过滤其子记录之前加载单个实体,这无助于。

Here是完整的控制台应用程序,可以快速复制它。

感谢。

1 个答案:

答案 0 :(得分:4)

假设您要执行过滤包含 - 多次请求的功能,并且在包括Core在内的任何EF版本中均不受支持。 AFAIK有计划将其添加到EF Core,但在此之前您必须手动解决它。

该技术与Loading Related Data - 显式加载部分中解释的基本相同,过滤器将相关实体加载到内存中示例,但应用于任何疑问。

首先应用所有必要的过滤来提取(但不执行)聚合根查询(在您的示例中为GrandParents):

var query = context.GrandParent.AsQueryable();

然后执行并具体化主查询,应用非过滤包括:

var result = query
    .Include(p => p.Parents)
    .ToList();

最后明确加载预期的过滤包括:

query.SelectMany(p => p.Parents)
    .SelectMany(c => c.Children)
    .Where(t => t.Name != "NoInclude")
    .Load();