Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbContext has been disposed, does not make any sense

I am creating an C# Web application, where I would be able to add companies and the places the company has its branches. A company could have several location branches. And for one location there could be several companies. So the relationship between Companies and Territory is Many-Many.

This is my current model for Company,

public class CompanyModel
{

    [HiddenInput(DisplayValue = false)]
    public long CompanyId { get; set; }

    [Display(Name = "Company Name")]
    [Required(ErrorMessage = "* required")]
    public string CompanyName { get; set; }

    [Display(Name = "Phone Number")]
    [Required(ErrorMessage = "* required")]
    [RegularExpression(@"\d*", ErrorMessage = "Not a valid phone number")]
    public string PhoneNo { get; set; }


    [Display(Name = "Post Code List", Prompt = "eg. BA5, BS16")]
    public string PostCodeList { get; set; }
}

It has the text box which will take in a comma separated string. So I iterate it using foreach to add it to the table,

            foreach (var s in company.PostCodeList.Split(','))
            {
                AddPostCode(s, company.CompanyId);
            }

Where AddPostcode is,

    public void AddPostCode(string postCode, long companyId)
    {
        using (var db = new BoilerServicingDbContext())
        {
            //Does post code exist
            var p = db.Territories.FirstOrDefault(x => x.PostCodePrefix == postCode);

            //if not create
            if (p == null)
            {
                p = new Territory
                {
                    PostCodePrefix = postCode
                };
                db.Territories.Add(p);
            }
            //get the company
            var c = db.Companies.First(x => x.Id == companyId);

            //add post code
            c.Territories.Add(p);

            //save
            db.SaveChanges();
        }
    }

Now I get the following error,

The operation cannot be completed because the DbContext has been disposed.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.

Exception Details: System.InvalidOperationException: Sequence contains no elements

Source Error:

Line 16:         </thead>
Line 17:         <tbody>
Line 18:         @foreach (var a in Model)
Line 19:             {
Line 20:                 <tr>

Source File: c:\Source\LSP.HEA.BoilerServicing\Main\LSP.HEA.BoilerServicing.Web\Views\Companies\Index.cshtml
Line: 18 
like image 997
PaulFrancis Avatar asked Feb 10 '23 22:02

PaulFrancis


1 Answers

This happens because you're waiting until the view is rendered to iterate the collection generated by an EF query, and the context has already been disposed at this point.

EF doesn't actually run the SQL query until the collection is accessed, so you need to force it to pull the data and populate the collection while the DbContext is still alive.

A simple solution to this is to use ToList(), which causes EF to immediately retrieve the data.

For example, instead of:

return View(mycollection);

Try:

return View(mycollection.ToList());
like image 151
Alan Avatar answered Feb 13 '23 20:02

Alan