John
John

Reputation: 3945

return the only record value in a table

ClientAccountAccess table will only ever have one record, containing an ID and a GUID. I want to return the GUID as string.

private static string GetAccessCode()
{
    using (EPOSEntities db = new EPOSEntities())
    {
        string clientAccessCode = from e in db.ClientAccountAccesses
                                     where string.IsNullOrWhiteSpace(e.GUID)
                                     select e.GUID;

        return clientAccessCode;
    }
}

select is throwing an error saying cant convert Ienumerable to string, but I dont want to create an IEnumerable clientAccessCode, as I said there will only ever be one record in this table and I want to return the value of the GUID.

? thanks for replies

Upvotes: 0

Views: 51

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Use FirstOrDefault() or SingleOrDefault() if there should not be more than one matched result:

private static string GetAccessCode()
{
    using (EPOSEntities db = new EPOSEntities())
    {
        var clientAccessCodes = from e in db.ClientAccountAccesses
                                where string.IsNullOrWhiteSpace(e.GUID)
                                select e.GUID;

        return clientAccessCodes.FirstOrDefault();
    }
}

Note - result of query will be of type IEnumerable<string>. You also can use lambda syntax:

private static string GetAccessCode()
{
    using (EPOSEntities db = new EPOSEntities())
    {
        return db.ClientAccountAccesses
                 .Where(e => String.IsNullOrWhiteSpace(e.GUID))
                 .Select(e => e.GUID)
                 .FirstOrDefault();
    }
}

Upvotes: 5

Related Questions