我正在开发一个应用程序,允许工程师通过选择数据库、表、字段来对我们的数据库进行简单的单表/视图查询。
我知道如何使用动态 LINQ 库示例在运行时动态选择 Select、Where 和 Order by 子句,但我在如何分配表选择方面陷入僵局。
有没有办法在运行时动态选择“来自”表,如果你能提供一些具体的例子或指出我的方向吗?
真的非常感谢你。
编辑
所以两个答案似乎都在说同样的一般想法。我将尝试将 C# 转换为 VB 并让它工作。
第一个答案转换为
NotInheritable Class DataContextExtensions
Private Sub New()
End Sub
<System.Runtime.CompilerServices.Extension> _
Public Shared Function GetTableByName(context As DataContext, tableName As String) As ITable
If context Is Nothing Then
Throw New ArgumentNullException("context")
End If
If tableName Is Nothing Then
Throw New ArgumentNullException("tableName")
End If
Return DirectCast(context.[GetType]().GetProperty(tableName).GetValue(context, Nothing), ITable)
End Function
End Class
但它向我抛出了一个错误,指出扩展方法只能在模块中定义。但是当我将它包装在模块标签中时,它仍然会给出同样的错误。
所以我通过将它包装在模块标签中并剥离类标签来编译它。我也可以从中拉出最后一行并将其直接推入我的基本方法中,这样我就可以执行它,但是它似乎又是空的。当我尝试枚举结果时,没有任何结果。不确定这是我的代码问题还是新代码问题,我会测试更多。
这是我对第二个示例的转换,现在我要尝试看看是否可以让它们工作。经过一些测试后,我会带着问题或结果回来。
'get the table from a type (which corresponds to a table in your context)
Dim dataContextNamespace = "My.DataContext.Namespace"
Dim type = Type.[GetType](dataContextNamespace + tableName)
Dim table = dc.GetTable(type
'add where clauses from a list of them
For Each whereClause As String In whereClauses
table = table.Where(whereClause)
Next
'generate the select clause from a list of columns
Dim query = table.[Select]([String].Format("new({0})"), [String].Join(",", selectColumns))
谢谢您的帮助。BBL