How to compare MD5 hashes stored as byte [] with Linq + entity?
I need to store a bunch of information about large files in a table on SQL Server 2005.
I am storing the complete MD5 of each file as a varbinary in SQL, and the .net database entity framework abstracts it as a byte [] array. Fair enough.
I am querying this table with a query like this, comparing hashes to check if the file is on db:
byte[] hash = inputfile.GetFileMD5();
var query = context.CurveData
.Where(n => n.MD5.Equals(hash))
.Select(n => n.MD5)
.DefaultIfEmpty(null).FirstOrDefault();
Arrays cannot be compared with .Equals (), because they compare instances, not sequences .. SequenceEqual (); However, the request runs fine. If I save the file and run a query against it, I get the correct hash from the database; many other files work fine too.
Two questions:
- How is this possible? Is there an overload of .Equals () that checks array equality?
- How do I implement the above request using .SequenceEqual ()? If I try to replace .Equals () with .SequenceEqual () I get Exception
LINQ to Entities does not recognize method 'Boolean SequenceEqual [Byte] (System.Collections.Generic.IEnumerable
1[System.Byte], System.Collections.Generic.IEnumerable
1 [System.Byte])'
source to share
The code in this request is not being executed as C # code. It is simply compiled into an object Expression
that describes what the code is, instead of being translated into IL code that can ultimately be used to execute the code. The query provider can then look at these objects Expression
to see what you wrote and do ... regardless of that information. In this particular case, it completes the translation of the code to SQL and runs the database query. This query provider knows how to translate the call to Equals
these two byte arrays into correct SQL to compare the two arrays. It was not designed to understand the method SequenceEqual
; he doesn't know how to translate this to SQL and so these are just errors.
You cannot implement this request with SequenceEqual
. You can try to convince the author of the request provider to support it or use SequenceEqual
it and then try to transform the created Expression
one so that all the calls SequenceEqual
become Equals
calls, but that would be a lot of work and I don't see it being productive.
source to share