Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DbSet from entity name in EF Core / .NET Core 2.0 [duplicate]

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.

like image 727
lenniep Avatar asked Dec 20 '17 16:12

lenniep


People also ask

How do I check my entity state EF core?

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.

What is DbSet in Entity Framework Core?

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.

What is the difference between DbContext and DbSet?

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!

What is ModelBuilder in Entity Framework?

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.


1 Answers

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));
    }
like image 108
Esteban Kito Avatar answered Sep 21 '22 03:09

Esteban Kito