我收到错误在使用mvc
中的代码优先方法时,基础提供程序在Open上失败了我的控制器代码是
public ActionResult Index()
{
SchoolDbContext schoolDbContext = new SchoolDbContext();
Student student = new Student() { Name = "New Student" };
schoolDbContext.Students.Add(student);
schoolDbContext.SaveChanges();
return View();
}
和web.config文件代码是
<add name="SchoolDbContext" connectionString="Data Source=.;User Id=sa;Password=*******;Initial Catalog=StudentDB;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
答案 0 :(得分:0)
当您使用代码优先方法时,您必须定义SchoolDbContext类并继承DBContext类。 像这样
public class SchoolDbContext : DBContext
{
public DBSet<Student> Students {get; set;}
}
public ActionResult Index()
{
SchoolDbContext schoolDbContext = new SchoolDbContext();
Student student = new Student() { Name = "New Student" };
student.name = "";// set the property here
student.age =""; // set the property here
schoolDbContext.Students.Add(student);
schoolDbContext.SaveChanges();
return View();
}