Matt Knowles
Matt Knowles

Reputation: 397

Must I create explicit DbSet properties on my DbContext?

I'm using Entity Framework 6 Code First with an Empty Database. I've created a fairly large number of POCO classes with a reasonably complex class hierarchy (a fair number of abstract classes and quite a few concrete classes). I'd like to be able to decorate my classes in some way so that they're automatically added to the DbContext without having to explicitly create a DbSet property for each, but I worry that this will cause problems when I try to update-database. I've seen a couple of threads here where someone seemed to be asking a similar question, but the response seemed more geared to using DbContext.Set() to get a reference to an existing set.

Upvotes: 4

Views: 1915

Answers (2)

Matt Knowles
Matt Knowles

Reputation: 397

I discovered that I don't need to add explicit DbSet properties to the DbContext for every class because EF automatically adds all related classes to the model.

I'm able to be lazy and only add explicit properties for some classes, and then reference any other classes using the DbContext.Set<>() method:

var q = from x in myContext.Set<myClass>() select x;

Upvotes: 1

Peter Lillevold
Peter Lillevold

Reputation: 33940

If you're relying on code-first migrations, then yes, EF uses reflection on your DbContext in order to discover what tables to create. Each DbSet property maps to a table in your database.

Upvotes: 2

Related Questions