我有一个问题,从LINQ中的匿名类中的属性返回一个可空的double和int。我的选择声明在这里:
return from workS in db.vWorkstations
join custF1 in db.CustomFields.Where(x => x.CustomFieldID == cuField[0].ID)
on intAreaNumber equals custF1.Area into tmpCust1
from custF1 in tmpCust1.DefaultIfEmpty()
join custFV1 in db.CustomFieldValues
on new DummyClass{P1 = workS.WorkstationID, P2 = custF1.CustomFieldID}
equals new DummyClass
{
P1 = custFV1.WorkstationID.HasValue ? custFV1.WorkstationID.Value : -1
, P2 = custFV1.CustomFieldID
} into tmpCustFV1
from custFV1 in tmpCustFV1.DefaultIfEmpty()
select new
{
WorkstationID = workS.WorkstationID
, CallName = workS.CallName
, CustomFieldString1 = (cuField[0].TypeID == 1) ? custFV1.FieldValue : ""
, CustomFieldSelection1 = (cuField[0].TypeID == 2) ? custFV1.FieldValue : ""
, CustomFieldNumber1 = (custFV1.FieldValue != null && cuField[0].TypeID == 3) ? new Nullable(int.Parse(custFV1.FieldValue)) : (int?)null
, CustomFieldAmount1 = (custFV1.FieldValue != null && cuField[0].TypeID == 4) ? new Nullable(Double.Parse(custFV1.FieldValue)) : new Nullable()
, CustomFieldDateTime1 = (custFV1.FieldValue != null && cuField[0].TypeID == 5) ? new Nullable(DateTime.ParseExact(custFV1.FieldValue,"yyyyMMdd",provider)) : new Nullable()
};
它编译,但不运行。问题在于
行 ,CustomFieldNumber1 = (custFV1.FieldValue != null && cuField[0].TypeID == 3)
? new Nullable<int>(int.Parse(custFV1.FieldValue))
: (int?)null
,CustomFieldAmount1 = (custFV1.FieldValue != null && cuField[0].TypeID == 4)
? new Nullable<Double>(Double.Parse(custFV1.FieldValue))
: new Nullable<Double>()
正如您所看到的,我尝试了两种不同的返回null值的方法,但它们都不起作用。如果我删除解析,只返回一个字符串,它的工作原理。不幸的是,这对我来说不是一个选择。
查询失败并显示错误:
base {System.SystemException} = {“参数'value'是错误的类型。预期'System.Nullable
1[System.Double]'. Actual 'System.Nullable
1 [System.Int32]'。”}
可能有什么不对?提前致谢
答案 0 :(得分:0)
你不应该在这里只返回null -
,CustomFieldNumber1 = (custFV1.FieldValue != null && cuField[0].TypeID == 3)
? new Nullable<int>(int.Parse(custFV1.FieldValue))
: null
答案 1 :(得分:0)
是的,我看到了Nullable()。我最终做了一个解决方法。在数据库中创建一个函数,如果它被告知,它将返回原始值为十进制或null。工作,但可能不那么漂亮。
,CustomFieldAmount1 = db.fn_ConvertVarcharToDecimal(custFV1.FieldValue,(custFV1.FieldValue != null && cuField[0].TypeID != 4) )