hub
hub

Reputation: 164

Entity Framework Select table using a string

Is it possible to select table with a string when using Entity Framwork generated code?

Example:

using (var db = new Model1())
{
    db.Database.Connection.ConnectionString = CreateConnectionString();
    var res = from a in db.R1
              select a;
    foreach (var item in res)
    {...}
}

But what I want is like

using (var db = new Model1())
{
    String tablename = "R1";
    db.Database.Connection.ConnectionString = CreateConnectionString();
    var res = from a in db.tablename
              select a;
    foreach (var item in res)
    {...}
}

I need to do a select on a number of tables named R1 to R12, they look almost the same.

I can solve it with a direct SQL query but I want to use Entity Framework as much as possible.

The post in Entity Framework inline SQL dynamically select table name is almost right, but I want to select all columns and preferbly get right type back.

Or am I going aboutit the wrong way? Should I use something else than EF?

Any help would be preciated!

Upvotes: 2

Views: 3379

Answers (1)

Mark Shevchenko
Mark Shevchenko

Reputation: 8197

You can use SqlQuery:

var sql = string.Format("SELECT * FROM [{0}]", tablename);
var query = db.Database.SqlQuery<R1>(sql);

It could work if all of your tables R1--R2 have the same structure (properties and their types).

Upvotes: 1

Related Questions