About DbSet and DbContext

c# entity-framework


I saw a piece of code that mixes DbSet and DbContext together. I am not strong on Entity Framework. I thought that they are different things.

Can somebody give me a little explanation?

public class testContext : DbContext
    public testContext();

    public string IPAddress { get; set; }
    public DbSet<WSettings> Settings { get; set; }
    public string UserName { get; set; }

    public override int SaveChanges();
9/20/2016 4:59:39 PM

Accepted Answer

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;}

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

11/29/2012 2:51:00 PM

Popular Answer

DbContext generally represents a database connection and a set of tables. DbSet is used to represent a table.

Your code sample doesn't fit the expected pattern. First, it is incomplete. Also, there are properties that really don't belong.

This pattern is more typical:

class User
   public string IPAddress { get; set; }
   public ICollection<Settings> Settings { get; set; }
   public string UserName { get; set; }

class MyContext : DbContext
   public DbSet<User> Users { get; set; }
   public DbSet<Settings> Settings { get; set; }

Related Questions


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