HOW TO RETURN FALSE IF NO RECORDS EXIST IN TABLE

ben reitman

Total Post:96

Points:676
Posted by  ben reitman
C# 
 792  View(s)
Ratings:
Rate this:

Want to check if any records exist in ClientAccessCode table, if not return false...

 

if (!CheckAccessCodeExists())

{

    Console.WriteLine("Client Access code does not exist");

    throw new ConfigurationErrorsException("Client Access code does not exist");

}

 

private static bool CheckAccessCodeExists()

{

    using (EPOSEntities db = new EPOSEntities())

    {

        ClientAccountAccess clientAccess = db.ClientAccountAccesses

                .OrderByDescending(x => x.Id)

                .Take(1)

                .Single();

 

        if (clientAccess != null)

        {

            return true;

        }

        return false;

    }

}

//this is flagging sequence contains no elements, in the lamba expression, so how can I just return false then? some use of .Any() perhaps?

 

Thanks

  1. Alex Leblois

    Post:67

    Points:471
    Re: how to return false if no records exist in table

    The problem is Single expects there to be at least one item in the collection, if it doesn't find 1 then it throws an exception. If it's possible for your collection to not have a record then you should be using SingleOrDefault - this will return the default value for the type you are working with, in your case this will return null.

     

    ClientAccountAccess clientAccess = db.ClientAccountAccesses

        .OrderByDescending(x => x.Id)

        .Take(1)

        .SingleOrDefault();

     

    if (clientAccess != null)

    {

        db.DeleteObject(clientAccess);

    }

  1. Barbara Jones

    Post:13

    Points:91
    Re: how to return false if no records exist in table

    private static bool CheckAccessCodeExists()

        {

            using (EPOSEntities db = new EPOSEntities())

            {

                var item = db.ClientAccountAccesses.FirstOrDefault();

                if(item != null)

                {

                   db.Remove(item);

                   db.SaveChanges();

                   return true;                

                }

     

                return false;

            }

        }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!