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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With