如何在linq查询中强制将字符串转换为int

时间:2017-07-16 16:50:51

标签: c# entity-framework linq

我收到错误

  

LINQ to Entities无法识别方法' Int32 Parse(System.String)'方法,并且此方法无法转换为商店表达式

在我的问题被称为重复之前,请完整阅读。我已经四处寻找并为此寻找了一些解决方案,但似乎没有一个适合这个......

var query = from royalHIstory in ctx.tblRoyalHistories
    join historyComment in ctx.tblRoyalHistoryComments
    on royalHIstory.RoyalHistoryID equals historyComment.RoyalHistoryID
    orderby royalHIstory.IndexNum ascending
    where royalHIstory.InstNmbr == instnmbr
    select new
    {
        RoyalHistoryID = royalHIstory.RoyalHistoryID,
        RoyalHistoryCommentID = historyComment.RoyalHistoryCommentID,
        InstNmbr = royalHIstory.InstNmbr,
        IndexNum = royalHIstory.IndexNum,
        RoyalIns = royalHIstory.RoyalIns,
        RoyalComment = historyComment.Comment,
        Name = (from memberName in ctx.tblMembers
               join instruct in ctx.tblInstructors
               on memberName.MemberID equals instruct.MemberID
               where Convert.ToInt32(instruct.InstructorInstrNo) == royalHIstory.RoyalIns
               select memberName.MemberFirstName + " " + memberName.MemberLastName).FirstOrDefault()
    };

错误落在我的where子句中,转换

  

其中Convert.ToInt32(instruct.InstructorInstrNo)== royalHIstory.RoyalIns

我需要转换才能发生

  

Convert.ToInt32(instruct.InstructorInstrNo)

我不知道如何强迫它发生

1 个答案:

答案 0 :(得分:0)

你不能使用

Convert.ToInt32(instruct.InstructorInstrNo)
在LINQ查询中

,如果要转换为int,请尝试使用

var query = (from royalHIstory in ctx.tblRoyalHistories
join historyComment in ctx.tblRoyalHistoryComments
on royalHIstory.RoyalHistoryID equals historyComment.RoyalHistoryID
orderby royalHIstory.IndexNum ascending
where royalHIstory.InstNmbr == instnmbr
select new {royalHIstory,historyComment }).AsEnumerable().Select(row=>new
{
    RoyalHistoryID = row.royalHIstory.RoyalHistoryID,
    RoyalHistoryCommentID = row.historyComment.RoyalHistoryCommentID,
    InstNmbr = row.royalHIstory.InstNmbr,
    IndexNum = row.royalHIstory.IndexNum,
    RoyalIns = row.royalHIstory.RoyalIns,
    RoyalComment = row.historyComment.Comment,
    Name = (from memberName in ctx.tblMembers
           join instruct in ctx.tblInstructors
           on memberName.MemberID equals instruct.MemberID
           where Convert.ToInt32(instruct.InstructorInstrNo) == row.royalHIstory.RoyalIns
           select memberName.MemberFirstName + " " + memberName.MemberLastName).FirstOrDefault()
});