2017-04-17 20 views
0

我有一個SQL Server表,其中列NameHashbinary(16)類型,它允許空值。如何在C#中將System.Data.Linq.Binary分配給null?

在我的C#應用​​程序,我有一個非常基本的MD5哈希擴展方法:

public static byte[] CalculateMD5HashBinary(this string input) 
{ 
    if (String.IsNullOrEmpty(input)) 
    { 
     return null; 
    } 

    MD5 md5 = System.Security.Cryptography.MD5.Create(); 
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); 

    return md5.ComputeHash(inputBytes); 
} 

我使用LINQ to SQL分配值:

var fooBar = MyContext.FooBars.First(); 
fooBar.NameHash = fooBar.Name.CalculateMD5HashBinary(); 
MyContext.SubmitChanges(); 

Name爲空或爲空, NameHash列應該爲空。但是,當我將這個值保存在數據庫中時,我檢查了我看到的十六進制字符串0x00000000000000000000000000000000的值。

它爲什麼這樣做?我如何獲得正確分配到NameHash二進制列中的空值?

回答

0

我想到了一些亂七八糟的東西后。

LINQ-to-SQLBinary(16) SQL-Server類型,並在C#中將其類型System.Data.Linq.Binary

您可以將Byte[]的值指定爲Binary變量,並對兩者進行布爾比較,因此我使用它們可以互換。

我意識到返回類型Byte[]的擴展方法是將{""}設置爲NameHash值,而不是出於任何原因。我將返回類型更改爲Binary並解決了我的問題。

using System.Data.Linq; 

public static Binary CalculateMD5HashBinary(this string input) 
{ 
    if (String.IsNullOrEmpty(input)) 
    { 
     return null; 
    } 

    MD5 md5 = System.Security.Cryptography.MD5.Create(); 
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); 

    return md5.ComputeHash(inputBytes); 
} 
相關問題