2012-07-10 244 views
9

我得到這個例外,當我嘗試插入DBNull.Value成可空 VARBINARY(最大值)字段:從數據類型爲nvarchar到VARBINARY(最大值)的隱式轉換是不允許

Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. 

那是我的代碼:

insertCMD.Parameters.AddWithValue("@ErrorScreenshot", SqlDbType.VarBinary).Value = DBNull.Value; 

我知道這裏存在重複的問題,但我不會像其他人一樣使用任何字符串。

我該怎麼做?

UPDATE:

using (var insertCMD = new SqlCommand("INSERT INTO TestplanTeststep (TeststepId,TestplanId,CreatedAt,ErrorText,ErrorScreenshot,TestState) VALUES (@TeststepId, @TestplanId,@CreatedAt,@ErrorText,@ErrorScreenshot,@TestState)", con)) 
{ 
var p1 = insertCMD.Parameters.Add("@TeststepId", SqlDbType.Int); 
var p2 = insertCMD.Parameters.Add("@CreatedAt", SqlDbType.DateTime); 
insertCMD.Parameters.AddWithValue("@TestplanId", testplan.Id); 
insertCMD.Parameters.AddWithValue("@ErrorText", (object) DBNull.Value); 
insertCMD.Parameters.AddWithValue("@ErrorScreenshot", (object) DBNull.Value); 
insertCMD.Parameters.AddWithValue("@TestState", (int)Teststep.TeststepTestState.Untested); 

     foreach (Teststep step in teststeps) 
     { 
      p1.Value = step.Id; 
      p2.Value = step.CreatedAt; 
      insertCMD.ExecuteNonQuery(); 
     } 
    } 
+2

看起來不是正確的代碼行。 UniqueIdentifier完全沒有提及。也許提供存儲過程的定義呢? – Sean 2012-07-10 11:01:35

+0

對不起,我複製了錯誤的異常。現在更正了。 – Pascal 2012-07-10 11:11:57

+0

「AddWithValue」的第二個參數是值。不是數據類型。 – 2012-07-10 11:17:56

回答

6

爲什麼不改變你的SQL語句:

INSERT INTO TestplanTeststep 
(TeststepId,TestplanId,CreatedAt,ErrorText,ErrorScreenshot,TestState) 
VALUES 
(@TeststepId, @TestplanId,@CreatedAt,NULL,NULL,@TestState) 

或只是

INSERT INTO TestplanTeststep 
(TeststepId,TestplanId,CreatedAt,TestState) 
VALUES 
(@TeststepId, @TestplanId,@CreatedAt,@TestState) 

...並省略兩個參數?

如果它總是NULL,那會有相同的效果。

否則,嘗試在兩行:

var binary1 = insertCMD.Parameters.Add("@ErrorScreenshot", SqlDbType.VarBinary, -1); 
binary1.Value = DBNull.Value; 

否則,你原來的SQL插入語句,你沒有定義的參數類型,但傳遞VARBINARY,因此錯誤。

+0

我得到同樣的錯誤。請參閱我的發佈代碼。 – Pascal 2012-07-10 11:45:50

+0

啊你快一點就找到了-1招嘿嘿。我想明確地將其設置爲null,或者我知道表的默認行爲。 – Pascal 2012-07-10 12:49:04

15

我有同樣的問題,而插入DBNull.ValueVarbinary(Max)列。谷歌搜索後,我找到了一個解決方案,它可以幫助你以及:

您需要設置大小-1這意味着Max長度varbinary列加入您的SQL參數時:你的情況

this.cmd.Parameters.Add("@Photo", SqlDbType.VarBinary, -1).Value = DBNull.Value; 

所以:

insertCMD.Parameters.Add("@ErrorScreenshot", SqlDbType.VarBinary,-1).Value = DBNull.Value; 
相關問題