1.3 为什么要使用LINQ
- 评论:0
- 浏览:326
- RSS:0
参考第1.2小节的例子,如果我们没有使用 LINQ来列出来数据库表Users的所有数据,则需要以下步骤:
SqlConnection sqlConnection = new SqlConnection(“数据库链接字符串”);
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = “select * from users”;
sqlConnection.Open();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
DataSet dataSet = new DataSet();
SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
sqlDataAdapter.Fill(dataSet, dataTableName);
GridView1.DataSource=dataSet;
GridView1.DataBind();
而我们使用了LINQ后则简化为:
GridView1.DataSource=from c in users select c;
GridView1.DataBind();
由此可见,使用 LINQ可以使我们不用关心数据层,简化代码,从繁杂的数据操作中解脱出来,从而专注于面向对象设计。
当然,使用LINQ还有更多的优点,我们会在以后的章节中慢慢给大家介绍