How to select table dynamically from Entity Framework?

I have this function in c#:

using (SKContext db = new SKContext())
{
    dynamic dynamic = new ExpandoObject();

    if (category == "Categories")
    {
        dynamic = db.Categories
                    .Where(X => X.Active == true)
                    .Select(f => f.Name).ToList();
    }
    else if (category == "Brands")
    {
        dynamic = db.Brands
                    .Where(X => X.Active == true)
                    .Select(f => f.Name).ToList();
    }
    else if (category == "Characters")
    {
        dynamic = db.Characters
                    .Where(X => X.Active == true)
                    .Select(f => f.Name).ToList();
    }

    return dynamic;
}

I would like to dynamically choose a table by string kind of like this:

var tableName = "Brands";
return db.[tableName].Where(X => X.Active == true).Select(f => f.Name).ToList();

Can anyone help?

Upvotes: 2

Views: 312

Answers (1)

Guru Stron
Guru Stron

Reputation: 141845

Instead of going dynamic I would recommend to introduce some discriminator type/interface and declare common properties/functionality there:

public interface ISomeInterface
{
    bool Active { get; set; }
    string Name { get; set; }
}

public class Category : ISomeInterface {...} // and others

And use this interface to build query:

IQueryable<ISomeInterface> query = category switch
    {
        "Categories" => db.Categories,
         // ...
        _ => throw new ArgumentOutOfRangeException()
    };
 return query.Where(X => X.Active == true).Select(f => f.Name).ToList();

Upvotes: 1

Related Questions