2

I have been working in a project which uses Entity Framework as the ORM data model to connect to the SQL database and retrieve data.

Now the basic query which is used to retrieve data is like this

ProjectDataContext dataContext = new ProjectDataContext();   

var result = (from project in dataContext.Projects
              select project).ToList();

Or in lambda

List<Project> lstprojects = dataContext.Projects.Take(10);

Now I would like to pass the table name dynamically based on some input parameter. How can I achieve that?

The way I am currently doing it is a bit messy.

if(tableName = "A")
{
     List<A> lstOfA = dataContext.A.Take(10);
}
else if(tableName = "B")
{
     List<B> lstOfB = dataContext.B.Take(10);
}

and so on...

My question is if there is a neat and clean way to do this without writing so many if else because I understand it may cause performance issues in future.

Thanks

1
  • Your first LINQ snippet is effectively dataContext.Projects.ToList(), there's no need for the select project portion. As to your question, you need to realize that Entity Framework is there (mostly) to abstract away the database and lets you manipulate data in terms of C# types instead of database tables. If you'll pass a <T> to your method instead of tableName string, you'll be able to call dataContext.Set<T>() and get your desired DbSet. Commented Nov 22, 2015 at 13:16

1 Answer 1

1

Ok after some trial and error I have been able to do it like this-

var type = Type.GetType("A");
context.Set(type).Load();
var result = context.Set(type).Local.Cast<object>().ToList();

Hope it helps.`

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

2 Comments

GetProjects<Type.GetType("A")> does not compile
@Backs changed appraoch

Your Answer

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