Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 485
Drew Noakes Avatar asked Feb 01 '26 14:02

Drew Noakes


1 Answers

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.

like image 102
bricelam Avatar answered Feb 03 '26 09:02

bricelam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!