Brad8118
Brad8118

Reputation: 4702

How to store an image in a db using EF 4.0 with the Model first approach. MVC2

I'm trying out the EF 4.0 and using the Model first approach. I'd like to store images into the database and I'm not sure of the best type for the scalar in the entity.
I currently have it(the image scalar type) setup as a binary. From what I have been reading the best way to store the image in the db is a byte[]. So I'm assuming that binary is the way to go. If there is a better way I'd switch.

alt text

In my controller I have:

 //file from client to store in the db
 HttpPostedFileBase file = Request.Files[inputTagName];
 if (file.ContentLength > 0)
 {
   keyToAdd.Image = new byte[file.ContentLength];
   file.InputStream.Write(keyToAdd.Image, 0, file.ContentLength);
 }

This builds fine but when I run it I get an exception writing the stream to keyToAdd.Image. The exception is something like: Method does not exist.

Any ideas? Note that when using a EF 4.0 model first approach I only have int16, int32, double, string, decimal, binary, byte, DateTime, Double, Single, and SByte as available types. Thanks

Upvotes: 2

Views: 1025

Answers (1)

Brad8118
Brad8118

Reputation: 4702

Instead of using Write I should have been using Read. I'm still interested if there is a better way to store the image stream.

It was file.InputStream.Write(tmpBytes, 0, file.ContentLength);

 byte[] tmpBytes = new byte[file.ContentLength];
 file.InputStream.Read(tmpBytes, 0, file.ContentLength);
 keyToAdd.Image = tmpBytes;

Upvotes: 1

Related Questions