[英]C#/LINQ Automated filtering on all tables
我正在使用C#和LINQ to SQL。
对于我的家庭作业,我必须创建一个应用程序,该应用程序将允许用户按某些列过滤数据库中的任何表。 我的想法是,我将DropdownList与表列表,3个TextBoxes +标签,DataGridView和Button一起使用。 当用户选择表时,标签文本更改为与所选表中的前三列匹配,然后当用户按下按钮时,程序执行查询,该查询将按textBoxes中的值过滤行。
例如,如果用户选择表“ Customers”,则分配给textBoxes的标签将更改为“ CustomerID”,“ Name”,“ Address”。 如果用户输入文本框“ 10”,“ Smith”,“ 11 Golden St.” 并按按钮,DataGridView将仅显示ID=10
或Name=Smith
或Address=11 Golden St.
所有这些都很简单,但是数据库有20多个表,因此仅做一项家庭作业就需要很多工作。 我想知道,是否有一种方法可以自动执行此过程,所以我不必编写单独的代码来筛选每个表并返回结果。
我已经想到,我可以使用myDataContext.GetType().GetProperties()
并对其进行遍历,将property.Name
添加到我的DropdownList项目中以创建我的表列表。 问题是去做剩下的。 映射的表(例如, Customers
)没有任何有用的属性( Customers
是System.Data.Linq.Table<Customer>
类型,而必需的属性在Customer
类中)。 我不知道如何从中提取引用的类Linq.Table<>
例如: Customer
从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个不同的表编写相同的代码...
您可以使用Type.GetGenericArguments()获得对象的通用类型,如下所示:
Type tableType = linqTable.GetGenericArguments()[0];
label1.Text = tableType.GetProperties()[0].Name;
您可能可以通过构建表达式树来创建动态LINQ查询,但是我不确定您将如何执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.