What is the purpose of a db context class in asp.net mvc

asp.net-mvc c# entity-framework

Question

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.

1
23
8/2/2019 2:54:27 PM

Accepted Answer

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.

22
8/11/2015 11:18:02 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow