我正在尝试保存Photo
具有byte[] File
字段的班级。尝试使用上下文保存它时会引发错误
你调用的对象是空的。
但是在调试时我可以看到它不为空。我可以看到该类的所有属性,包括字节数组中的值。
public class PhotoRepository
{
private static BlogContext _ctx;
public PhotoRepository()
{
_ctx = new BlogContext();
}
public static void Save(Photo p)
{
_ctx.Photos.Add(p);
_ctx.SaveChanges();
}
}
控制器
public class PhotoController : Controller
{
public ActionResult Index()
{
using (var ctx = new BlogContext())
{
return View(ctx.Photos.AsEnumerable());
}
}
public ActionResult Upload()
{
return View(new Photo());
}
[HttpPost]
public ActionResult Upload(PhotoViewModel model)
{
var photo = new Photo();//Mapper.Map<PhotoViewModel, Photo>(model);
if (ModelState.IsValid)
{
photo.AlternateText = model.AlternateText;
photo.Description = model.Description;
photo.File = MapStreamToFile(model.File);
photo.Name = model.Name;
PhotoRepository.Save(photo);
return RedirectToAction("Index");
}
return View(photo);
}
public byte[] MapStreamToFile(HttpPostedFileBase file)
{
using (var stream = file.InputStream)
{
var memoryStream = stream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
}
return memoryStream.ToArray();
}
}
}
照片
public class Photo
{
public int Id { get; set; }
public Byte[] File { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string AlternateText { get; set; }
}
照片视图模型
public class PhotoViewModel
{
public int Id { get; set; }
public HttpPostedFileBase File { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string AlternateText { get; set; }
}