【问题标题】:Interpreting byte[] in stored procedure在存储过程中解释 byte[]
【发布时间】:2011-05-06 19:27:27
【问题描述】:

我们通过加密搜索字段并比较这些加密值来搜索加密字段。我需要做的是将加密的值(通过 Entity Framework 4)传递到 proc(通过 Entity Framework 4)(因为代码对其进行加密),但如果未提供该值,也允许为 null。

所以我需要传入一个字节[],但它也需要接受空值......这甚至可能吗,或者如果不是,有什么解决方法?再次,我通过实体框架调用存储过程。

谢谢。

【问题讨论】:

  • NULL 是 byte[] 引用的有效值....那么问题是什么?
  • 你使用的是什么数据库? MySQL、MSSQL 等?
  • 对不起,SQL Server。 byte[] 数组为空,OK。我不确定 EF 是否会有任何问题......或者即使 EF 以相同的方式将 varbinary 值转换为字节数组。我知道 LINQ to SQL 有点不同。
  • @Tejs 实际上你确定,我说的是存储过程的 EF 包装器;我的同事试图传递空值,但不能。

标签: c# .net sql-server stored-procedures entity-framework-4


【解决方案1】:

给定这个存储过程:

create procedure dbo.pConvertBytesToInt

  @bytes varbinary(4)

as

  select convert(int,@bytes)

go

下面的代码会执行它,如果传递的参数为null,则传递NULL:

static int? Bytes2IntViaSQL( byte[] @bytes )
{
  int? value ;
  const string connectionString = "Data Source=localhost;Initial Catalog=sandbox;Integrated Security=SSPI;" ;
  using ( SqlConnection connection = new SqlConnection( connectionString ) )
  using ( SqlCommand    sql        = connection.CreateCommand() )
  {
    sql.CommandType = CommandType.StoredProcedure ;
    sql.CommandText = "dbo.pConvertBytesToInt" ;

    SqlParameter p1 = new SqlParameter( "@bytes" , SqlDbType.VarBinary ) ;
    if ( @bytes == null ) { p1.Value = System.DBNull.Value ; }
    else                  { p1.Value = @bytes              ; }

    sql.Parameters.Add( p1 ) ;

    connection.Open() ;
    object result = sql.ExecuteScalar() ;
    value = result is DBNull ? (int?)null : (int?)result ;
    connection.Close() ;

  }

  return value ;
}

这个测试工具

static void Main( string[] args )
{
  byte[][] testcases = { new byte[]{0x00,0x00,0x00,0x01,} ,
                         null                   ,
                         new byte[]{0x7F,0xFF,0xFF,0xFF,} ,
                       } ;

  foreach ( byte[] bytes in testcases )
  {
      int? x =  Bytes2IntViaSQL( bytes ) ;
      if ( x.HasValue ) Console.WriteLine( "X is {0}" , x ) ; 
      else              Console.WriteLine( "X is NULL" ) ;
  }

  return ;
}

产生预期的结果:

X is 1
X is NULL
X is 2147483647

【讨论】:

    【解决方案2】:

    我们最终通过将其作为字符串推送,然后在 proc 中解析它来使其工作。那行得通。但我相信我读到有一个表示 byte[] 数组的 Binary 对象,这也可以。

    【讨论】:

      猜你喜欢
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多