Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting part of a single entity without retrieving the entire entity

I want to get a single property(blob) from a single entity (by Id). I have:

context.References
    .Single(r => r.ID == id)
    .Blob;

This strikes me as inefficient, because I'm getting the entire Reference, only to discard everything except the Blob. This led to

context.References
    .Where(r => r.ID == id)
    .Select(r => r.Blob)
    .Single();

Which should only query for the Blob, but having the Single as an afterthought at the end is somewhat annoying (yet enforcing the singularity I feel is necessary). My question is this: is there a better way to accomplish this, or is my second codeblock just the way it is?

Thanks!

like image 328
Matthew Fotzler Avatar asked Nov 22 '25 14:11

Matthew Fotzler


2 Answers

I'm afraid that's the way it is. Running your queries in LINQPad shows that Entity Framework translates the queries to this:

SELECT TOP (2) 
[Extent1].[Id] AS [Id], 
[Extent1].[Blob] AS [Blob], 
... etc for all columns
FROM [dbo].[References] AS [Extent1]
WHERE 1 = [Extent1].[Id]

and

SELECT TOP (2) 
[Extent1].[Blob] AS [Blob]
FROM [dbo].[References] AS [Extent1]
WHERE 1 = [Extent1].[Id]

So you're correct that the second query is slightly more efficient. Whether this is significant is something for you to test and decide.

like image 90
Phil Avatar answered Nov 25 '25 09:11

Phil


You can use context.References.Single(r => r.ID == id).Blob to combine the Where and the Single, but that will transfer the whole entity. For efficiency sake your solution is best.

like image 45
jessehouwing Avatar answered Nov 25 '25 11:11

jessehouwing