Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert system.data.linq.binary to byte[]

I am storing bytes in a database table. When I retrieve it with Linq 2 sql I get the return type in system.data.linq.Binary.

I am not able to convert the system.data.linq.binary to byte array(byte[]).

How do I convert it?

///my datacontext

var db = new db();

//key is an value from user

var img = from i in db.images
          where i.id == key
          select i.data; 

the i.data is in linq.binary I want it to be in byte[].

I tried with (byte[])img but it did not work.

like image 821
user1797079 Avatar asked Dec 25 '12 10:12

user1797079


2 Answers

Have you tried calling ToArray() on i.data?

var img = from i in db.images
      where i.id == key
      select i.data.ToArray();

System.Data.Linq.Binary has a ToArray method just for that purpose.

like image 116
Mike Two Avatar answered Sep 18 '22 13:09

Mike Two


Probably its too late by now but may help others :)

//testTable PK:ID, binaryData :binary(32)

public void insertDummyData()
{
    DBML.testTable v = new DBML.testTable ();
    v.ID = 1;

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    v.binaryData = new System.Data.Linq.Binary(encoding.GetBytes("11111111000000001111111100000000"));                                                                    

    db.testTable.InsertOnSubmit(v);
    db.SubmitChanges();
}

Or else, Click on the Binary field from .dbml file, open properties and then change the field type from Binary to byte[] as found here

like image 33
FunMatters Avatar answered Sep 19 '22 13:09

FunMatters