Ivo Coumans
Ivo Coumans

Reputation: 759

Saving image data as a byte[] in MSSQL through EF

The column is a varbinary(MAX) called Data. I generated an ADO.NET model from the existing database to use with EntityFramework.

Creating a new model, I set the field as follows:

Image img = Image.FromFile(filename);
var model = new Media();
MemoryStream ms = new MemoryStream();

img.Save(ms, ImageFormat.Jpeg);
model.Data = ms.ToArray(); // the model field is of byte[] type

db.Media.Add(model);
db.SaveChanges();

The final line, db.SaveChanges() will throw a DbEntityValidationException stating: Data must be a string or arraytype with max length '5000'.

When I step through the code, I find that my sample image (972x355, 71,6 kB) results in a byte[73571] value for model.Data. Is this too large for the db column? What can I do differently to allow the database to store this image?

I use similar code in a different project, which works just fine. The only difference there is that I insert the image through a stored procedure. The stored procedure doesn't do anything to the parameter, it just plain inserts it.

Upvotes: 0

Views: 2065

Answers (1)

Alexander Derck
Alexander Derck

Reputation: 14488

In your model for media you can add the typename Image if your column in database is an image, if you use varbinary(MAX) you can just use byte[] normally.

public partial class Media
{
   //[Column(TypeName = "image")]
   public byte[] Data {get; set;}
}

Also you can get the bytes much easier:

model.Data = File.ReadAllBytes(filename);

By the way if your Media model is used for other things than fetching the image, you should make a separate model for storing the image data and make a one-to-one relation to Media. That way you don't have to fetch the whole image everytime you need a Media model.

Upvotes: 2

Related Questions