Dynamic query by LINQ

kavehyn

New member
Joined
Jun 4, 2008
Messages
2
Programming Experience
5-10
hello
i have about 30 tables with same structure:
Code smallint
Name nvarchar(50)

iwant to create a function with Linq Codes who recive the
name of table and return a query that i can set it
as a datagrid datasource
the quaery should return code,name columns


kindly can any one help me Please?

Rgards
 
I'm guessing that it will be little late for the OP but I'll answer this for others anyway.

First, you need to define a type to represent a record from one of those tables:
VB.NET:
Public Class PicklistItem

    Private _code As Integer
    Private _name As String

    Public Property Code() As Integer
        Get
            Return _code
        End Get
        Set(ByVal value As Integer)
            _code = value
        End Set
    End Property

    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

End Class
Now you call ExecuteQuery on a DataContext to execute a query against one of those tables and return an IEnumerable containing an instance of your type for each record:
VB.NET:
Private Function GetPicklistItems(ByVal tableName As String) As IEnumerable(Of PicklistItem)
    Using context As New MyDataContext
        Return context.ExecuteQuery(Of PicklistItem)("SELECT * FROM " & tableName)
    End Using
End Function
 

Latest posts

Back
Top