gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:31:15 25 4
gpt4 key购买 nike

我正在创建一个 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 对其进行迭代以将其添加到表中,

            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

最佳答案

发生这种情况是因为您一直在等待 View 呈现以迭代由 EF 查询生成的集合,并且此时已经释放了上下文。

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

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

例如,代替:

return View(mycollection);

尝试:

return View(mycollection.ToList());

关于c# - DbContext 已被处置,没有任何意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28484504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com