3

Currently I am using the following code block to create DbSet dynamically and retrieve data from it -

Type entityType = Type.GetType("MyProject.Models."+ EntityName + ", SkyTracker");
DbSet mySet = Db.Set(entityType);

foreach (var entity in mySet)
{

}

I would like to use a Where clause here i.e. .Where(m=>m.Id==1) or something like that.

Is there any way to do it ?

s.k.paul
  • 7,099
  • 28
  • 93
  • 168

1 Answers1

1

You should use generics here to make it simpler.

public DbSet<T> GetDbSet<T>() where T: class
{
    DbContext db = new DbContext("");
    return db.Set<T>();
}

public List<T> GetFilteredData<T>(Expression<Func<T, bool>> criteria) where T : class 
{
    DbContext db = new DbContext("");
    return db.Set<T>().Where(criteria).ToList();
}

And you can call these methods as following.

Expression<Func<AudioClass, bool>> criteria = ac => ac.Name == "jazz";

var result = GetFilteredData(criteria);

Here AudioClass is just a sample class I created for example.

This should help you to implement the behavior you want to.

Muhammed Shevil KP
  • 1,404
  • 1
  • 16
  • 21
Chetan
  • 6,711
  • 3
  • 22
  • 32