Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically loading DbSet to DbContext

Tags:

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?

like image 982
fuegonju Avatar asked Aug 09 '16 15:08

fuegonju


2 Answers

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);
    }
    
like image 104
Mehran Norouzi Avatar answered Sep 24 '22 16:09

Mehran Norouzi


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>.

like image 21
natemcmaster Avatar answered Sep 22 '22 16:09

natemcmaster