【问题标题】:Using Dynamic LINQ Where in a one-to-many Entity Framework relationship在一对多实体框架关系中使用动态 LINQ Where
【发布时间】:2015-09-09 17:52:28
【问题描述】:

我正在使用 EF 6 和 .net 4.5。 我有一个带有 PK“DocumentId”(Int)和另一列“Title”的“Documents”表。我有另一个名为“DocumentFilters”的表,其中包含“DocumentId”(Int)和“DocGUID”(Guid)列。两个表之间的“Doc Id”上有一个 FK。 Documents 和 DocumentFilters 表之间是一对多 Id 的关系。模型如下所示:

我正在尝试使用 NuGet 包中的 DynamicLibrary.cs 库编写动态 LINQ 查询。

使用常规 Linq,查询在 c# 中看起来像这样:

DocDBContext db = new DocDBContext();
var documents = db.Documents.Include(d => d.DocumentFilters);
Guid gTest = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");

documents = documents.Where(d => d.DocumentFilters.Select(f => f.DocGUID).Contains(gTest));

这完美地工作并检索由我感兴趣的 GUID 过滤器分隔的文档。但是,我需要将它动态地放置在过滤器字符串中,它可能包含其他过滤器。有可能这样做吗?我试过这样的代码:

documents = documents.Where("DocumentFilters.Select(DocGUID).Contains(@0)", gTest);

错误:不存在适用的聚合方法“Select”

documents = documents.Where("DocumentFilters.DocGUID=@0", gTest);

错误:DocumentFilters 上不存在 GUID 属性。 (这是有道理的,因为 DocumentFilters 是一个集合)。

我还认为值得一试:

documents = documents.Where("DocumentFilters.AsQueryable().Select(DocGUID).Contains(@0)", gTest);

但同样,该库似乎不支持 AsQueryable 并抛出 错误:不存在适用的聚合方法“AsQueryable”。

是否可以在 Documents 表中对可枚举对象的属性编写这样的限制?

【问题讨论】:

    标签: c# entity-framework-6 ienumerable one-to-many dynamic-linq


    【解决方案1】:

    因此,一种解决方案是通过将“Select”添加到ExpressionParser 类中的IEnumerableSignatures 接口来修改Dynamic.cs。并将其添加到ParseAggregate() 方法中:

    if (signature.Name == "Min" || signature.Name == "Max")
            {
                typeArgs = new Type[] { elementType, args[0].Type };
            }
            else if (signature.Name == "Select")
            {
                typeArgs = new Type[] { elementType, Expression.Lambda(args[0], innerIt).Body.Type };
            } 
    

    但是,在此之后,我仍然需要重载 Contains() 方法以使用 GUID。我没有费心去做那件事。相反,我意识到我可以简单地使用已经支持的.Any() 而不是.Select()

    documents = documents.Where("DocumentFilters.Any(DocGUID.Equals(@0))", gTest); //!!!
    

    我还必须将列名从“GUID”更改为“DocGUID”,因为在限制字符串中写入 GUID.Equals() 时,解析器将其误认为是GUID 类型而不是列名,并抛出 Equals() 不是类型 GUID 的有效扩展的错误。

    抱歉浪费了大家的时间!

    【讨论】:

      【解决方案2】:

      尝试使用Dynamic Linq,它可以用于字符串。

      【讨论】:

      • 我正在尝试使用它。无论如何,我已经找到了解决方案。谢谢!
      猜你喜欢
      • 2015-03-24
      • 2011-04-01
      • 2016-12-15
      • 2013-11-24
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 2017-01-28
      • 2011-12-17
      相关资源
      最近更新 更多