0

我正在尝试使用字符串来确定我正在执行查询的表。但是我找不到任何方法来做到这一点。这是我的代码:

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();
            }

是否可以更换

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

有一行使用我的表字符串而不是地址?因此它将是

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

编辑:

我这样做是为了学习 wpf/entity 框架/C#。当我在 puralsight 上观看视频时,我正在考虑尝试将其添加到该程序中的东西。

4

2 回答 2

1

这是我想出的解决方案。

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;

感谢所有评论/回答所有帮助并为我指明正确方向的人。

于 2013-01-17T13:51:41.130 回答
0

我的类的版本(.Net 4.0)System.Data.Objects.ObjectContext包含以下公共方法:

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

如果你愿意,你可以使用它,但是,我非常怀疑(而且我认为很多人也会同意我的观点)这是一件好事。请提供更多有关您要实现的目标的背景知识,因为很可能有更好的方法可以做到这一点,而不必求助于“魔术弦”。

于 2013-01-15T22:23:26.300 回答