I'm trying to save my Photo class that has a byte[] File field. When trying to save it using context is throws the error
Object reference not set to an instance of an object.
But when debugging I can see that it is not null. I can see all of the properties of the the class including the values in the byte array.
public class PhotoRepository
{
private static BlogContext _ctx;
public PhotoRepository()
{
_ctx = new BlogContext();
}
public static void Save(Photo p)
{
_ctx.Photos.Add(p);
_ctx.SaveChanges();
}
}
controller
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();
}
}
}
Photo
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; }
}
PhotoViewModel
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; }
}

nullor raises a NullReferenceException? Less code and more stack, please.PhotoRepositoryyou will re-initialize that static field, right? That seems like and error prone and confusing design to me_ctxwill not be set before an instance is created._ctxisnullbecause you never create an instance ofPhotoRepository,_ctx.Photosisnull, or you are getting the exception in_ctx.SaveChanges();. Initialize that static member statically (i.e., when you declare it). You are going to run into weird problems relying on a constructor to initialize static data.