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

旧时模样 提交于 2019-12-10 15:13:47

问题


I have two tables named Rank and CrewMembers.I want to fetch the name of rank which is present in Rank table on the basis of id of CrewMember.I have passed the crewId as a parameter and on the basis of that the method would return the Rank of that specific Crew Member.This is how my code is-

       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 build the code ,I get the following error-

Cannot implicitly convert type System.Linq.IQueryable to string

where am I going wrong?


回答1:


You should to 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;
 }


来源:https://stackoverflow.com/questions/19875473/cannot-implicitly-convert-type-system-linq-iqueryablestring-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!