I have a DbContext
with several DbSet<T>
properties:
public virtual DbSet<A> A { get; set; }
public virtual DbSet<B> B { get; set; }
public virtual DbSet<C> C { get; set; }
...
In certain scenarios I must now be able to retrieve a specific DbSet with the entity name as string (e.g. when the user enters "A", I need to get the Dbset<A>
).
In previous EF versions, the following was possible:
var dbset = Context.Set(Type.GetType(A));
Is there a similar way to do so with the current versions of EF core? I've tried several ways to achieve that, but the only way I have it working at the moment is using a rather ugly switch/case and I would like to get rid of that.
I've found several posts with similar issues around here, but all of them relate to early .NET Core versions or EF5 / EF6.
Find, DbContext. FindAsync, DbSet<TEntity>. Find, and DbSet<TEntity>. FindAsync find a single entity by primary key, first looking in tracked entities, and then querying the database if needed.
In Entity Framework Core, the DbSet represents the set of entities. In a database, a group of similar entities is called an Entity Set. The DbSet enables the user to perform various operations like add, remove, update, etc. on the entity set.
Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database. So it makes perfect sense that you will get a combination of both!
The ModelBuilder is the class which is responsible for building the Model. The ModelBuilder builds the initial model from the entity classes that have DbSet Property in the context class, that we derive from the DbContext class. It then uses the conventions to create primary keys, Foreign keys, relationships etc.
Do this to add de extension Set(Type t) method to de dbcontext class.
using Microsoft.EntityFrameworkCore;
namespace ApiWebApplication.Utils
{
public static class MyExtensions
{
public static IQueryable<object> Set (this DbContext _context, Type t)
{
return (IQueryable<object>)_context.GetType().GetMethod("Set").MakeGenericMethod(t).Invoke(_context, null);
}
}
}
Example:
// GET: api/Employees
[HttpGet]
public IEnumerable<object> GetEmployees()
{
return _context.Set(typeof(Employee));
}
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