DbContext 已被处置,没有任何意义

DbContext has been disposed, does not make any sense

我正在创建一个 C# Web 应用程序,我可以在其中添加公司以及公司设有分支机构的地点。一家公司可以有多个地点分支机构。一个地点可能有几家公司。所以CompaniesTerritory之间的关系是Many-Many

这是我公司目前的模型,

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; }
}

它有一个文本框,可以输入逗号分隔的字符串。所以我使用 foreach 对其进行迭代,将其添加到 table、

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

AddPostcode 在哪里,

    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();
        }
    }

现在我得到以下错误,

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 

发生这种情况是因为您正在等待呈现视图以迭代由 EF 查询生成的集合,此时上下文已被释放。

EF 在访问集合之前实际上并不 运行 SQL 查询,因此您需要强制它在 DbContext 仍然存在时提取数据并填充集合。

一个简单的解决方案是使用 ToList(),这会导致 EF 立即检索数据。

例如,而不是:

return View(mycollection);

尝试:

return View(mycollection.ToList());