Drew Noakes
Drew Noakes

Reputation: 311305

When to add a DbSet to the DbContext

When should you add a DbSet for a table to the DbContext? If an entity type does not have a DbSet but is referenced from another entity type that does have a DbSet, then both tables are created and things work as you'd expect.

Is there any overhead associated with having DbSet properties on your DbContext that you don't use? Should it be avoided? Are there cases where you cannot track entity changes reliably without a DbSet?

One potential minor issue I've found when using a code-first model is that if you don't add a DbSet for a referenced entity type, the table name is generated with a singular name. However if you later add a DbSet with a plural name (seems to be the convention), you'll generate a migration for a table rename.

I couldn't find any guidance on this in the documentation.

Upvotes: 3

Views: 937

Answers (1)

bricelam
bricelam

Reputation: 30425

Adding a DbSet property to your DbContext does two things:

  1. Lets you query the table using db.Customers (duh) instead of db.Set<Customer>(). The properties are initialized by EF.
  2. Configures the table name. It's shorthand for modelBuilder.Entity<Customer>().ToTable("Customers") (as you found) Note, EF isn't pluralizing the name; you are. ;)

It won't otherwise affect Entity Framework.

Upvotes: 3

Related Questions