Ari*_*ule 3 c# asp.net-mvc entity-framework dbcontext
我是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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试将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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这些值正被添加到数据库中,但仍然会得到上述异常.
建议也许是为什么我得到这个错误.这是我调用上述方法的Controller方法.
[HttpPost]
public JsonResult AddNewCatalogue(string catalogueName)
{
ViewModel model = new ViewModel();
model.AddCatalogue(catalogueName);
return Json(new { ViewModel = model });
}
Run Code Online (Sandbox Code Playgroud)
是context模型中的场?我认为你不应该在using语句中分配一个字段.在使用上下文的闭合支架将被处理.如果您在另一个地方访问该字段(无需重新分配),您将访问可能引发您获得的异常的已处置对象.
尝试更改这样的使用状态using (var context = new RecipeContext()).(var在上下文之前注意)并删除该字段.