The field already has a default value:
null
.
You're getting a
NullReferenceException
because you are trying to call a method on a reference which is
null
. You simply need to test for
null
before trying to call methods on the instance.
public async Task<IActionResult> Create(IFormFile Data, IFormFile Img, UploadDocument tbl)
{
if (!ModelState.IsValid)
{
return View();
}
var document = new UploadDocument
{
Content = tbl.Content,
Title = tbl.Title,
DateOfTraining = tbl.DateOfTraining,
CreatedOn = DateTime.UtcNow
};
if (Data != null)
{
document.Name = Path.GetFileName(Data.FileName);
document.ContentType = Data.ContentType;
using var ms = new MemoryStream();
Data.CopyTo(ms);
document.Data = ms.ToArray();
}
if (Img != null)
{
document.imgName = Path.GetFileName(Img.FileName);
document.imgContentType = Img.ContentType;
using var ms = new MemoryStream();
Img.CopyTo(ms);
document.Img = ms.ToArray();
}
_context.Add(document);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}