该名称在当前上下文中不存在

时间:2014-10-09 12:53:45

标签: asp.net-mvc-4 razor sql-server-2012

if (ModelState.IsValid)
 {
 using (mydataEntities1 db = new mydataEntities1()) 
 db.Contactmodels.Add(model);
 db.SaveChanges();


 ModelState.Clear();
 model = null;
 ViewBag.Message = "Thanks for contacting us";

错误是当前上下文中不存在名称db。 请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

您忘记了using区块的大括号。当前代码的结构如下:

using (mydataEntities1 db = new mydataEntities1()) 
    db.Contactmodels.Add(model); // inside the block, "db" exists
db.SaveChanges(); //  outside the block, "db" is no longer in scope

像其他任何代码块一样包装整个using块:

using (mydataEntities1 db = new mydataEntities1())
{
    db.Contactmodels.Add(model);
    db.SaveChanges();
}