MVC EF将位图插入表中



编辑后,此代码生成一个位图并将其写入hdd文件。如何将其保存在数据库中?

//   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();
}

我的班级:

public class Lot
{
public int LotID { get; set; }
public byte?[] TaskImage { get; set; }   
}

从EF的角度来看,模型如下所示:

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; }
}

这将把作为字节数组的Image属性映射到数据库中image类型的列。要将图像转换为字节数组/从字节数组转换图像,您应该能够使用类似的方法。如果将Image属性设置为转换方法的结果并调用.SaveChanges(),则会将图像保存到数据库中。当您查询数据库时,物化实体将Image属性设置为数据库中的数据,您必须将它们转换回以获取图像。

最新更新