You have to register entities in a DbContext. It can infer relations and discover other entities by itself, but it's better to be explicit about it.
You have two options:
1. Adding DbSet<T> properties to DbContext
One way to do this is to add DbSet<TEntity> properties in DbContext class:
class AppDbContext: DbContext {
public DbSet<Product> Products { get; set; }
// ...
}
This is easy, but requires modifying DbContext for every new entity.
2. Implementing IEntityTypeConfiguration<T>
Another way is to implement IEntityTypeConfiguration<TEntity> for all entities, and let DbContext discover configurations using modelBuilder.ApplyConfigurationsFromAssembly method.
Note that there are no DbSet<TEntity> properties in the DbContext class!
class AppDbContext: DbContext
{
// no DbSet properties 🎉
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
}
}
class Product
{
public int Id { get; set; }
public string Title { get; set; }
}
class ProductEntityConfiguration: IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.HasIndex(e => e.Title).IsUnique();
}
}
Now you can access a DbSet for an entity using:
var productSet = dbContext.Set<Product>();
References