how to return false if no records exist in table

Total Post:96

Points:676
C# 
 1072  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. 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);
    }

      Modified On Apr-07-2018 02:23:33 AM
  1. 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;
            }
        }

      Modified On Apr-07-2018 02:23:08 AM

Answer