Christian Haaland
Christian Haaland

Reputation: 151

Getting DbSet<MyTable> from a string

ADO.NET user trying EF for the first time. I'm trying to get a table from a string of the table name.. Harder than I presumed. Basiclly I'm here:

var tableName = "Name.Entities.Measure" + measureType;
var table = Activator.CreateInstance("Name.Entities", tableName);
var unwrapped = table.Unwrap();
var type = unwrapped.GetType();
var dbset = context.Set<type>();

OR

switch (tableString)
{
    case "table1":
    return GetDataFromTable1();
    case "table2":
    return GetDataFromTable2();
}

Less code would be nice ;)

Thinking of making an extension method with a searchable collection of all the entities. Better solution anyone?

Upvotes: 2

Views: 6656

Answers (1)

Ackroydd
Ackroydd

Reputation: 1610

I was looking for the same thing. Try the non-generic version of Set():

var tableName = "Name.Entities.Measure" + measureType;
var type = Type.GetType(tableName);
var dbset = Context.Set(type);

Upvotes: 3

Related Questions