不允许从数据类型nvarchar隐式转换为varbinary(max) [英] Implicit conversion from data type nvarchar to varbinary(max) is not allowed
本文介绍了不允许从数据类型nvarchar隐式转换为varbinary(max)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试将DBNull.Value插入 nullable varbinary(max)字段时,出现此异常:
I get this exception when I try to insert a DBNull.Value into a nullable varbinary(max) field:
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;
我知道SO上存在重复的问题,但我不像其他人那样使用任何String。
I know there exist duplicate questions on SO, but I do NOT use any String like the others do.
我怎么了?
更新:
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();
}
}
推荐答案
为什么不要将您的SQL更改为:
Why not change your SQL to:
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,将具有相同的效果。
If it's always NULL, that will have the same effect.
否则,请尝试两行:
var binary1 = insertCMD.Parameters.Add("@ErrorScreenshot", SqlDbType.VarBinary, -1);
binary1.Value = DBNull.Value;
否则,在您原始的SQL插入语句中,您没有定义参数类型,而是传入varbinary ,因此是错误。
Otherwise, in your original SQL insert statement, you're not defining the parameter type but passing in varbinary, hence the error.
这篇关于不允许从数据类型nvarchar隐式转换为varbinary(max)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文