Kasun Koswattha
Kasun Koswattha

Reputation: 2471

Is there a way to load a dbset dynamically in EF core?

I wanted to make a generic method that will dynamically load the dbset and does something.

For example something like this (imaginary method):

 public IList<TEntity> GetData<TEntity>(DbSet<TEntity> entity) where TEntity : class
 {
   return DbContext<entity>.Load().Where(*Some Logic*).ToList();
 }

I figured if I execute raw sql query, I can fulfill the requirement. But I want to do it without direct queries.

Is there any way I can do this?

Upvotes: 1

Views: 707

Answers (1)

Backs
Backs

Reputation: 24913

public IList<TEntity> GetData<TEntity>(Expression<Func<TEntity, bool>> expression) where TEntity : class
{
    return _context.Set<TEntity>().Where(expression).ToList();
}

And use:

GetData<Contest>(t => t.IsOpened == true);

Upvotes: 1

Related Questions