MVC EF将位图插入表中

时间:2013-12-04 23:04:50

标签: asp.net-mvc entity-framework graphics bitmap

编辑后,此代码生成位图并将其写入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; }   
}

1 个答案:

答案 0 :(得分:0)

从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类型的列。要将图像转换为字节数组,应该能够使用this之类的内容。如果将Image属性设置为转换方法的结果并调用.SaveChanges(),则会将图像保存到数据库中。查询数据库时,实体化实体将Image属性设置为数据库中的数据,您必须将它们转换回来获取图像。