动态Linq“Where声明”与关系

问题描述 投票:1回答:3

我正在尝试使用Dynamic Linq和我自己计算的where字符串语句构建查询。例如:

List<Publication> results = new List<Publication>();

// Just an example, previously calculated dynamically
string filterQuery = "(Id = 1 and Number = 2)";

IQueryable<Publication> query = db.Publications.Include(i => i.Product);
query = query.Where(filterQuery);

results = query.OrderBy(orderQuery).ToList();

这很有效,我得到了一份带产品的出版物清单。现在......问题是。如何基于与使用Dynamic Linq和字符串语句的Product的关系来创建字符串语句来获取结果?

就像是:

string filterQuery = "(Id = 1 and Number = 2 and Products.Id = 1)"
c# entity-framework visual-studio linq
3个回答
1
投票

我不确定你为什么这样做,但以下应该有效:

List<Publication> results = new List<Publication>();

// Just an example, previously calculated dynamically
string filterQuery1 = "(Id = 1)"
string filterQuery2 = "(Id = 1 and Number = 2)";

IQueryable<Publication> query = db.Publications.
Where(filterQuery1).     
Include(i => i.Product);
query = query.Where(filterQuery2);

results = query.OrderBy(orderQuery).ToList();

1
投票

经过大量的研究和尝试,使用相同的Dynamic Linq库是一种简单友好的方式:

List<Publication> results = new List<Publication>();

// Just an example, previously calculated dynamically
string filterQuery = "(Id = 1 and Number = 2)";
string filterQueryChildren = "Products.Any(Id == 1)"

IQueryable<Publication> query = db.Publications.Include(i => i.Product).Where(filterQueryChildren);

query = query.Where(filterQuery);

results = query.OrderBy(orderQuery).ToList();

0
投票

要进行动态LINQ查询,您需要一个支持它的库或使用Expression Tree自己完成

见:Entity Framework Dynamic Query Library

免责声明:我是Eval-Expression.NET项目的所有者

该库允许您在运行时评估,编译和执行代码。

该库还包含动态LINQ的扩展方法

维基:Eval Dynamic LINQ

// using Z.Expressions; // Don't forget to include this.

// The filterQuery must use the C# syntax
string filterQuery = "x.Id == 1 && x.Number = 2";

IQueryable<Publication> query = db.Publications.Include(i => i.Product);
query = query.Where(x => filterQuery);

编辑:回答子问题

很棒,但我如何按产品过滤?

实体框架不支持Include方法中的过滤器。

但是,EF +做

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

见:EF+ Query IncludeFilter

通过组合两个库,您可以实现所需的结果:

// Extension method must be registered, otherwise the library cannot be aware of which extension method exists!
EvalManager.DefaultContext.RegisterExtensionMethod(typeof (QueryIncludeFilterExtensions));

string where1 = "x.Id == 1 && x.Number == 2";
string where2 = "y.Id == 3";

var left2 = ctx.Publications
    .Where(x => where1)
    .Execute<IQueryable<Publication>>("IncludeFilter(x => x.Product.Where(y => " + where2 + "))")
    .ToList();

如果您想尝试此解决方案,请确保下载最新版本的Eval-Expression.NET。我们刚刚修复了几个问题,我们通过尝试您的方案找到了一个问题。

EDIT2:回答子问题

这是我推荐你的。

在没有我们的库的情况下尝试查询,然后动态尝试。

这更容易找到编译错误或您想要做的事情。

例如,我们可能没有正确理解初始问题并建议您不想要的IncludeFilter。我以为你想过滤多个产品。但是,它看起来每个发布只有一个产品,所以Where子句方法显然不存在。

也许这就是你想要的更多:

string where1 = "x.Id == 1 && x.Number == 2 && x.Product.Id == 3";

var left2 = ctx.Publications
    .Include(x => x.Product)
    .Where(where1)
    .ToList();

简而言之,通过硬编码(没有动态)来尝试查询,然后您将知道如何动态使用它。

© www.soinside.com 2019 - 2024. All rights reserved.