Leron
Leron

Reputation: 9866

How to check if record with given ID already exists using EF5 and repository

For my project I am using Entity Framework 5 with Code First which I use through repositories and UnitOfWork.

When I Edit/Update an entity I want to make sure that this entity exists in the database. I'm not sure how exactly this must be done. First I thought of querying for an entity with this ID and check if the result is null (entity with this ID is not found) and base my logic on this.

Then I decided that maybe this is not the best way so now I use this:

if (unitOfWork.EntityRepository.GetAll().Any(r => r.EntityID == model.EntityID))

Where GetAll is implemented in my Repository as:

    public virtual IQueryable<TEntity> GetAll()
    {
        return dbSet;
    }

I'm not sure if there is any big difference between using Any() and just trying to get a record with by the given ID, in both ways I need to query the database (I think). But since it's something that I have to do common in my code I want to know how exactly to do it.

Upvotes: 2

Views: 938

Answers (2)

Guru Stron
Guru Stron

Reputation: 142038

as for me i prefer not to use Any() for returning bool result because it generates(EF 5) pretty ugly sql:

new Entities().Tasks
    .Any()

turns into

SELECT 
CASE WHEN ( EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[Task] AS [Extent1]
)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[Task] AS [Extent2]
)) THEN cast(0 as bit) END AS [C1]
FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]

so in your case I would better try to get record with given id and analyze the result

Upvotes: 1

Thomas Weller
Thomas Weller

Reputation: 11717

It should be equal.

The difference between the Any() and FirstOrDefault() LINQ expressions of the EF provider is that the former results in an SQL EXISTS(...) clause, the latter in a simple WHERE .... As long as you query for an indexed column, this both is blazingly fast (and interchangeable).

Upvotes: 2

Related Questions