Dynamic table name in linq [duplicate]

In your DbContext class, add a method say called Set that returns:

public DbSet Set(string name)
{
  // you may need to fill in the namespace of your context
  return base.Set(Type.GetType(name));
}

Which you can query like this:

using (var db = new YourDataContext())
{
  // Since your DbSet isn't generic, you can can't use this:
  // db.Set("Namespace.EntityName").AsQueryable().Where(a=> a.HasSomeValue...
  // Your queries should also be string based.
  // Use the System.Linq.Dynamic nuget package/namespace
  var results = db.Set("Namespace.EntityName")
    .AsQueryable()
    .Where("SomeProperty > @1 and SomeThing < @2", aValue, anotherValue);
  // you can now iterate over the results collection of objects
}

More information on System.Linq.Dynamic can be found here

Leave a Comment