嗨,我得到一个奇怪的错误需要另一组眼睛
我有这段代码:
con.Open();
var cmd = new SqlCommand("INSERT INTO [lntmuser].[attach] ([sysid],[name],[att_size],[cid],[flags],[contents]) VALUES (@sysid, @name, @att_size, @cid, @flags, @contents)", con) { CommandType = CommandType.Text };
(Blah, Blah, ASIGN FIRST 5 VALUES, These All work)
cmd.Parameters.AddWithValue("@contents", SqlDbType.Image).Value = aa.contents ?? (object) DBNull.Value;
其中aa.contents的类型为byte []。刚开始尝试没有
"?? (object) DBNull.Value;"
我得到了一个“插入期望@contents参数”所以我添加了?? (对象)DBNull.Value;现在,当我运行单元测试时,我得到以下难看的错误:
RestoreTest.TestMultiParAttLookUp : FailedSystem.Data.SqlClient.SqlException : Operand type clash: nvarchar is incompatible with image
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at bcDAL.RestoreFunc.ExecuteSQL(List`1 emailIds, List`1 attIds, String conStrA, String conStrM) in RestoreFunc.cs: line 173
at bcDAL.RestoreFunc.RestoreEntry(String sysid, String conStrA, String conStrM) in RestoreFunc.cs: line 22
at tcUnitTests.RestoreTest.TestMultiParAttLookUp() in RestoreTest.cs: line 18
nvarchar在哪里玩? I was looking at this question但是我在分配值之前明确说明了SQL数据类型。
我可能只需要一些睡眠哈哈。提前谢谢。
答案 0 :(得分:2)
这里的问题是,ADO.NET无法分辨出DBNull.Value
是什么类型,如您引用的问题中所述。就像答案所说,ADO.NET无法分辨它是什么数据类型,所以默认为一个。
它不是那么漂亮,并没有遵循与其他人相同的惯例,但它会完成工作。建议把它放在2+行而不是你已经拥有的单行。
var contentsParam = new SqlParameter("@contents", SqlDbType.Image);
contentsParam.Value = aa.contents ?? (object) DBNull.Value;
cmd.Parameters.Add(contentsParam);
cmd.ExecuteNonQuery();