4

I am inserting data, using EF, which contains a SHA512 Hash. I am then looking up the same data like this, but no results are returned:

var searchHash = requestToFind.GetSelfSha512Hash();
var foundRequest = _complianceContext.ScoreResults
    .Where(sr => sr.SearchHash == searchHash);

Both sr.SearchHash and searchHash are byte[].

If I take out the Where clause, I do get 1 result. Any ideas why this may be?

2
  • 1
    Try this: Convert.ToBase64String(sr.SearchHash) == Convert.ToBase64String(searchHash) Commented Jan 25, 2017 at 21:19
  • What is the SQL type of SearchHash? Can you use SQL Profiler to determine what SQL Statement is being executed? Commented Jan 25, 2017 at 21:26

2 Answers 2

10

The equality operator does not work like you expect for byte arrays. Try SequenceEqual.

var foundRequest = _complianceContext.ScoreResults
  .Where(sr => sr.SequenceEqual(searchHash));
Sign up to request clarification or add additional context in comments.

1 Comment

Based on the documentation, it is one pass through each byte array comparing corresponding bytes. I doubt that will have much impact. The only way to know for sure which approach is optimal is to profile.
1

This is how I made EF 7 build queries that compare byte[] values:

  1. Declared an empty method that accepts two byte arrays and returns bool in my context Class:
public partial class DbContext 
{
    public static bool LessThanOrEqual(byte[] a, byte[] b)
    {
       throw new NotImplementedException();
    }

  1. In DbContetx.OnConfiguring() method defined a translation from this function to an SQL tree section:
modelBuilder.HasDbFunction(
    typeof(DbContext).GetMethod(nameof(LessThanOrEqual), new[] { typeof(byte[]), typeof(byte[]) }))
    .HasTranslation(
    args =>
        new SqlBinaryExpression(
            ExpressionType.LessThanOrEqual,
            args[0],
            args[1],
            args[0].Type,
            args[0].TypeMapping)
    ); 
  1. Used this method in my Linq query:
    byte[] arr = ...
    db.tbl.Where(r => DbContext.LessThanOrEqual(r.arr1, arr) &&
                      DbContext.LessThanOrEqual(arr, r.arr2))
  1. This Linq query produces the following SQL query:
    SELECT ...
    FROM tbl
    WHERE (b.arr1 <= @__arr_0) AND (@__arr_0 <= b.arr2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.