简体   繁体   English

如何根据子集合中的值 select 对象?

[英]How to select objects based on values in sub collection?

I have a list of Documents.我有一份文件清单。 A Document is like this:一个文档是这样的:

class Document
{
    string Name;
    string Description;
    List<Page> Pages;
}

A Page is like this:一个页面是这样的:

class Page
{
    string OCR;
}

What would be the following query in fluent LINQ against ef core 5?: I want to get all the document where "text" is in Name, or Description or OCR.在 fluent LINQ 中针对 ef core 5 的以下查询是什么?:我想获取名称、描述或 OCR 中包含“文本”的所有文档。

Is it possible to get the documents with a single fluent LINQ query?是否可以使用单个流畅的 LINQ 查询获取文档? I came up with this, but I don't know how to add the OCR bit:我想出了这个,但我不知道如何添加 OCR 位:

Documents.Where (   
                    x =>    x.Name.ToUpper ().Contains (text) 
                    ||      x.Description.ToUpper ().Contains (text)
                ).ToList ();

I know I could add a property on the Document like OCR, retrieve all the documents and then, in memory return all the OCR text from pages and then in the query do something like我知道我可以在 Document 上添加一个属性,例如 OCR,检索所有文档,然后在 memory 中返回页面中的所有 OCR 文本,然后在查询中执行类似的操作

Documents.Where (   
                    x =>    x.Name.ToUpper ().Contains (text) 
                    ||      x.Description.ToUpper ().Contains (text)
                    ||      x.OCR.ToUpper ().Contains (text)
                ).ToList ();

and that there could be other solutions, but I'd like to know if it's possible to do it in LINQ alone and against the database.并且可能有其他解决方案,但我想知道是否可以单独在 LINQ 中针对数据库执行此操作。

Thanks in advance!提前致谢!

You can simply include the Pages as a condition, which should translate properly in EF's query translation.您可以简单地包含页面作为条件,它应该在 EF 的查询翻译中正确翻译。

Here's an example, with example data:这是一个示例,带有示例数据:

var Documents = new List<Document>()
    {
        new Document
        {
            Name = "nottext",
            Description = "nottext",
            Pages = new List<Page>
            {
                new Page
                {
                    OCR = "text"
                }
            }
        },
        new Document
        {
            Name = "nottext",
            Description = "nottext",
            Pages = new List<Page>
            {
                new Page
                {
                    OCR = "text"
                }
            }
        }
    };

Documents.Where(d =>
       d.Name.Contains("text", StringComparison.OrdinalIgnoreCase)
    || d.Description.Contains("text", StringComparison.OrdinalIgnoreCase)
    || d.Pages.Any(p => p.OCR.Contains("text", StringComparison.OrdinalIgnoreCase)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM