Steven Zack
Steven Zack

Reputation: 5104

How to save image into sql-server using linq?

I'm trying to save image into sql-server using linq. I set the field type to be image, in my application I use a fileupload controler to read the image file as byte[]. Here comes the question, it cannot convert byte[] to binary when I evaluate the image field. Do you think it's a good way to save image?

My code:

Stream imgStream = FileUpload1.PostedFile.InputStream;
int imglen = FileUpload1.PostedFile.ContentLength;
string imgContentType = FileUpload1.PostedFile.ContentType;
string imgName = FileUpload1.PostedFile.FileName;
byte[] imgBinaryData = new byte[imglen];
int n = imgStream.Read(imgBinaryData, 0, imglen);
ImgStore info = new ImgStore();
info.pic = imgBinaryData;// it cannot implictly convert type 'byte[]' to Linq.Binary
info.type = imgContentType;
info.fileName = imgName;

Upvotes: 2

Views: 6607

Answers (2)

Remus Rusanu
Remus Rusanu

Reputation: 294197

Using LINQ to store images is going to be very inefficient because all APIs require at least one complete in-memory byte array the of image size. Even under moderate load this breaks quickly as the memory gets exhausted in spurious large array copies. I recommend you use streaming semantics, which avoid the problem of passing in and out large byte arrays into the ADO.Net API. See these two articles for complete working code which takes the HTTP POST uploaded file as a stream and transfers it into the database in a buffered stream (chuncked) manner, and similarly transfers the image from the database to the HTTP response in a similar fashion:

The code is also available on CodeProject.

Upvotes: 3

Brian Webster
Brian Webster

Reputation: 30855

Storing images with LINQ to SQL: Converting byte array or stream to Binary

To convert a byte array to a LINQ Binary, you can utilize the Binary constructor:

MyObject.BinaryProperty = new Binary(bytes);

References

Upvotes: 4

Related Questions