添付のコードを実行すると、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);
}