vaso123
vaso123

Reputation: 12391

Entity Framework under the hood

I have some legacy code that uses Entity Framework.

When I debug the code I can see that EF DbContext contains the whole table. It was passed by OData to the frontend, and then angular processed it.

So I tried to search, is it possible to get only a single record by EF?

Everywhere I see the SingleOrDefault method, or other IQueryable, but as I understood, these are parts of the collections.

Microsoft says: Sometimes the value of default(TSource) is not the default value that you want to use if the collection contains no elements.

Does that mean EF always get all the data from the table and I can use them later?

Or is there a way to force inner query to get only one, and only one row?

We are using postgresql.

Upvotes: 0

Views: 777

Answers (2)

RemedialBear
RemedialBear

Reputation: 644

With Entity Framework, you can use LINQ to run queries and get single records or limited sets. However, in your .NET project the controller should be parsing OData query parameters and filtering the dataset before returning results to the client application. Please check your Controller code against this tutorial to see if you might be missing something.

If you are somehow bypassing the built-in OData framework, what might help is understanding which queries execute immediately vs which ones are deferred. See this list to understand exactly which operations will force a trip to the database and try to hold off on anything with immediate execution until as late as possible.

Upvotes: 1

BradleyDotNET
BradleyDotNET

Reputation: 61339

No, EF will not SELECT the entire table into memory if you use it correctly. By correctly; I mean:

context.Table.First();

Will translate into a SQL query that only returns one row, that will then map to an object to be returned to the calling code. This is because the above code uses LINQ-to-Entities. If you did something like this instead:

context.Table.ToList().First();

Then the entire table is selected to make the ToList work, and LINQ-to-Objects handles the First. So as long as you do your queries with lazy enumeration (not realizing the result ahead of time), you'll be fine.

Upvotes: 1

Related Questions