Soulzityr
Soulzityr

Reputation: 456

Best way to grab a single value from a table?

So I have a method designed to grab a single value from the table using a key that may or may not be in the table. My method looks like this, after changing some names around.

Using Entity Framework and Linq

public IHttpActionResult GetBool(int Id)
{
    Entity e = db.Entity.FirstOrDefault(x => x.Id== Id);

    if (e == null) return NotFound();

    return Ok(e.BoolValue);
}

This call seems unnecessary, pulling the whole entire Entity just to address one value. How do I error check for the entity possibly not existing while at the same time only grabbing the relevant columns?

My solution is something like

bool value =
            (from e in db.Entity
            where e.ID == Id
            select e.BoolValue).ToList().ElementAtOrDefault(0);
if(value== null) return NotFound();
return Ok(value);

Is this the best way to query?

Solution:

Top Answer:

return db.Entity.Where(x => x.Id== Id)
                .Select(x => Ok(x.BoolValue))
                .DefaultIfEmpty(NotFound())
                .First();

For my personal needs, I modified it to return as a JSON object.

Upvotes: 1

Views: 227

Answers (2)

var value = (from e in db.Entity
             where e.ID == Id
             select e.BoolValue).SingleOrDefault();
if(value == null) 
    return NotFound();
else 
    return Ok(value);

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460168

You could select this column and specify a default value:

return db.Entity.Where(x => x.Id== Id)
    .Select(x => Ok(x.BoolValue))
    .DefaultIfEmpty(NotFound())
    .First();

However, selecting a single record and return one of it's columns isn't really expensive. If it's causing a performance issue you should better fetch multiple records with one query instead of always executing GetBool in a loop.

Upvotes: 4

Related Questions