简体   繁体   中英

In Entity Framework Core, how can I query data on joined tables with a condition at DB level (not local LINQ)?

As part of a small .NET Core 3 project, I'm trying to use the data model based in Entity Framework, but I'm having some troubles related with queries on joined tables.

When looking for data matching a condition in a single table, the model is easy to understand

List<Element> listOfElements = context.Elements.Where(predicate).ToList();

However, when this query requires joined tables, I'm not sure how to do it efficiently. After some investigation, it seems that the include (and theninclude) methods are the way to go, but I have the impression that the Where clause after the include is not executed at DB level but after all the data has been retrieved. This might work with small datasets, but I don't think it's a good idea for a production system with millions of rows.

List<Element> listOfElements = context.Elements.Include(x => x.SubElement).
    Where(predicate).ToList();

I've seen some examples using EF+ library, but I'm looking for a solution using the nominal EF Core. Is there any clean/elegant way to do it?

Thank you.

There are a few scenarios when the data from DB is populating:

  • Deferred query execution: this is when you try to access your query results, for example, in the foreach statement.
  • Immediate Query Execution: this when you call ToList() (or conversions to other collections, like ToArray() ).

I think the answer's to your question:

... but I have the impression that the Where clause after the include is not executed at DB level but after all the data has been retrieved.

is that your assumptions are wrong because you are calling ToList() at the end, not before the Where method.

For more information please also check here .


I've another suggestion also: to be sure about what is exactly executing at the DB level run SQL Server Profiler when executing your query.

Hope this will help ))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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