What is the purpose of a db context class in asp.net mvc
I would first say that the DbContext
class relates to Entity Framework (EF), but then the question tags would suggest you figured that much out yourself. In typical usage, deriving from the DbContext
class is simply the way to incorporate EF-based data access into your application. The class that derives from DbContext
is, in essence, the data access layer of your application.
So to put it the other way around, if you want to do data access with Entity Framework, DbContext
is what you want.
You can think of DbContext
as the database connection and a set of tables, and DbSet
as a representation of the tables themselves. The DbContext
allows you to link your model properties (presumably using the Entity Framework) to your database with a connection string.
Later, when you wish to refer to a database in your controller to handle data, you reference the DbContext
. For Example,
public class UserSitesContext : DbContext
{
public UserSitesContext()
:base("name=UserSitesContext")
{
}
public virtual DbSet<Site> Sites { get; set; }
}
is referenced later in the controller like
private UserSitesContext dbUser = new UserSitesContext();
var queryExample = from u in dbUser.Sites select u;
:base("connection")
refers to your connection string found in Web.config
.