LINQ and Entity Framework with DbContext – Convert Anonymous type to Strongly Typed – Bind to ListBox
03-Jul-1212 Leave a comment
[ Personally I have a sample of this in EFSample1.sln ]
To convert anonymous type to strongly typed, you can add a class that does what you want, then Select New … with {.ID = …}
This allows you to say get data from more than one table and still have a strongly typed output. Will not be updateable.
To fill a ListBox use
Imports System.Linq ‘if namespace not already imported
Dim result = …GetEmployees
ListBox.DataSource = result.ToList
To save on setting the DisplayMember use .ToString in the class
Public Class EmployeeList
Property ID As Integer
Property FullName As String
Overrides Function ToString() As String
Return FullName
End Function
End Class
Public Class EmployeeEF
Private context As New EFWinFormsDBContext.TestEFIEntities
Function GetEmployees() As System.Linq.IQueryable(Of EmployeeList)
Dim result = From emp As Employee In context.Employees Join con As Contact In context.Contacts On emp.EmployeeID Equals con.ID Order By con.FullName
Select New EmployeeList With {.ID = emp.EmployeeID, .FullName = con.FullName}
Return result
End Function
End Class