實體框架核心:屬性表達式'xx'無效。表達式應代表屬性訪問:'t => t.MyProperty'

c# entity-framework entity-framework-core linq sql-server

嘗試在實體框架核心的葉級別查詢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();
            }
        }


    }



}

閱讀這篇文章,但是延遲加載示例很簡單,並且希望在過濾其子記錄之前加載單個實體,這對於沒有幫助。

是完整的控制台應用程序,可以快速復制它。

謝謝。

熱門答案

假設您要執行過濾包含 - 多次請求的功能,並且在包括Core的任何EF版本中都不支持。 AFAIK有計劃將其添加到EF Core,但在此之前您必須手動解決它。

該技術與加載相關數據 - 顯式加載部分中所解釋的基本相同, 過濾哪些相關實體被加載到內存示例中,但應用於任何查詢。

首先,應用所有必要的過濾,提取(但不執行)聚合根查詢(在您的示例中為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();


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow