How can I dynamically select my Table at runtime with Dynamic LINQ

后端 未结 2 1281
栀梦
栀梦 2020-12-20 09:46

I\'m developing an application to allow engineers to conduct simple single table/view queries against our databases by selecting Database, Table, Fields.

I get how t

相关标签:
2条回答
  • 2020-12-20 09:57

    You can use GetTable() to get the corresponding ITable of your data. Then coupled with using DLINQ, making it relatively easy.

    This example uses the AdventureWorks database. My project has the context defined in the DatabaseTest assembly in the DatabaseTest.AdventureWorks namespace.

    '' need my database and DLINQ extensions up top
    Imports DatabaseTest.AdventureWorks
    Imports System.Linq.Dynamic
    
    '' sample inputs
    Dim dc = New AdventureWorksDataContext()
    Dim tableName = "Contact"
    Dim whereClauses() = {"FirstName = ""John"" OR LastName = ""Smith"""}
    Dim selectColumns() = {"FirstName", "LastName"}
    
    '' get the table from a type (which corresponds to a table in your database)
    Dim typeName = "DatabaseTest.AdventureWorks." & tableName & ", DatabaseTest"
    Dim entityType = Type.GetType(typeName)
    Dim table = dc.GetTable(entityType)
    Dim query As IQueryable = table
    
    '' add where clauses from a list of them
    For Each whereClause As String In whereClauses
        query = query.Where(whereClause)
    Next
    
    '' generate the select clause from a list of columns
    query = query.Select(String.Format("new({0})", String.Join(",", selectColumns)))
    

    In retrospect, using reflection might have been the easier way to get the table since you have the name already. But then the names might not have a 1-to-1 correspondence so you'll have to compensate for it.

    Dim table As ITable = dc.GetType().GetProperty(tableName & "s").GetValue(dc, Nothing)
    
    0 讨论(0)
  • 2020-12-20 10:23

    See Get table-data from table-name in LINQ DataContext.

    This is probably actually better done by using direct SQL statements. LINQ will just get in your way.

    VB Conversion:

    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
    

    Usage:

    Dim myDataContext as New MyCustomDataContext
    myDataContext.GetTableByName("ORDERS").Where("...")
    
    0 讨论(0)
提交回复
热议问题