With LINQ-to-SQL, there are specific ways of doing this from the data-context; basically, db.GetTable
. This returns an ITable
, but it is a little tricky to work with an untyped ITable
. You can enumerate it, at least...
To get the ITable
, you normally need the Type
, which you can get with (for example) Assembly.GetType
:
using (var ctx = new MyDataContext()) {
string name = "Customer"; // type name
Type ctxType = ctx.GetType();
Type type = ctxType.Assembly.GetType(
ctxType.Namespace + "." + name);
ITable table = ctx.GetTable(type);
foreach(var row in table) {
Console.WriteLine(row); // works best if ToString overridden...
}
}
Of course, once you have the Type
, you use use Activator
to create new entity instances:
object newObj = Activator.CreateInstance(type);
// TODO: set properties (with reflection?)
table.InsertOnSubmit(newObj);
but if you want to use the property-name, that can work too:
using (var ctx = new MyDataContext()) {
string name = "Customers"; // property name
ITable table = (ITable) ctx.GetType()
.GetProperty(name).GetValue(ctx, null);
foreach (var row in table) {
Console.WriteLine(row); // works best if ToString overridden...
}
}
Running filters (Where
) etc is tricky with untyped data, as building the Expression
would be tortuous. I'd probably start switching to a typed model at that point...