0

I have byte[] stored in a SQL Server database as varbinary(64) and I need to find a specific row with input byte[]. I'm using Entity Framework to access the database, thus I can run a linq query like this:

private MyTable GetMyTable(byte[] inputArray) 
{
   return _context.MyTable.FirstOrDefault(x => x.Hash.SequenceEqual(inputArray));
}

The issue is that SequenceEqual can't be translated into SQL query and the query will be evaluated locally (which is is undesirable behavior). Is it possible to replace SequenceEqual for simple compare operator ==? Or is this approach error-prone? Is there any better alternatives than this?

private MyTable GetMyTable(byte[] inputArray) 
{
   return _context.MyTable.FirstOrDefault(x => x.Hash == inputArray);
}

Note that my byte arrays will range from 32 to 64 bytes so it's not going to be huge array comparisons.

2
  • You can use Array.Equals(object, object) Commented Aug 13, 2020 at 13:13
  • Actually, using Array.Equals seem much more "right" in this case than ==. Thank you so much @jdweng Commented Aug 13, 2020 at 15:08

1 Answer 1

1

Is it possible to replace SequenceEqual for simple compare operator ==?

Probably yes, that will be tranlated to SQL as

  SELECT ...
  FROM [MyTable] AS [c]
  WHERE [c].[Hash] = @__inputArray_0

And = in SQL Server for binary/varbinary performs a byte-wise binary comparison on the values, ignoring trailing 0's. So if that's the comparison you want, then your're good to go.

Sign up to request clarification or add additional context in comments.

1 Comment

I tested both methods, == and Array.Equals as @jdweng suggested and they seems that both transforms to this. I just wanted to be sure. Thanks for your help!

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.