3

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!

Matthew Fotzler
  • 630
  • 1
  • 6
  • 13

2 Answers2

1

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.

Phil
  • 42,255
  • 9
  • 100
  • 100
1

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.

jessehouwing
  • 106,458
  • 22
  • 256
  • 341