David Reing
David Reing

Reputation: 40

Use a string to determine table to query

I am trying to use a string to determine the table that I am performing my query on. However I can not find any way to do this. Here is my code:

ADVENTUREWORKSSUPEREntities context = new ADVENTUREWORKSSUPEREntities();
string table = "Addresses" //this is set elsewhere in the code but I put it here for clarity

            if (table == "Addresses")
            {
                results.ItemsSource = context.Addresses.Where(condition).ToList();
            }
            else if (table == "Customers")
            {
               results.ItemsSource = context.Customers.Where(condition).ToList();
            }
              ...
              ...
              ...
            else if (table == "SalesOrderHeaders")
            {
                results.ItemsSource = context.SalesOrderHeaders.Where(condition).ToList();
            }

Is it possible to replace the

results.ItemsSource = context.Addresses.Where(condition).ToList();

with a line that uses my table string instead of Addresses? Thus it would be

results.ItemsSource = context.[table].Where(condition).ToList();

Edit:

I'm doing this as an exercise to learn wpf/entity framework/C#. As I am watching videos on puralsight I am thinking of stuff to try and adding it to this program.

Upvotes: 0

Views: 89

Answers (2)

David Reing
David Reing

Reputation: 40

Here is the solution that I came up with.

dynamic test = t.InvokeMember(table,
                        BindingFlags.DeclaredOnly |
                        BindingFlags.Public | BindingFlags.NonPublic |
                        BindingFlags.Instance | BindingFlags.GetProperty, null, context, new object[0]);

            ((IQueryable)test).AsQueryable().Where(condition).Load();
            results.ItemsSource = test.Local;

Thanks to everyone that commented/answered for all the help and pointing me in good directions.

Upvotes: 1

Fede
Fede

Reputation: 44038

My version (.Net 4.0) of the System.Data.Objects.ObjectContext class contains the following public method:

public ObjectSet<TEntity> CreateObjectSet<TEntity>(string entitySetName) where TEntity : class;

You can use that if you wish, however, I highly doubt (and I think many people will agree with me as well) that this is a good thing to do. Please give some more background as to what you're trying to achieve, because most probably there is a much better way of doing it without having to resort to "Magic Strings".

Upvotes: 0

Related Questions