Home > DeveloperSection > Forums > how to return false if no records exist in table
ben reitman
ben reitman

Total Post:96

Points:676
Posted on    December-05-2014 2:54 AM

 ASP.Net C# 
Ratings:


 2 Reply(s)
 513  View(s)
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



Alex Leblois
Alex Leblois

Total Post:67

Points:471
Posted on    December-05-2014 6:39 AM

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

}


Barbara Jones

Total Post:13

Points:91
Posted on    December-05-2014 7:06 AM

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;

        }

    }


Don't want to miss updates? Please click the below button!

Follow MindStick