我一直在尝试使用实体框架的代码优先。我写了下面的代码行代码优先使用DbContext
DbContext _context = new DbContext(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
但是在执行过程中,连接保持关闭。这段代码有什么问题?
我创建使用的DbContext下面
public class GenericRepository<T> where T:class
{
public DbContext _context = new DbContext(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
private DbSet<T> _dbset;
public DbSet<T> Dbset
{
set { _dbset = _context.Set<T>(); }
get { return _dbset; }
}
public IQueryable<T> GetAll()
{
return Dbset;
}
}
所示的通用库类,然后我呼吁网页加载事件,其中教师是映射到数据库中的表
一个实体类该类protected void Page_Load(object sender, EventArgs e)
{
GenericRepository<Teacher> studentrepository = new GenericRepository<Teacher>();
rptSchoolData.DataSource = studentrepository.GetAll().ToList();
rptSchoolData.DataBind();
}
但连接保持关闭状态,并且上下文对象的ServerVersion中还有一个InvalidOperation异常。
我错过了什么?
您需要创建自己的上下文类,它从DbContext继承并定义实体集合。 – tvanfosson
我的数据库已经存在与表。这是我在我已经传入DbContext对象的连接字符串中指定的内容。我仍然需要一个继承它的类吗? – RAHUL
@RAHUL:是的,你需要。 – Slauma