使用firstordefault时,指定的强制转换无效

时间:2013-09-02 18:18:23

标签: c# linq sql-server-2012

运行附加代码时,我在foreach行收到“Specified cast is invalid”错误。我已检查重新检查.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);
        }

2 个答案:

答案 0 :(得分:0)

我相信使用

Convert.ToInt32(fvDetails.DataKey.Value)
linq语句中不允许

答案 1 :(得分: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