如何將LambdaExpression傳遞給IncludeFilter?


我正在嘗試將動態生成的LambdaExpression傳遞給IncludeFilter,如下所示:

編輯:我已將我的測試代碼更改為以下內容,因為(正確)我沒有實現我的“Where”語句。正在生成正確的where語句,但我無法將lambda語句傳遞給IncludeFilter調用:

        DbSet<MyTestEntity> dbSet = db.Set<MyTestEntity>();
        ParameterExpression parameter = Expression.Parameter(typeof(MyTestEntity), "t");
        Expression idProperty = Expression.Property(parameter, "mytestentityid");
        Expression delProperty = Expression.Property(parameter, "deleted");
        Expression delTarget = Expression.Constant(false, typeof(bool));
        Expression deletedMethod = Expression.Call(delProperty, "Equals", null, delTarget);
        Expression<Func<MyTestEntity, bool>> lambda = Expression.Lambda<Func<MyTestEntity, bool>>(deletedMethod, parameter);
        IQueryable<MyTestEntity> query = dbSet.Where(lambda);
        Console.WriteLine("Current Query: {0}", query.ToString());
        foreach (string include in includes)
        {
            Type subType = db.GetType().Assembly.GetTypes().SingleOrDefault(x => x.Name.EndsWith(include));
            Assert.IsNotNull(subType);
            ParameterExpression innerParam = Expression.Parameter(subType, subType.Name);
            Assert.IsNotNull(innerParam);
            MemberExpression inrDelProp = Expression.Property(innerParam, "deleted");
            Assert.IsNotNull(inrDelProp);
            ConstantExpression inrDelCstProp = Expression.Constant(false, typeof(bool));
            Assert.IsNotNull(inrDelCstProp);
            MethodCallExpression inrDelMthd = Expression.Call(inrDelProp, "Equals", null, inrDelCstProp);
            Assert.IsNotNull(inrDelMthd);
            var delegateType = typeof(Func<,>).MakeGenericType(subType, typeof(bool));
            dynamic inrLmbdaExpr = Expression.Lambda(delegateType, inrDelMthd, innerParam);
            Assert.IsNotNull(inrLmbdaExpr);
            Console.WriteLine("inrLmbdaExpr: {0}", inrLmbdaExpr.ToString()); // Result: MyTestEntityChild => MyTestEntityChild.deleted.Equals(false)
            query = query.IncludeFilter(inrLmbdaExpr); // ERROR HERE
            Assert.IsNotNull(query);
            Console.WriteLine("-------------------------------------------------");
            Console.WriteLine("Current Query: {0}", query.ToString());
        }

它構建在一個抽像類中,允許我傳入實體類型,檢索記錄,並重用該方法而不管實體類型如何;但是,我也試圖過濾掉標記為已刪除的子實體(因此使用EF +)。

我怎樣才能做到這一點?

編輯2:所以,我意識到我的解決方案中也有Linq.Dynamic.Core(!),所以我已經有權從字符串中解析LambdaExpression。但是,我得到的錯誤說IncludeFilter不知道它試圖使用哪種方法。 (我在對象瀏覽器中看到一個人使用Expression>,一個使用Expression >>。如果我能弄清楚如何讓IncludeFilter識別哪個方法,我想我會完成!這是代碼的示例我改寫了:

string myIncStr = String.Format("x => x.{0}.Where(s => s.deleted.Equals(false)).Where(x => x.MyEntityId.Equals(IncomingId)",includedEntityName);
IEnumerable<MyEntity> result = db.MyEntity.IncludeFilter(System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(typeof(MyChildEntity), myIncStr, null));

有沒有辦法“強制”(缺乏一個更好的術語)IncludeFilter使用一種方法?是通過在Parser中傳遞值而不是null嗎?

順便說一句,謝謝你的幫助。您的EFP庫實際上非常出色。

專家解答

免責聲明 :我是項目Entity Framework Plus的所有者

是的,這是可能的,但QueryFilter是您可以為QueryFilter明確指定方法所需的泛型參數類型(正如您在評論中提到的那樣)。

否則,您還需要通過表達式調用QueryFilter以使一切都通用。


但是,您當前的表達式似乎有一些錯誤,例如不調用Where方法。

你想要達到的目標可能類似於:

query = query.IncludeFilter(x => x.Childs.Where(y => !y.Deleted));


免責聲明 :我是Eval-Expression.NET項目的所有者

此庫不是免費的,但可以更輕鬆,更快速地使用動態表達式。

一旦使用,您可以像通常編寫LINQ一樣在幾行中快速創建動態表達式。這是一個代碼,可以處理類似的情況:

using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Windows.Forms;
using Z.Expressions;

namespace Z.EntityFramework.Plus.Lab.EF6
{
    public partial class Form_Request_IncludeFilter_Dynamic : Form
    {
        public Form_Request_IncludeFilter_Dynamic()
        {
            InitializeComponent();

            // CLEAN
            using (var context = new EntityContext())
            {
                context.MyEntityClasses.RemoveRange(context.MyEntityClasses);
                context.MyEntityClassToFilters.RemoveRange(context.MyEntityClassToFilters);
                context.SaveChanges();
            }

            // SEED
            using (var context = new EntityContext())
            {
                var entity1 = context.MyEntityClasses.Add(new MyEntityClass {ColumnInt = 1, Childs = new List<MyEntityClassToFilter>()});
                entity1.Childs.Add(new MyEntityClassToFilter {ColumnInt = 1, Deleted = true});
                entity1.Childs.Add(new MyEntityClassToFilter {ColumnInt = 2, Deleted = false});
                context.MyEntityClasses.Add(new MyEntityClass {ColumnInt = 2});
                context.MyEntityClasses.Add(new MyEntityClass {ColumnInt = 3});
                context.SaveChanges();
            }

            // TEST
            using (var context = new EntityContext())
            {
                // You must register extension method only once
                // That should not be done here, but for example purpose
                EvalManager.DefaultContext.RegisterExtensionMethod(typeof(QueryIncludeFilterExtensions));

                // That could be also dynamic. I believe you already handle this part
                IQueryable<MyEntityClass> query = context.MyEntityClasses;

                // The path to include
                var include = "Childs";

                // The dynamic expression to execute
                var dynamicExpression = "IncludeFilter(x => x." + include + ".Where(y => !y.Deleted));";
                query = query.Execute<IQueryable<MyEntityClass>>(dynamicExpression);

                // The result
                var list = query.ToList();
            }
        }

        public class EntityContext : DbContext
        {
            public EntityContext() : base("CodeFirstEntities")
            {
            }

            public DbSet<MyEntityClass> MyEntityClasses { get; set; }
            public DbSet<MyEntityClassToFilter> MyEntityClassToFilters { get; set; }

            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Types().Configure(x =>
                    x.ToTable(GetType().DeclaringType != null
                        ? GetType().DeclaringType.FullName.Replace(".", "_") + "_" + x.ClrType.Name
                        : ""));

                base.OnModelCreating(modelBuilder);
            }
        }

        public class MyEntityClass
        {
            public int ID { get; set; }
            public int ColumnInt { get; set; }

            public List<MyEntityClassToFilter> Childs { get; set; }
        }

        public class MyEntityClassToFilter
        {
            public int ID { get; set; }
            public int ColumnInt { get; set; }

            public bool Deleted { get; set; }
        }
    }
}

編輯:回答問題

請查看我更改的代碼

你仍然缺少where子句。

你得到的是與你評論的類似的東西

// Result: MyTestEntityChild => MyTestEntityChild.deleted.Equals(false)

你想要的是類似的東西

// Result: MyTestEntityChild => MyTestEntityChild.Where(x => x.deleted.Equals(false))

編輯:回答問題

對不起,我現在明白了它的問題。

如果您不知道類型,則需要在表達式中調用IncludeFilter以使一切都通用。它不能像你想要的那樣被明確地稱為。





許可下: CC-BY-SA
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因