About DbSet and DbContext

Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database. So it makes perfect sense that you will get a combination of both!

You will be using a DbContext object to get access to your tables and views (which will be represented by DbSet’s) and you will be using your DbSet’s to get access, create, update, delete and modify your table data.

If you have 10 tables in your database and your application works with 5 of them (let us call them Table1 – Table 5) it would make sense to access it using a MyAppContext object where the MyAppContext class is defined thus:

public class MyAppContext : DbContext
{
    public MyAppContext () : ;

    public DbSet<Table1> Table1 { get; set; }
    public DbSet<Table2> Table2 { get; set; }
    public DbSet<Table3> Table3 { get; set; }
    public DbSet<Table4> Table4 { get; set; }
    public DbSet<Table5> Table5 { get; set; }
}

Note that, for instance, the identifier Table1 is used both as the name of a type and as a name of a property in the defined context type. What you see above is quite typical. An example of a class that corresponds to a table schema is given below:

public class Table1 
{
   public int Id {get; set;}
   public string AStringField {get; set;}
   //etc.
}

Have a look here for more information: http://entityframeworktutorial.net/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)