DataTable与一个byte []字段作为存储过程的参数 [英] DataTable with a byte[] field as parameter to a stored procedure

查看:417
本文介绍了DataTable与一个byte []字段作为存储过程的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在重用这种使用DataTable作为存储过程的参数的方法,并且一直在很好。这是简化的工作代码:

I've been reusing this method of using a DataTable as a parameter to a stored procedure and it's been working great. This is the simplified working code:

using (dbEntities dbe = new dbEntities())
{
    var dt = new dataTable();
    dt.Columns.Add("ID");
    dt.Columns.Add("Message");
    dt.Columns.Add("CreatedOn", typeof(DateTime));

    foreach (var row in randomDataSource)
    {
        dt.Rows.Add(
            row.id,
            row.message,
            DateTime.Now
            );
    }

    var tableType = new SqlParameter("tableType", SqlDbType.Structured);
    tableType.Value = dt;
    tableType.TypeName = "[dbo].[RandomTableType]";

    dbe.ExecuteStoreCommand(
        "EXEC [dbo].[SaveTable] @tableType",
        new object[] { tableType }
        );
}

当我要添加的字段是二进制类型时,出现问题。即:

The problem arises when the field I want to add is of a binary type. i.e.:

dt.Columns.Add("BinaryMessage", typeof(byte[]));

数据库中的相应列是 varbinary(MAX)顺便一提。当我尝试运行它,我得到这个错误:

The corresponding column in the database is varbinary(MAX) by the way. When I try to run this, I get this error:


从数据类型nvarchar(max)到varbinary(max)的隐式转换是
不允许。使用CONVERT函数来运行这个查询。

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

如何修改我要做的工作? $ b

How do I modify what I have to make this work?

推荐答案

.NET中的二进制字符串的表示是 SqlBinary 结构

The representation for a binary string in .NET is the SqlBinary structure.

你想添加这样的列:

dt.Columns.Add("BinaryMessage", typeof(SqlBinary));

SqlBinary 类有一个显式转换为字节数组从字节数组的隐式转换,所以从字节数组到列的值是一个简单的分配问题,而从列中获取字节数组需要显式转换。

The SqlBinary class has an explicit conversion to a byte array and an implicit conversion from a byte array, so the value from a byte array to the column is a simple matter of assignment, while getting a byte array from the column requires an explicit cast.

这篇关于DataTable与一个byte []字段作为存储过程的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆