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