简体   繁体   English

如何修复我的“指定演员表无效”错误?

[英]How can I fix my “Specified cast is not valid” error here?

I'm trying to get the id that is a SMALLINT using OUTPUT on an insert statement and using DataContext.ExecuteQuery (or whatever DataContext method would be more appropriate). 我试图在插入语句上使用OUTPUT并使用DataContext.ExecuteQuery (或任何DataContext方法更合适)获取SMALLINT的id。

Attempt: 尝试:

            string query = $@"
                DELETE FROM MyTable WHERE [Name] = '{name}'
                INSERT INTO MyTable ([Name], ...)
                OUTPUT INSERTED.ID
                VALUES ('{name}', ...)";
            short id = (short)context.ExecuteQuery<int>(query).Single();

and I get the error 我得到了错误

System.InvalidCastException was unhandled by user code
  HResult=-2147467262
  Message=Specified cast is not valid.
  Source=System.Data
  StackTrace:
       at System.Data.SqlClient.SqlBuffer.get_Int32()
       at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)
       at Read_Int32(ObjectMaterializer`1 )
       at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
       at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)

I tried using SCOPE_IDENTITY() and same thing happened. 我尝试使用SCOPE_IDENTITY()并发生了同样的事情。

remove the 去除

OUTPUT INSERTED.ID OUTPUT INSERTED.ID

and add 并添加

; ; Select SCOPE_IDENTITY() 选择SCOPE_IDENTITY()

to the end, inside the quotes 到最后,在报价内

ExecuteQuery expects a value to be returned in the result set which is different from an output variable. ExecuteQuery期望在结果集中返回一个与输出变量不同的值。 The InvalidCastException comes from trying to convert the result set (which is null) to an int. InvalidCastException来自尝试将结果集(为null)转换为int。

Try: 尝试:

short id = context.ExecuteQuery<short>(query).Single();

That CAST exception is happening in the code when it's expecting SQL Server to return an Int32 and getting an Int16. 当期望SQL Server返回Int32并获得Int16时,代码中会发生CAST异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM