I'm new to MVC and have done some tutorials to get the hang of it, but in some of these tutorials I have come across an example with a DbContext class asp.net mvc5 with EF6 tutorial
I have tried researching information on DbContext Class but was unable to get any information that made me any the wiser! all I could find are more of the same tutorials with little information I also looked up the class on msdn DbContext Class.
I have done previous tutorials without a db context class and it works fine and my question is do I need to use a context class, and what are the advantages of using a DbContext Class?
Any help would be appreciated thanks.
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
.