Home > Net >  Better way to check if record exists and select in Linq/Entity Framework
Better way to check if record exists and select in Linq/Entity Framework

Time:10-08

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?

CodePudding user response:

I would probably prefer to see something like this:

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

CodePudding user response:

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.

CodePudding user response:

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);   
  • Related