2011-05-06 73 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