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 ?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.