使用实体框架和本机 sql 从 vb.net 中的 sqlserver 检索数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17900669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:25:28  来源:igfitidea点击:

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

vb.netwinformsentity-framework-4native-sql

提问by Khushi

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:

我想使用 vb.net、实体框架和本机 sql 在 Winforms 中检索数据。我使用了下面的代码,它允许我向 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?

但我不知道如何触发查询以从数据库中检索数据。假设我想从名为 SampleDB 的数据库中的 Cars 表中获取所有记录。所以我需要"SELECT * FROM Cars",但如何使用这个查询?

采纳答案by Recipe

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.

要么直接使用 SQL(通过 SQL 或存储过程)并使用 SqlConnection、SqlCommand 和 DataReader 或 DataAdapter 与服务器通信,要么正确使用已配置的实体框架。

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

我不是真的到 VB.Net,所以它会是伪代码,但你需要解决你的 EF 上下文。

Something like

就像是

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

回答by OneFineDay

To get all the cars it would be:

要获得所有汽车,它将是:

Using db As New SampleDBEntities
  Dim cars = db.Cars.ToList
End Using

To get all cars by type, if you have a 'type' field in that entity.

要按类型获取所有汽车,如果该实体中有“类型”字段。

Using db As New SampleDBEntities
  Dim mazdaCars = db.Cars.Where(Function(c) c.Type = "Mazda").ToList
End Using

ENtity Framework was built for LINQ and Lambda. Be sure to close/dispose your entity container object.

实体框架是为 LINQ 和 Lambda 构建的。请务必关闭/处置您的实体容器对象。