2011-05-06 67 views
0

我们通过加密搜索字段并比较这些加密值来搜索加密字段。我需要做的是将加密值(通过实体框架4)传递给proc(如代码加密),但如果未提供该值,则也允许为null。解释存储过程中的字节[]

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

谢谢。

+0

'NULL'是byte []引用....的一个有效值,那么问题是什么? – Tejs 2011-05-06 19:31:01

+0

你使用什么数据库? MySQL,MSSQL等? – 2011-05-06 19:31:26

+0

对不起,SQL Server。 byte []数组,空值,OK。我不确定EF是否会有任何问题......或者即使EF以同样的方式将varbinary值转换为字节数组。我知道LINQ to SQL有点不同。 – 2011-05-06 19:44:59

回答

0

我们最终通过将它作为字符串推送,然后在proc中解析它来完成它的工作。这工作。但我相信我读的是一个表示byte []数组的Binary对象,这也可以起作用。

0

鉴于这种存储过程:

create procedure dbo.pConvertBytesToInt 

    @bytes varbinary(4) 

as 

    select convert(int,@bytes) 

go 

下面的代码将执行它,传递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 
+0

好,但这不是一个实体框架的实现。 – 2011-05-09 13:09:52