Creating generic DbSets based on entity types

208 views Asked by At

In EF code first using following peace of code, I could create non-generic DbSets based on each entity type:

foreach (var entry in _dbContext.ChangeTracker.Entries<BaseEntity>())
{
    BaseEntity entity = entry.Entity;
    Type type = entity.GetType();
    var set = _dbContext.Set(type);
} 

Is there any way to create them as Generic DbSets?

1

There are 1 answers

0
Michael Edenfield On

Not easily. You could call the correct generic overload of Set<> using reflection, if you really needed to get the generic DbSet. Beyond that, in order to call the generic methods you need to know the correct generic type parameters at compile time. Reflection aside, any time you end up using Type objects at runtime you lose the ability to use generic types.