C# 如何使用LINQ进行简单的数据库查询?
下面是我如何在C# 如何使用LINQ进行简单的数据库查询?,c#,.net,vb.net,linq,C#,.net,Vb.net,Linq,下面是我如何在.NET2.0中进行数据访问的。我应该如何使用.NET4.0中的LINQ来执行此操作 Dim dt As DataTable Using oDB As OleDbConnection = GetDbConnection() oDB.Open() Using oCmd As New OleDbCommand("SELECT * FROM TABLE1 WHERE COLUMN1 = @id", oDB) oCmd.Parameters.AddWithValue
.NET2.0
中进行数据访问的。我应该如何使用.NET4.0
中的LINQ来执行此操作
Dim dt As DataTable
Using oDB As OleDbConnection = GetDbConnection()
oDB.Open()
Using oCmd As New OleDbCommand("SELECT * FROM TABLE1 WHERE COLUMN1 = @id", oDB)
oCmd.Parameters.AddWithValue("@id", UserId)
oDB.Open()
dt = New DataTable()
Using da As OleDbDataAdapter = New OleDbDataAdapter(oCmd)
da.Fill(dt)
End Using
End Using
End Using
Msgbox "Surname: " + dt.Rows(0)("Surname")
如果使用以下命令,则执行查询的方式如下:
你也可以考虑。
首先,必须在你的机器上安装实体框架。您必须在项目中添加实体模型。它将使用内部VisualStudio工具自动将所有数据库表映射到类中。然后您必须像这样检索数据
假设数据库中有一个表Employee
,它映射到.net项目中的Employee
类
您必须使用以下代码获取年龄小于45岁的员工,其中age
是Employee
表的一个属性。它将自动映射为Employee
类的属性
我们开始吧
using(var _entities = new MyDBEntities())
{
//LINQ query
var query = from emp in _entities.Employees //Employees is the collection of Employee
where emp.Age < 45
select emp;
//query object will be containing all the employees in the form of collection whose age is
// less than 45
}
使用(var\u entities=new MyDBEntities())
{
//LINQ查询
var query=来自_entities.Employees//Employees中的emp是雇员的集合
其中皇帝年龄<45
选择emp;
//查询对象将以集合的形式包含年龄为的所有员工
//少于45
}
您确定这是Stackoverflow的一个好问题吗?您应该阅读一些关于LINQ to Entities
getstart with Entity Framework(EF)的教程,这些教程对实体不感兴趣。我正在访问的是一个预先存在的数据库。为什么你认为这样做有什么不对?你希望从使用LINQ中得到什么改进?@CJ7:我想你误解了什么。为了使用LINQ查询数据库,您需要使用LINQ提供程序。并且有两个流行的提供商可用。此外,它不是关于“更少的代码行”。还有更大的好处。为什么first或default
?为了确保只返回一条记录,但OP说他希望返回哪一条记录呢?:)我读了这个问题,好像他想要一个收藏(da.Fill(dt)
)
using(var context = new MyEntities())
{
var result = context.Table1.Where(x => x.Column1 == id);
}
using(var _entities = new MyDBEntities())
{
//LINQ query
var query = from emp in _entities.Employees //Employees is the collection of Employee
where emp.Age < 45
select emp;
//query object will be containing all the employees in the form of collection whose age is
// less than 45
}