maztt
maztt

Reputation: 12294

LINQ-to-SQL using tables dynamically by name

Is this possible ? or any workaround is possible

string table="language";
var a=_db.table.FirstOrDefault();

Upvotes: 2

Views: 149

Answers (2)

Dennis Traub
Dennis Traub

Reputation: 51634

First find the Type being represented by the name, then call _db.GetTable<T>() like this:

string entityName = "language";

var entityType = FindType(entityName);

var result = _db.GetTable<entityType>().FirstOrDefault;

The helper method FindType() gets the Type through Reflection:

public Type FindType(string typeName) {
    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) {
        var result = assembly.GetType(typeName, false, true);
        if (result != null) { return result; }
    }
    throw new Exception("Selected type can't be found in loaded assemblies");
}

Upvotes: 2

Mark Sowul
Mark Sowul

Reputation: 10600

If you have the entity type (rather than just a string) you can use _db.GetTable()

Upvotes: 1

Related Questions