1

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.

4
  • 1
    You didn't explain what issue you are facing with this code. Commented Sep 12, 2018 at 13:04
  • 1
    I don't think this is the problem you are asking about, but why are you copying the document to a MemoryStream but not doing anything with the MemoryStream? Commented Sep 12, 2018 at 13:10
  • you copy data to memory stream and promptly dispose of it after. You need to clarify what it is you are trying to do. Commented Sep 12, 2018 at 13:11
  • What I am attempting to do is to load a file to store it on a database so it can be later downloaded to be viewed at a later stage. Commented Sep 17, 2018 at 19:43

1 Answer 1

1

First of all, you should not have the new entity that you want to create as a property inside of your view model. You should have those separated and only create the entity when you are actually creating it.

Then, in order to store the data from the uploaded file, you will have to store it inside of your entity. Right now, all you are doing is copying the data from the uploaded file into a memory stream. And then you discard the memory stream, so all the data is lost and never reaches the entity or the database (the database changes are also saved before you read the file).

Your code should look something like this:

if (ModelState.IsValid)
{
    var newRecordObj = new CWRecords
    {
        CWId = model.CWId,
        DateAdded = DateTime.Now,
    };

    using (var memoryStream = new MemoryStream())
    {
        await model.Document.CopyToAsync(memoryStream);
        newRecordObj.Document = memoryStream.ToArray();
    };

    _db.Add(newRecordObj);
    await _db.SaveChangesAsync();

    return RedirectToAction(nameof(Create), new { CWId = model.CWId });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.