2

运行附加代码时,我在 foreach 行收到“指定的强制转换无效”错误。我已经重新检查了 .dbml 与 SQL Server (2012) 数据类型中的所有数据类型。如果我使用 firstordefault 删除 linq 语句,则不会引发异常。有什么想法,我的大脑很痛...

        // open DB context
        ERAQDataContext db = new ERAQDataContext();

        // get set of Room type Inspection codes
        var RCodes = from v in db.InspectionCodes  
                     where v.CodeType == 'R'
                     select v;            

        // loop thru inspection codes and build table of all codes, checking a checkbox
        // for the ones selected for this inspection.
        foreach (InspectionCode ic in RCodes)
        {
            TableRow tr = new TableRow();
            TableCell tc = new TableCell();
            tc.Style.Add("Width", "25px");
            CheckBox cb = new CheckBox();
            tc.Controls.Add(cb);
            tr.Cells.Add(tc);
            TableCell tc1 = new TableCell();
            tc1.Text = ic.CodeDescription;
            tc1.Style.Add("Width", "150px");
            tr.Cells.Add(tc1);

            // if this code selected on this inspection, check the checkbox and show any comments
            var RCodeComment = (from s in db.RoomCodesViews
                                where s.InspectionCodeId == ic.InspectionCodeId &&
                                s.InspectionId == Convert.ToInt32(fvDetails.DataKey.Value)
                                select s.Comments).FirstOrDefault();

            TableCell tc2 = new TableCell();
            if (RCodeComment != null)
            {
                tc2.Text = Convert.ToString(RCodeComment);
            }
            else
            {
                tc2.Text = "";
            }
            tr.Cells.Add(tc2);
            tbl.Rows.Add(tr);
        }
4

2 回答 2

0

该声明

from s in db.RoomCodesViews
where s.InspectionCodeId == ic.InspectionCodeId &&
s.InspectionId == Convert.ToInt32(fvDetails.DataKey.Value)
select s.Comments).FirstOrDefault();

返回一个IQueryable<RCodeComment>,而不是一个RCodeComment

from s in db.RoomCodesViews
where s.InspectionCodeId == ic.InspectionCodeId &&
s.InspectionId == Convert.ToInt32(fvDetails.DataKey.Value)
from c in s.Comments
select c).FirstOrDefault();

返回一个RCodeComment

于 2013-09-02T21:01:07.070 回答
0

我相信使用

Convert.ToInt32(fvDetails.DataKey.Value)

在 linq 语句中不允许

于 2013-09-02T18:19:56.800 回答