好的,也許我正在繞過這個錯誤。我們將看到。C#用DBNull.value更新數據庫條目似乎錯誤
因此,我正在檢查一些數據。這些數據將會是Int32類型。或多或少,如果該物品不是我的標誌之一,我想將其設置爲DBNull.value
,我相信。
我想確定的是列是可以爲空的,所以如果我不輸入任何東西,它應該被設置爲null。
這裏是我的程序邏輯:
int content = 5; //set for sake of program;
int test;
if(content == 5){
test = content;
}else{
//i want test to be labeled as DBNULL.
//didnt know if i could redefine here to be like:
// free(test); DBNull test = new DBNull;
}
//my companys db command
CommandFactory cmd = new CommandFactory();
cmd.commandText = "insert into TABLE (value) values (@a)";
cmd.addInputParameters("@a", test, DBType.Int32);
...
在這種情況下,怎麼會是等它的DBNull?如:
if(test != -1){
cmd.addInputParameters("@a", test, DBType.Int32);
}
//no param would be entered for @a, maybe forcing it to be null?
在表的定義,值是空的,所以你不必擔心。
雖然正確答案張貼,它是不是一個最後我用我的同事也沒有要我做「魔法」與??,所以他們有我做:
int? temp;
if(temp.HasValue){
cmd.addInputParameters("@a", temp, DBType.Int32);
}else{
cmd.addInputParameters("@a", DBNull.Value, DBType.Int32);
}
我建議你學習LINQ to Entities,除非你有一個很好的理由去做這個原始的方法。 – Jeroen