2017-04-17 136 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); 
}