[英]C# Entity Framework and DB - change from smallint to int
[英]Conversion error from database smallint into C# nullable int
我在smallint
數據類型的數據庫中有一個security_role_cd列。 我正在使用以下代碼將其選擇為nullable int
變量。
我收到以下錯誤:
錯誤3無法確定條件表達式的類型,因為'null'和'short'之間沒有隱式轉換
克服此錯誤的正確代碼是什么?
SELECT R.security_role_cd FROM Security_Role R WHERE security_role_name = 'Admin'
C#
int? roleID = null;
string commandText = "SELECT R.security_role_cd FROM Security_Role R WHERE security_role_name = @roleName";
SqlCommand command = new SqlCommand(commandText, connection);
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("@roleName",roleName);
SqlDataReader readerRole = command.ExecuteReader();
if (readerRole.HasRows)
{
while (readerRole.Read())
{
roleID = readerRole.GetInt16(0) == 0 ? null : readerRole.GetInt16(0) ;
}
}
readerRole.Close();
它只需要知道如何鍵入 null
:
roleID = readerRole.GetInt16(0) == 0 ? (int?)null : (int)readerRole.GetInt16(0);
我個人會緩存值:
int tmp = readerRole.GetInt16(0); // implicit widening to int here
roleID = tmp == 0 ? (int?)null : tmp;
雖然我也懷疑將0
變為null
的智慧 - 更好地使用IsDBNull
- 類似於:
if(reader.IsDBNull(0)) {
roleID = null;
} else {
roleID = (int)readerRole.GetInt16(0);
}
嘗試這個
roleID = readerRole.GetInt16(0) == 0 ? (int?) null : readerRole.GetInt16(0) ;
根據三元運算符的文檔,冒號(:)兩側的數據類型必須相同。 正如你沒有強制轉換那樣,無法確定null的類型(即,如果是nullable int,或null string,或null對象)
更新
roleID = readerRole.GetInt16(0) == 0 ? (int?) null : readerRole.GetInt32(0) ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.