c# - 使用 firstordefault 时指定的转换无效

标签 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);
        }

最佳答案

我相信使用

Convert.ToInt32(fvDetails.DataKey.Value)

在linq语句中不允许

关于c# - 使用 firstordefault 时指定的转换无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18578854/

相关文章:

SQL 服务器 2012 : sum over order by gives error Incorrect syntax near 'order'

sql-server - 尝试读取跟踪文件时出现 SQL Server 错误 5 : “5(Access is denied. )

c# - 更改Word中的文本背景颜色

c# - DownloadFile 停止下载文件

c# - 从单独的后台工作人员更改表格

c# - 如何选择 LINQ GroupBy 子句中的最后一条记录

c# - WPF Storyboard延迟播放wma文件

c# - LINQ 选择具有不同 ForeignKeyId 列的最新记录

c# - 如何创建 LINQ 查询以从对象字段内的数组生成唯一的对象列表?

visual-studio-2010 - 在 ssis 包中使用临时表