Cannot implicitly convert the type System.Linq.IQueryable <string> to a string

I have two tables named Rank and CrewMembers. I want to get the rank name that is in the rank table, based on the identifier CrewMember.I passed the crew as a parameter and based on this method will return the rank of this particular crew member. This is my code -

       public string GetRank(int CrewId)
       {

        string rank = (from r1 in context.Rank
            join r2 in context.CrewMember on r1.RankId equals r2.RankId
            where r2.CrewId == CrewId
            select r1.RankName);

        return rank;
      }

When I create the code, I get the following error:

Cannot Implicitly Convert System.Linq.IQueryable Type to String

where am i wrong

+4
source share
1 answer

You should use FirstOrDefault or SingleOrDefault:

public string GetRank(int CrewId)
{       
    string rank = (from r1 in context.Rank
        join r2 in context.CrewMember on r1.RankId equals r2.RankId
        where r2.CrewId == CrewId
        select r1.RankName).SingleOrDefault();

    return rank;
 }
+12
source

All Articles