Search code examples
vb.netwinformsentity-framework-4native-sql

Retrieve data from sqlserver in vb.net using entity framework and native sql


I want to retrieve data in Winforms using vb.net, entity framework and native sql. I have used the code below which allows me to add data to the sql:

Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim db As New SampleDBEntities
    Dim bs As New BindingSource
    bs.DataSource = db.Cars.Local
    DataGridView1.DataSource = bs
End Sub

But I don't know how to fire a query to retrieve data from database. Suppose I want to get all the records from Cars table in my Database named SampleDB. So I need "SELECT * FROM Cars", but how to use this query?


Solution

  • Either you work with SQL directly (through SQL or stored procedures) and communicate with the server using SqlConnection, SqlCommand and perhaps DataReader or DataAdapter or you correctly use the Entity Framework that you have configured.

    I'm not really into VB.Net, so it'll be pseudocode, but you need to be addressing your EF context.

    Something like

    using (myEntityModel context = new myEntityModel()) 
    {
        MyResult = context.Cars.where(c => c.model == "myModel").ToList();
    }