如何将LambdaExpression传递给IncludeFilter?

时间:2017-12-28 20:16:01

标签: entity-framework entity-framework-plus

我正在尝试将动态生成的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&gt;并且一个使用Expression&gt;&gt;。如果我能弄清楚如何让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库实际上非常出色。

1 个答案:

答案 0 :(得分:0)

免责声明:我是该项目的所有者Entity Framework Plus

是的,这是可能的,但前提是您可以为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以使一切都通用。它不能像你想要的那样被明确地称为。