数据表用一个byte []字段作为参数传递给存储过程 [英] DataTable with a byte[] field as parameter to a stored procedure

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

问题描述

我一直在使用重用一个DataTable作为参数传递给存储过程的这个方法,它一直伟大的工作。这是简化的工作代码:



<预类=郎-CS prettyprint-覆盖> 使用(dbEntities DBE =新dbEntities())
{
变种dt的=新的DataTable();
dt.Columns.Add(ID);
dt.Columns.Add(信息);
dt.Columns.Add(CreatedOn的typeof(DateTime的));

的foreach(在randomDataSource VAR行)
{
dt.Rows.Add(
row.id,
row.message,
DateTime.Now
);
}

变种TABLETYPE =新的SqlParameter(TABLETYPE,SqlDbType.Structured);
tableType.Value = DT;
tableType.TypeName =[DBO] [RandomTableType];

dbe.ExecuteStoreCommand(
EXEC [DBO] [SaveTable] @tableType,
新的对象[] {} TABLETYPE
);
}



在出现问题时,我想补充的领域是二进制类型。即:



<预类=郎-CS prettyprint-覆盖> dt.Columns.Add(BinaryMessage的typeof(字节[])) ;

在数据库中相应的列是 VARBINARY(MAX)的方式。当我尝试运行它,我得到这个错误:




从数据类型为nvarchar(最大)到VARBINARY的隐式转换(max)是
不允许的。使用CONVERT函数来运行此查询。




如何修改我有什么使这项工作?


解决方案

在.NET中的二进制字符串的表示形式为的 SqlBinary 结构



您想添加列是这样的:

  dt.Columns.Add(BinaryMessage的typeof(SqlBinary)); 



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


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[]));

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

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

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

解决方案

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

You want to add your column like this:

dt.Columns.Add("BinaryMessage", typeof(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.

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

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