基础提供程序在打开数据库时失败

时间:2015-02-05 04:25:40

标签: asp.net-mvc

我收到错误在使用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" />

1 个答案:

答案 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();
    }
相关问题