Dynamic table name in linq

c# entity-framework linq reflection

Accepted Answer

Add a method named Set, for example, to your DbContext class. It should return:

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 ask about by doing 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
}

Zzz-17-Zzz has more information about System.Linq.Dynamic.

5
1/23/2015 8:13:34 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow