[英]Specified cast is invalid when using firstordefault
運行附加的代碼時,我在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);
}
我相信使用
Convert.ToInt32(fvDetails.DataKey.Value)
linq語句中不允許
該聲明
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.