如何使用表名作为实体的变量?

时间:2019-04-17 20:04:25

标签: vb.net entity-framework-6

在VB .net中,我正在使用Entity Framework,我有一个包含DataGridView的表单(frmAdd),其数据源为:

DataGridView1.DataSource = myEntity.Genders.ToList

我想将(性别)设为这样的变量:

DataGridView1.DataSource = myEntity.tblName.ToList

这是我的代码:

Public Class frmAdd

Dim myEntity As New HRDataEntities

Dim tblName As String

Private Sub frmAdd_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    DataGridView1.DataSource = myEntity.Genders.ToList

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

       tblName = "Jobs"

编辑器中不接受下一行:

       DataGridView1.DataSource = myEntity.tblName.ToList

       DataGridView1.Refresh()

    End Sub

 End Class

1 个答案:

答案 0 :(得分:0)

您可以使用DbContext.Set Method动态获取DbSet。但是,您不必使用名称Type来代替它。

Dim entityType As Type

entityType = GetType(Jobs)
DataGridView1.DataSource = context.[Set](entityType).Cast(Of Object)().ToList()