我是Entity Framework Code的新手,我正在构建一个小应用程序来习惯它。当网站第一次运行时,我访问数据库中的现有目录值,并使用razor在下拉列表中显示。
public void GetCats()
{
using (context = new RecipeContext())
{
try
{
var query = (from r in context.Catalogues
select r).Distinct().ToList();
catalogues = query.Select(t => t.CatalogueName.ToString()).ToList();
catalogues.Sort();
}
catch (Exception exe)
{
labMessage = exe.Message;
}
}
}
现在,当我尝试将Catalog值添加到上下文时,我得到了上述错误。
public void AddCatalogue(string catalogueName)
{
using(context = new RecipeContext())
{
try
{
catalogueName = catalogueName.ToLower();
var catalogue = new RecipeCatalogue { CatalogueName = catalogueName };
if (context.Catalogues.Where(t => t.CatalogueName == catalogueName).Count() > 0)
{
labMessage = "The value already exists";
CatalogueNameAdded = false;
return;
}
context.Catalogues.Add(catalogue);
context.SaveChanges();
catalogueNameAdded = true;
labMessage = "a new catalogue record was added";
}
catch (Exception exe)
{
catalogueNameAdded = false;
labMessage = exe.Message;
}
}
}
但是这些值正被添加到数据库中,但仍然会得到上述异常。
建议也许是为什么我得到这个错误。这是我调用上述方法的Controller方法。
[HttpPost]
public JsonResult AddNewCatalogue(string catalogueName)
{
ViewModel model = new ViewModel();
model.AddCatalogue(catalogueName);
return Json(new { ViewModel = model });
}
答案 0 :(得分:6)
context
是模型中的字段吗?
我认为你不应该在using语句中分配一个字段。在使用上下文的闭合支架将被处理。如果您在其他地方访问该字段(无需重新分配),您将访问可能引发异常的已处置对象。
尝试更改此using (var context = new RecipeContext())
之类的使用状态。
(在上下文之前注意var
)并删除该字段。
答案 1 :(得分:3)
当退出执行查询的using
块时,您的上下文将被处理。这就是using
陈述的全部要点:
using(context = new RecipeContext()) {
// ...
}
// context has been disposed at this point
而不是using
语句,为您的班级提供一个字段来保存对它的引用。
private RecipeContext _context;
public void GetCats() {
_context = new RecipeContext();
// ...
}
public void AddCatalogue(string catalogueName) {
// Use _context here
}
请确保在某个时候致电_context.Dispose()
。此外,在使用它执行任何操作之前,最好在构造函数或仅调用一次的其他位置创建上下文。
答案 2 :(得分:0)
我的2美分:
以上答案是正确的!如果你正在使用像存储库这样的模式,我会把它作为一个单例实现!这样你的对象就不会被分离,你的上下文也不会被处理掉!