Aboriginal
Aboriginal

Reputation: 394

Cannot access a disposed object while using different contexts

I am trapped with definitions of Entity framework and using objects.
I am trying to save an uploaded file once I am saving the details related to that file in my database.

public async Task<IActionResult> Edit(string List<IFormFile> files, [Bind("param")] Entity entity)
    {
        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(entity);
                await _context.SaveChangesAsync();   

                //update Attachments
                if (files.Count > 0)
                {
                    attachment.UploadFiles(files);
                }
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EntityExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Index");
        }
        return View(entity);
    }


When I run the application and want to submit the form I receive below error:
Cannot access a disposed object. Object name: 'FileBufferingReadStream'.

  [HttpPost]
    public async void UploadFiles(List<IFormFile> files)
    {
        if (files == null || files.Count == 0)
        {
            log.error("files not selected");
        }
        try
        {
            List<string> filenames = new List<string>();
            string directory = Directory.GetCurrentDirectory() + "\\wwwroot";

            createDir(directory);

            foreach (var file in files)
            {
                string filename = file.GetFilename();
                filenames.Add(filename);
            }
            if (filenames.Count > 0)
                foreach (var filename in filenames)
                {
                   AttachmentQ(filename, directory, createdBy);
                }
            foreach (var file in files)
            {
                string filename = file.GetFilename();
                var path = Path.Combine(directory, filename);
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                filenames.Add(filename);
            }
        }
        catch (Exception e)
        {
            log.error(e.Message);

        }
    }

    [ValidateAntiForgeryToken]
    public async void AttachmentQ(string filename, string path, string createdBy)
    {
        try
        {
            Attachment attachment = new Attachment
            {
                Name = filename,
                Path = path,
                CreatedBy = createdBy,
                CreatedDate = DateTime.Now
            };

                _context.Add(attachment);
                await _context.SaveChangesAsync();
        }
        catch (Exception e)
        {
            log.error(e.Message);
        }
    }

Surprisingly I don't get error in debug mode. But when I run the app I get This page isn’t working error.
I also noticed I need to return a value when I use async but I don't have any return vale in UploadFiles() and AttachmentQ() methods.
Could you please help me how to handle objects when using different contexts.
Thanks

Upvotes: 1

Views: 1477

Answers (1)

Wahid Bitar
Wahid Bitar

Reputation: 14104

Do NOT use async void at all.

if you want to use async/await pattern then let your methods returns Task

public async Task UploadFiles(List<IFormFile> files)

Upvotes: 1

Related Questions