I have been trying to work with Entity Framework’s Code First. I wrote the below line of code
DbContext _context = new DbContext(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
However on execution, the connection remains closed. Is there something wrong with this code??
I have created a generic repository class using the DBContext shown below
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;
}
}
and I then call this class on the page load event, where Teacher is an entity class which maps to a table in the database
protected void Page_Load(object sender, EventArgs e)
{
GenericRepository<Teacher> studentrepository = new GenericRepository<Teacher>();
rptSchoolData.DataSource = studentrepository.GetAll().ToList();
rptSchoolData.DataBind();
}
but the connection remains closed and there is also an InvalidOperation Exception in the ServerVersion of the context object.
Am I missing something??
This property
has a heavy smell to it. A setter that does nothing with
valueis an anti pattern big time. Do you expect to set theDbSetafter creating aGenericRepository?I don’t understand that your code even works because you never initialize
_dbset, it should throw a null object reference exception.The
_dbsetandDbSetshouldn’t be there in the first place.GetAllshould return_context.Set<T>(). EF should open and close the connection all by itself. Maybe the fact that you don’t initialize the DbSet causes a connection never to open, causing problems in other pieces of code not revealed here.