2

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!

3
  • 1
    you should use a generic method, then you can use db.Set<T>. And you have to use reflection to get a type from your string. Commented Mar 4, 2015 at 12:52
  • There exists a old (but nice) library for dynamic linq queries. Not sure if it will help you out in this case. You might want to combine it with the stackoverflow question. Links: weblogs.asp.net/scottgu/… stackoverflow.com/questions/5032228/… Commented Mar 4, 2015 at 12:53
  • There might be an update to that, or similar, project here, not sure though: github.com/kahanu/System.Linq.Dynamic Commented Mar 4, 2015 at 12:56

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.