i am struggling to load a file into a database with ASP.NET Core. What could i be doing wrong.
This is what i have in my Model
namespace BeeshoekCWPortal.Models
{
public class CWRecords
{
public int Id { get; set; }
public string RecordName { get; set; }
public byte[] Document { get; set; }
[DisplayFormat(DataFormatString ="{0:d}")]
public DateTime DateAdded { get; set; }
public int CWId { get; set; }
[ForeignKey("CWId")]
public virtual ContingentWorker CW { get; set; }
}
}
This is what I have in My ViewModel
namespace BeeshoekCWPortal.ViewModel
{
public class CWandRecordsViewModel
{
public int CWId { get; set; }
public string Title { get; set; }
public string FullNames { get; set; }
public string Surname { get; set; }
public string DateofBirth { get; set; }
public string IdPassportNumber { get; set; }
public string Gender { get; set; }
public string Race { get; set; }
public string Nationality { get; set; }
public IFormFile Document { get; set; }
public CWRecords NewRecordObj { get; set; }
public IEnumerable<CWRecords> PastRecordObj { get; set; }
}
}
I have a strong believe that I am doing something wrong in the Controller.
//POST : Services/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CWandRecordsViewModel model)
{
if (ModelState.IsValid)
{
{
model.NewRecordObj.CWId = model.CWId;
model.NewRecordObj.DateAdded = DateTime.Now;
_db.Add(model.NewRecordObj);
await _db.SaveChangesAsync();
};
using (var memoryStream = new MemoryStream())
{
await model.Document.CopyToAsync(memoryStream);
};
return RedirectToAction(nameof(Create), new { CWId = model.CWId });
}
var CW = _db.ContingentWorkers.FirstOrDefault(c => c.Id == model.CWId);
var newModel = new CWandRecordsViewModel
{
CWId = CW.Id,
Title = CW.Title,
FullNames = CW.FullNames,
Surname = CW.Surname,
DateofBirth = CW.DateofBirth,
IdPassportNumber = CW.IdPassportNumber,
Gender = CW.Gender,
Race = CW.Race,
Nationality = CW.Nationality,
PastRecordObj = _db.CWRecords.Where(r => r.CWId == model.CWId).OrderByDescending(r => r.DateAdded).Take(5)
};
return View(newModel);
}
How can i fix the controller so that i can upload the file onto the database.
MemoryStreambut not doing anything with theMemoryStream?