[英]How to assign System.Data.Linq.Binary to null in C#?
I have an SQL Server table with a column NameHash
with type binary(16)
which allows nulls. 我有一个SQL Server表,其中的
NameHash
列类型为binary(16)
,该列允许为空。
In my C# application, I have a very basic MD5 hashing extension method: 在我的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);
}
I am using LINQ to SQL
to assign the value: 我正在使用
LINQ to SQL
来分配值:
var fooBar = MyContext.FooBars.First();
fooBar.NameHash = fooBar.Name.CalculateMD5HashBinary();
MyContext.SubmitChanges();
When Name
is null or empty, the NameHash
column should be null. 如果
Name
为null或为空,则NameHash
列应为null。 However, when I save this value in the DB, I check the values I see the hex string 0x00000000000000000000000000000000
instead. 但是,当我将该值保存在数据库中时,我检查了值,但看到的是十六进制字符串
0x00000000000000000000000000000000
。
Why does it do this? 为什么这样做呢? How can I get a null value properly assigned into the
NameHash
binary column? 如何获得正确分配给
NameHash
二进制列的空值?
I figured this out after some messing around. 经过一番混乱后,我想出了这一点。
LINQ-to-SQL
takes the Binary(16)
SQL-Server type and makes it of type System.Data.Linq.Binary
in C#. LINQ-to-SQL
采用Binary(16)
SQL-Server类型,并在C#中使其类型为System.Data.Linq.Binary
。
You can assign Byte[]
values to Binary
variables and do boolean comparisons the two, so I was using them some-what interchangeably. 您可以将
Byte[]
值分配给Binary
变量,然后对两者进行布尔比较,所以我在某种程度上可以互换使用它们。
What I realized is that my extension method of return type Byte[]
was setting {""}
to the NameHash
value instead of null for whatever reason. 我意识到,无论出于何种原因,我的返回类型
Byte[]
扩展方法都将{""}
设置为NameHash
值而不是null。 I changed the return type to Binary
and it solved my problem. 我将返回类型更改为
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.