1

I have been using

if(_context.Foo.Any(o => o.Id == id))
{
    var myfoo = _context.Foo.Where(o => o.Id == id).FirstOrDefault();
}

to check if a record exists and select it.

Is there a more concise way to do this using a single query that returns an object if found?

1
  • 1
    var myfoo = _context.Foo.FirstOrDefault(o => o.Id == id); if it doesnt exists, myfoo willl be null. Commented Oct 7, 2022 at 18:02

3 Answers 3

4

Others already have pointed out FirstOrDefault will return null if no item matches.

I'd add that you can get really concise with pattern matching, with the added benefit of scoping your variable so it can only be used if it's not null.

if(_context.Foo.FirstOrDefault(o => o.Id == id) is Foo myfoo)
{
    // use myfoo
}
// compiler will complain if you use myfoo out here.
Sign up to request clarification or add additional context in comments.

Comments

3

I would probably prefer to see something like this:

var myFoo = _context.Foo.FirstOrDefault(x => x.Id == id);
if (myFoo != null)
{
     //do something.
}

Comments

0

You can go with which will return the object if found, else null:

var fooObject = _context.Foo
    .FirstOrDefault(x => x.Id == id);   

If you want an async version, you can do this:

var fooObject = await _context.Foo
    .FirstOrDefaultAsync(x => x.Id == id);   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.