在控制器中声明“DBContext”的全局变量然后将其用于所有数据库操作是否正确?
例子:
public class ProductController : Controller
{
private readonly DBContextEntities _db = new DBContextEntities();
public ActionResult Index()
{
var products = _db.Products.ToList();
return View(products);
}
public ActionResult Create()
{
_db.Products.AddObject(new Product{Name="x",Price="5.2"});
_db.SaveChanges();
return View(products);
}
}
请指教,