1

我正在使用 C# 和 LINQ to SQL。

对于我的家庭作业,我必须创建一个应用程序,它允许用户按某些列过滤数据库中的任何表。这个想法是我使用带有表格列表、3 个文本框 + 标签、DataGridView 和按钮的 DropdownList。当用户选择表时,标签文本更改为匹配所选表中的前 3 列,然后当用户按下按钮时,程序执行查询,该查询将按文本框中的值过滤行。

例如,如果用户选择表“客户”,则分配给文本框的标签将更改为“客户 ID”、“名称”、“地址”。如果用户输入文本框“10”、“Smith”、“11 Golden St.”。并按下按钮,DataGridView 将仅显示带有ID=10Name=Smith或的用户Address=11 Golden St.

这一切都很简单,但是数据库有 20 多个表,所以仅仅做一个家庭作业就需要做很多工作。我想知道,是否有办法自动化这个过程,所以我不必编写单独的代码来过滤每个表并返回结果。

我已经想到,我可以使用myDataContext.GetType().GetProperties()并遍历它,将其添加property.Name到我的 DropdownList 项目中以创建我的表格列表。问题是做剩下的事情。例如Customers,映射表没有任何有用的属性(Customers属于类型System.Data.Linq.Table<Customer>,所需的属性在类中Customer)。我不知道如何从Linq.Table<>(例如Customerfrom Linq.Table<Customer>)中提取引用的类,即使可以在不明确知道表名的情况下构建查询(仅使用GetType().GetProperties()和类似)。

我的目标是做(或找出是否不可能做)这样的事情:

myDropdown_SelectedIndexChanged()
{
    string tableName = myDropdown.SelectedItem.ToString();
    <some universal type> table = dataContext.GetType.GetProperty(tableName)
    .SomeFunctionIDontKnowAbout(); //something to get class "Customer" if selected table was "Customers"
    label1.Text = table.GetType().GetProperties()[0].Name; // set first column name as label's text
}

然后点击按钮:

string tableName = myDropdown.SelectedItem.ToString();
var query = dataContext.GetProperty(tableName)
.Select(table => table.GetProperties()[0] == textBox1.Text); 
//select from dynamically chosen table where value in first column matches text in textBox1

这甚至可能吗?我希望我的老师没有给我们这个作业,所以我们会一次又一次地为 20 个不同的表编写相同的代码......

4

1 回答 1

1

您可以使用Type.GetGenericArguments()获取对象的泛型类型,如下所示:

Type tableType = linqTable.GetGenericArguments()[0];
label1.Text = tableType.GetProperties()[0].Name;

您也许可以通过构建Expression Tree创建动态 LINQ 查询,但我不确定您将如何做到这一点。

于 2012-12-02T18:05:43.180 回答