GetByID method

Jan 24, 2012 at 6:21 PM

Hi,

why there isn't any GetByID method in your code?

I think Single() is not a solution because it will locate the whole data set into the memory and only after this it will filter my data. 

Coordinator
Jan 24, 2012 at 11:21 PM
Edited Jan 24, 2012 at 11:24 PM

Hello QuadroPlay,

First of all thank you for using EntityFramework.Patterns.

Regarding the lack of a getById() method, in fact searching with the identifier is a special case of a generic search pattern that can be achieved with the Find() method.

Let's start by using Single, which in reality is not as horrible as you think.

 

repo.Single (x => x.Id == 3) generate the following query:

 

 

SELECT TOP (2)
[Extent1]. [Id] AS [Id]
[Extent1]. [Name] AS [Name]
FROM [dbo]. [Workbench] AS [Extent1]
WHERE 3 = [Extent1]. [Id]

As you can see, EF do not load the whole table in memory; just 2 lines.

 

If the identifier is unique we can improve a bit by using the First() method like this:
 

repo.First (x => x.Id == 3) 

which results in :

 

SELECT TOP (1)
[Extent1]. [Id] AS [Id]
[Extent1]. [Name] AS [Name]
FROM [dbo]. [Workbench] AS [Extent1]
WHERE 3 = [Extent1]. [Id]

 
But as I said at the beginning, the search by Id is a special case, so we can use the Find() method

 

 

repo.Find (y => y.Id == 3). Take (1)

   

 

produces the following SQL:

 

SELECT
[Extent1]. [Id] AS [Id]
[Extent1]. [Name] AS [Name]
FROM [dbo]. [Workbench] AS [Extent1]
WHERE 3 = [Extent1]. [Id]


This last query is probably the closest that everyone would have written by hand.

 


Does this answer your question?

Jan 26, 2012 at 5:22 PM

Yes, thanks a lot for your response. It is clear now

Sep 17, 2012 at 6:33 PM

What about a SingleorDefault and a FirstOrDefault since .Single / .First / .Find throws an exception when Sequence contains no elements

Coordinator
Sep 19, 2012 at 3:13 PM
Edited Sep 19, 2012 at 3:14 PM
l_wolf wrote:

What about a SingleorDefault and a FirstOrDefault since .Single / .First / .Find throws an exception when Sequence contains no elements

Hello I_Wolf,

SingleOrDefault and FirstOrDefault work and won't throw any exception.

Their usage instead of Single and First depends on your requirements.

Back to the original question, I think it's better/safer to throw an exception if you are looking for an element with the key primary and the query does not return results.