DataTable with a byte[] field as parameter to a stored procedure

对着背影说爱祢 提交于 2019-11-30 03:53:07

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12482687/datatable-with-a-byte-field-as-parameter-to-a-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!