如果表中没有记录,如何返回false

时间:2014-02-11 14:50:29

标签: c# asp.net linq asp.net-mvc-3

想检查ClientAccessCode表中是否存在任何记录,如果没有返回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;
    }
}

//这是标记序列,在lamba表达式中不包含任何元素,那么我怎么才能返回false呢?有人使用.Any()吗?

感谢

修改 非常感谢帮助人员现在标记答案,如果我有其他问题

ClientAccountAccess clientAccess = db.ClientAccountAccesses
                  .OrderByDescending(x => x.Id)
                  .Take(1)
                  .Single();

if (clientAccess != null)
{
    db.DeleteObject(clientAccess);
}

我怎么能重构这个来说一些比较整洁的东西呢

if (db.ClientAccountAccesses.Any())
{
    db.DeleteObject(//what does in here do I have to use above code to get record to delete?);
}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

问题是Single期望至少集合中的一个项目,如果找不到1则会抛出异常。如果您的收藏可能没有记录,那么您应该使用SingleOrDefault - 这将返回您正在使用的类型的默认值,在您的情况下,它将返回null

ClientAccountAccess clientAccess = db.ClientAccountAccesses
    .OrderByDescending(x => x.Id)
    .Take(1)
    .SingleOrDefault();

if (clientAccess != null)
{
    db.DeleteObject(clientAccess);
}

答案 2 :(得分:-1)

    private static bool CheckAccessCodeExists()
    {
        using (EPOSEntities db = new EPOSEntities())
        {
            var item = db.ClientAccountAccesses.FirstOrDefault();
            if (item != null)
            {
                db.DeleteObject(item);
                db.SaveChanges();
                return true;
            }             
        }
        return false;
    }