0

After an edit, this code generates a bitmap and writes it to a hdd file. How do I save this in my db?

//   first   save the edit data  
Actionresult Edit (Lot Lot)   
{    remove scaffold code for clarity
db.SaveChanges();
// create a new image to replace image currently in db.  
Bitmap mybmp = new Bitmap(400, 20);  
Graphics g = Graphics.FromImage(mybmp);  
g.DrawRectangle(Pens.Black, 0, 0, 400, 20);  
SolidBrush b = new SolidBrush(Color.OldLace);  
g.FillRectangle(b, 0, 0, 400, 20);  
// write a test file to confirm this is ok   ------it works  
mybmp.Save("C:\\temp\\lot1.bmp",System.Drawing.Imaging.ImageFormat.Gif);

//  add code here to save image to Lot table field TaskImage  here
db.SaveChanges();
}

My class:

public class Lot
{
public int LotID { get; set; }
public byte?[] TaskImage { get; set; }   
}
tereško
  • 58,060
  • 25
  • 98
  • 150
user2887440
  • 51
  • 1
  • 8

1 Answers1

0

From the EF perspective the model would look like this:

public class PhotoContext : DbContext
{
    DbSet<PhotoEntity> Photos { get; set; }
}

public class PhotoEntity
{
    public int Id { get; set; }

    public string Name { get; set; }

    [Column(TypeName = "image")]
    public byte[] Image { get; set; }
}

This will map the Image property that is a byte array to a column of image type in the database. To convert an image to/from the byte array you should be able to use something like this. If you set the Image property to a result of the conversion method and call .SaveChanges() it will save your image to the database. When you query the database the materialized entities will have the Image property set to data from the database and you will have to convert them back to get the image.

Pawel
  • 31,342
  • 4
  • 73
  • 104