How do I dynamically load into an EF7 DbContext
a X number of classes without explicitly writing them in a DbContext
class ?
For example, I tried to avoid it like this:
public class MyDbContextClass : DbContext
{
public DbSet<Category> categories {get;set;}
public DbSet<Product> products {get;set;}
...
}
So it could be great to load Category and Product dynamically (without knowing if I have 2 or 20 classes).
Is it possible?
You should use this method:
All entities must inherit from BaseType...
public static void RegisterAllEntities<BaseType>(this ModelBuilder modelBuilder, params Assembly[] assemblies)
{
var types = assemblies.SelectMany(a => a.GetExportedTypes())
.Where(c => c.IsClass && !c.IsAbstract && c.IsPublic && typeof(BaseType).IsAssignableFrom(c));
foreach (var type in types)
modelBuilder.Entity(type);
}
dbContext.Set<T>()
creates an instance of DbSet<T>
as long as T
is a type in your model (i.e. you have to add the entity type in OnModelCreating
).
See the source code for .Set<T>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With