5

in my SQL Server DB table, I have the binary column type.

I can't execute the query, why ?

var data = (from x in model.MyTable
            where x.BinaryColumn[0] == 1
            select x).FirstOrDefault();

I get the The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities error

Tony
  • 12,405
  • 36
  • 126
  • 226
  • What is the type of `BinaryColumn`? – haim770 May 11 '15 at 17:44
  • Because the Entity Framework doesn't know how to translate it to TSQL. – xanatos May 11 '15 at 17:44
  • haim770 >> it's the `byte[]` type in C# – Tony May 11 '15 at 17:46
  • This isn't the kind of calculation that can be performed by the SQL server; The only way you'll be able to do this would be to pull the entire table and then filter the table at the client, which isn't ideal. What is the context of this query? Maybe there is another way to structure the query? – Claies May 11 '15 at 17:48
  • Depending on how you are using Entity Framework (edx file, code first, ...) perhaps it is possible to define a user defined function to return a scalar (the first byte of the BinaryColumn). In SQL you could retrieve it with a `SUBSTRING(BinaryColumn, 1, 1)` – xanatos May 11 '15 at 17:59

3 Answers3

4

These expressions are translated to SQL queries, and this is one of the things you cant do. Take a look here for more detail: LINQ To Entities doesn't recognize array index

Community
  • 1
  • 1
Jon Koivula
  • 899
  • 1
  • 11
  • 24
3

In TSQL the SUBSTRING function can be used on binary/varbinary.

Somewhere define:

[DbFunction("SqlServer", "SUBSTRING")]
public static byte[] SubString(byte[] field, int start, int length)
{
    throw new NotSupportedException("Direct calls are not supported.");
}

then

var data = (from x in model.MyTable
            where Substring(x.BinaryColumn, 1, 1) == new byte[] { 1 }
            select x).FirstOrDefault();
xanatos
  • 109,618
  • 12
  • 197
  • 280
1

If you're willing to change your query a bit, this would work:

var data = (from x in model.MyTable
            where SqlFunctions.CharIndex(new byte[] { 1 }, x.BinaryColumn) == 1
            select x).FirstOrDefault();

See MSDN

haim770
  • 48,394
  • 7
  • 105
  • 133