check if record exists in database using LINQ

I am getting a cast error here but I do not understand as to why.

protected bool isPlayerdb(string userName)
{
    try
    {
        Users adminUsers = from users in SoccerEntities.Users
                           where users.roleId == new Guid("ED85788D-72DA-4D0A-8D5E-B5378FC00592") 
                           && users.UserName == userName
                           select users;

        if (adminUsers != null)
            return true;
        else
            return false;
    }
    catch (Exception ex)
    {
        throw new EntityContextException("isPlayer failed.", ex);
    }
}

Error in debugger is:

Error 11 Cannot implicitly convert type 'System.Linq.IQueryable<soccerCmsDal.Users>' to 'soccerCmsDal.Users'. An explicit conversion exists (are you missing a cast?) C:\new code\UniteCms\UniteCms\soccerCmsDal\SocerDataAccess.cs 80 23 soccerCmsDal

Jon Skeet
people
quotationmark

You're asking to assign a sequence value to single entity variable. That's like trying to do this:

// Won't work for the same reason
string name = new List<string> { "foo", "bar" };

If you're just trying to find out whether there are any results, you can use Any - and there's an overload of that taking a predicate as an argument, so you don't need a query expression at all.

Additionally, any time you find yourself writing:

if (condition)
    return true;
else
    return false;

you can just use:

if (condition)

So we end up with:

protected bool isPlayerdb(string userName)
{
    try
    {
        return SoccerEntities
            .Users
            .Any(user => user.roleId == new Guid("ED85788D-72DA-4D0A-8D5E-B5378FC00592") 
                         && user.UserName == userName)
    }
    catch (Exception ex)
    {
        throw new EntityContextException("isPlayer failed.", ex);
    }
}

Note that:

  • Your method name violates .NET naming conventions - consider PlayerExists instead
  • Catching Exception is rarely a good idea, IME - consider catching more specific exceptions
  • I've changed the name of the variable used in the predicate from users (which was the range variable name in the query expression) to user, because the predicate acts on a single user. Naming matters for clear code - making it clear whether you're dealing with a single entity or multiple entities helps readability. (That confusion was what led you to the compile-time failure.)

people

See more on this question at Stackoverflow