![](/img/trans.png)
[英]EF6 MySQL StrongTypingException When Column is not PK
[英]StrongTypingException when setting column value
任何人都可以告訴我為什么在將值賦值給強類型DataTable中的列時會出現StrongTypingException? (我明白為什么如果我用DBNull值讀取列,我會得到它)
在下面的示例中,我嘗試將一個DataTable中的值分配給另一個(示例中的所有列都是Int32類型)。 我可以為'newOrderRow.items'列分配一個值,但是當我對'newOrderRow.debcode'列執行相同操作時,會拋出異常! 為什么?!
到目前為止我嘗試過的一些事情(沒有任何運氣):
- 分配硬編碼值而不是'calclineRow.debcode'
- 在分配另一個值之前調用newOrderRow.SetdebcodeNull()
- 將'orderrows'表中'debcode'列的DefaultValue屬性從DBNull更改為-1, 並且STILL拋出異常並說它是DBNull!
myDataSet.orderrowsRow newOrderRow;
foreach (MyDataSet.calclinesRow calclineRow in myDataSet.calclines)
{
newOrderRow = myDataSet.orderrows.NeworderrowsRow(); //Create new 'orderrows' row
//Assign values from one DataTable to another
if (!calclineRow.IsitemsNull())
newOrderRow.items = calclineRow.items; //calclineRow.items == 1. Assignment successful
if (!calclineRow.IsdebcodeNull())
newOrderRow.debcode = calclineRow.debcode; //calclineRow.debcode == 556. Assignment raises System.Data.StrongTypingException ! (See message below)
myDataSet.orderrows.AddorderrowsRow(newOrderRow);
}
/*Exception Message:
=====================
System.Data.StrongTypingException: The value for column 'debcode' in table 'orderrows' is DBNull.
---> System.InvalidCastException: Specified cast is not valid.
at MyProject.MyDataSet.orderrowsRow.get_debcode() in Q:\MyProjFolder\DataSets\MyDataSet.Designer.cs:line 21680
*/
如果nullable屬性為null,則必須使用自動生成的SetNull
方法:
if (!calclineRow.IsitemsNull())
newOrderRow.items = calclineRow.items;
else
newOrderRow.SetitemsNull();
if (!calclineRow.IsdebcodeNull())
newOrderRow.debcode = calclineRow.debcode;
else
newOrderRow.SetdebcodeNull();
您還必須將新的DataRow
到循環中的表中,因為NeworderrowsRow
不會自動執行此操作。
myDataSet.orderrows.AddNeworderrowsRow(newOrderRow);
發生異常的行(MyDataSet.Designer.cs:行21680)表明它是從DataSet
的自動生成的方法引發的,該方法讀取此屬性。 由於您還沒有使用SetdebcodeNull
因此它不知道它為null並在嘗試讀取時拋出StrongTypingException
。
你可以試試這個:
if (!calclineRow.IsdebcodeNull())
newOrderRow["debcode"] = calclineRow.debcode;
雖然我承認它沒有多大意義,但似乎調用Set
for newOrderRow.debcode具有調用Get
的效果,如上所述,如果底層屬性為DbNull則拋出異常。
解決了。 對不起這是我的錯。
我忘記了我正在使用DataTable上的OnColumnChanging事件處理程序中的'debcode'列進行操作。 當我禁用它時它一切正常。
不管怎么說,還是要謝謝你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.