[英]Implicit conversion from data type nvarchar to varbinary(max) is not allowed
I get this exception when I try to insert a DBNull.Value into a nullable varbinary(max) field:当我尝试将 DBNull.Value 插入可为空的 varbinary(max) 字段时出现此异常:
Implicit conversion from data type nvarchar to varbinary(max) is not allowed.
不允许从数据类型 nvarchar 到 varbinary(max) 的隐式转换。 Use the CONVERT function to run this query.
使用 CONVERT 函数运行此查询。
This is my code:这是我的代码:
insertCMD.Parameters.AddWithValue("@ErrorScreenshot", SqlDbType.VarBinary).Value = DBNull.Value;
I know there exist duplicate questions on SO, but I do NOT use any String like the others do.我知道在 SO 上存在重复的问题,但我不像其他人那样使用任何字符串。
What do I wrong?我错了什么?
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();
}
}
I had the same problem while insertion DBNull.Value
for a Varbinary(Max)
column.在为
Varbinary(Max)
列插入DBNull.Value
时,我遇到了同样的问题。 After Googling I found a solution that may help you as well:谷歌搜索后,我找到了一个可能对您也有帮助的解决方案:
You need to set size -1 which means Max
length for varbinary column when adding your sql parameter:您需要设置大小-1 ,这意味着添加 sql 参数时 varbinary 列的
Max
长度:
this.cmd.Parameters.Add("@Photo", SqlDbType.VarBinary, -1).Value = DBNull.Value;
So in your case:所以在你的情况下:
insertCMD.Parameters.Add("@ErrorScreenshot", SqlDbType.VarBinary,-1).Value = DBNull.Value;
Why not change your SQL to:为什么不将您的 SQL 更改为:
INSERT INTO TestplanTeststep
(TeststepId,TestplanId,CreatedAt,ErrorText,ErrorScreenshot,TestState)
VALUES
(@TeststepId, @TestplanId,@CreatedAt,NULL,NULL,@TestState)
or just要不就
INSERT INTO TestplanTeststep
(TeststepId,TestplanId,CreatedAt,TestState)
VALUES
(@TeststepId, @TestplanId,@CreatedAt,@TestState)
...and omit the two parameters? ...并省略这两个参数?
If it's always NULL, that will have the same effect.如果它始终为 NULL,那将具有相同的效果。
Otherwise, try it in two lines:否则,请分两行尝试:
var binary1 = insertCMD.Parameters.Add("@ErrorScreenshot", SqlDbType.VarBinary, -1);
binary1.Value = DBNull.Value;
Otherwise, in your original SQL insert statement, you're not defining the parameter type but passing in varbinary, hence the error.否则,在原始 SQL 插入语句中,您没有定义参数类型,而是传入 varbinary,因此会出现错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.