Get and use DbSet by type set at runtime in EntityFramework Core

52 views Asked by At

I want to get a DbSet based on a type set at runtime so I can then use it to add, remove or update entities in the DbContext.

As I understand it, the way to do that in EF 6 would be, for example :

context.Set(entity.GetType()).Add(entity);

However, EF Core does not have access to the non-generic method Set (Type entityType) but only to the generic methods Set<TEntity>([NotNullAttribute] string name) where TEntity : class and Set<TEntity>() where TEntity : class; it also does not have access to the non-generic class DbSet but only to the generic version DbSet<TEntity>, all of which makes coding an EF Core equivalent to the code above very difficult. Still, as it would be very convenient for me, I'd like to know if there exists an alternative.

Edit : Well, this is embarrassing. So apparently I am an idiot and did not realize that the class DbContext already had its own methods Add, Update and Remove. Thanks to the people who still took the time to answer me anyway.

0

There are 0 answers