Using LINQ in ASP.NET

Using LINQ in ASP.NET (1)


Linq简介

     LINQ,语言级集成查询(Language INtegrated Query),面向对象编程技术( object-oriented (OO) programming technologies )在工业领域的应用已经进入了一个稳定的发展阶段。程序员现在都已经认同像 类(classes)、对象(objects)、方法(methods)这样的语言特性。考察现在和下一代的技术,一个新的编程技术的重大挑战开始呈现出来,即面向对象技术诞生以来并没有解决降低访问和整合信息数据( accessing and integrating information )的复杂度的问题。其中两个最主要访问的数据源与数据库( database )和 XML 相关。

  LINQ 提供了一条更常规的途径即给 .Net Framework 添加一些可以应用于所有信息源( all sources of information )的具有多种用途( general-purpose )的语法查询特性( query facilities ),这是比向开发语言和运行时( runtime )添加一些关系数据( relational )特性或者类似 XML 特性( XML-specific )更好的方式。这些语法特性就叫做 .NET Language Integrated Query (LINQ) 。

                                                                                                                                                    -----------------from  百度百科

LINQ改变了我们写数据应用程序的方式,先前,开发人员需要考虑并编写不用的代码来处理不同数据源中的数据(SQL Server ,XML ,Memory....)。LINQ很好的帮我们解决了这个烦人的问题。下面我将简单介绍如何在ASP.NET中使用LINQ。

Example

个人认为学习Linq最好的方法就是通过实例来学习。光看书本上的理论效率是很慢的。我将作一个简单的web应用程序,实现对数据的增删改操作。用到大家都熟悉的Northwind数据库。

一.引用命名空间

System.Data.Linq

System.Data.Linq.Mapping (需要在项目中先引用System.Data.Linq)

二.为数据库表创建实体类


[Table(Name="Employees")]
public class Employee
{
 [Column(IsDbGenerated
=true,IsPrimaryKey=true)]
 
public int EmployeeID { getset; }

 [Column(Name
="FirstName",DbType="varchar(20)")]
 
public string FirstName { getset; }

 [Column(Name 
= "LastName", DbType = "varchar(20)")]
 
public string LastName { getset; }

}

常用的属性声明,可以很好的描述表中字段的属性:

Name: 字段的名称

DbType: 字段的数据类型

IsDbGenerated: 是否自动生成

CanBeNull: 字段是否为空

Storage: 保存数据的类字段名

三.创建一个强类型的数据环境

我们的数据库系统可能会和多种类型的数据源打交道,所以应该使我们的程序有和数据源进行创建连接的能力。这里我们将创建的NorthwindDb类继承DataContext基类。DataContext类表示LINQ to SQL 框架的主入口点。

其中有相关的处理LINQ to SQL的类,方法等。

public class NorthwindDb:DataContext
{
    
public NorthwindDb(string connectionString):base(connectionString)
    {

    }

    
public Table<Employee> Employee;
}

 

四.创建Web From

首先为GridView绑定数据


private void BindGridView(string criteria)
    {
        
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        NorthwindDb db 
= new NorthwindDb(strConn);

        IEnumerable
<Employee> results;

        
if (criteria == string.Empty)
        {
            results
=db.Employee.ToArray();
        }
        
else
        {
            results 
= (from c in db.Employee
                          
where c.FirstName.Contains(criteria)
                          select c).ToArray();
            
        }
        GridView1.DataSource 
= results;
        GridView1.DataBind();
    }

搜索按钮只需将参数传进去即可BindGridView(TextBox1.Text);

如果选中了GridView中的某一行,则需要将选中的数据绑定到DetailsView 中进行编辑使用。


private void BindDetailsView()
    {
        
int employeeID = (int)GridView1.SelectedValue;
        
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        NorthwindDb db 
= new NorthwindDb(strConn);

        var results 
= from emp in db.Employee
                      
where emp.EmployeeID == employeeID
                      select emp;

        DetailsView1.DataSource 
= results;
        DetailsView1.DataBind();

    }

 


 protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        GridView1.SelectedIndex 
= e.NewSelectedIndex;
    }
    
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        
int employeeID = (int)GridView1.SelectedValue;
        
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        BindDetailsView();
    }

 

接下来就是对数据的增删改操作:

 

 


protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        NorthwindDb db 
= new NorthwindDb(strConn);

        var results 
= from emp in db.Employee
                                        
where emp.EmployeeID == (int)DetailsView1.SelectedValue
                                        select emp;


        results.First().FirstName 
= ((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text;
        results.First().LastName 
= ((TextBox)DetailsView1.Rows[2].Cells[1].Controls[0]).Text;
        
        db.SubmitChanges();
        BindGridView(
string.Empty);

    }
    
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        NorthwindDb db 
= new NorthwindDb(strConn);

        Employee emp 
= new Employee();
        emp.FirstName 
= ((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text;
        emp.LastName
= ((TextBox)DetailsView1.Rows[2].Cells[1].Controls[0]).Text;
        db.Employee.InsertOnSubmit(emp);
        db.SubmitChanges();
        BindGridView(
string.Empty);

    }
protected void DetailsView1_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
    {
        
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        NorthwindDb db 
= new NorthwindDb(strConn);

        var results 
= db.Employee.Single(emp => emp.EmployeeID==(int)DetailsView1.SelectedValue);
        db.Employee.DeleteOnSubmit(results);
        db.SubmitChanges();
        BindGridView(
string.Empty);

    }

 更新和添加的操作差不多,只是作了些小的改动。

ok,这就是在ASP.NET中利用LINQ对数据的操作。

源码:aspLINQ.zip


 

Using LINQ in ASP.NET (2)

Using LINQ in ASP.NET (1)

中介绍了利用LINQ to SQL实现对数据的增删改的操作,但是在实际的项目应用中,我们经常会使用到存储过程。本篇将介绍如何利用LINQ对存储过程进行操作。

我们利用的还是Northwind数据库,首先创建存储过程

(1)返回所有EMPLOYEES 的信息

CREATE PROCEDURE [dbo].[Employees_GetAll]
AS
SELECT * FROM EMPLOYEES ORDER BY EMPLOYEEID

(2)根据EMPLOYEEID获得信息

CREATE PROCEDURE [dbo].[Employees_GetByID]
(
@ID int
)
AS
SELECT * FROM EMPLOYEES WHERE EMPLOYEEID=@ID

(3)添加职员信息

CREATE PROCEDURE [dbo].[Employees_Insert]
(
@FIRSTNAME NVARCHAR(20),
@LASTNAME NVARCHAR(20)
)
AS
INSERT INTO EMPLOYEES(FIRSTNAME,LASTNAME)
VALUES(@FIRSTNAME,@LASTNAME)

(4)更新职员信息

CREATE PROCEDURE [dbo].[Employees_Update]
(
@ID INT,
@FIRSTNAME NVARCHAR(20),
@LASTNAME NVARCHAR(20)
)
AS
UPDATE EMPLOYEES
SET FIRSTNAME=@FIRSTNAME,
LASTNAME=@LASTNAME
WHERE EMPLOYEEID=@ID

(5)删除职员信息

CREATE PROCEDURE [dbo].[Employees_Delete]
(
@ID INT
)
AS
DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@ID

前面我们知道了如何将一个数据表映射为实体类,现在我们要将存储过程也相应的映射成为实体类,创建LINQ to SQL 的类文件。


[Function(Name = "Employees_GetAll")]
public ISingleResult<Employee> GetAllEmployees()
{
IExecuteResult result 
= this.ExecuteMethodCall
(
this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((ISingleResult<Employee>)(result.ReturnValue));
}

GetAllEmployees()  方法利用[Function]属性进行描述,由于存储过程的返回值可能是一个或多个记录,方法返回值的类型必须和ISingleResult类型相匹配。存储过程返回的字段页必须和Employee类中声明的相一致。

GetEmployeeByID() 接收一个参数,并且返回一行


[Function(Name="Employees_GetByID")]
public ISingleResult<Employee> GetEmployeeByID
([Parameter(Name 
= "ID", DbType = "Int")] 
System.Nullable
<int> iD)
{
IExecuteResult result 
= this.ExecuteMethodCall
(
this, ((MethodInfo)(MethodInfo.GetCurrentMethod())),
 iD);
return ((ISingleResult<Employee>)(result.ReturnValue));
}

调用存储过程的时候需要传入一个参数,方法的参数和存储类型的参数可以用[Parameter] 进行匹配。参数传给ExecuteMethodCall() 方法。大多数的代码都是差不多的。

下面是对数据添加,删除,修改的方法


[Function(Name = "Employees_Insert")]
    
public int InsertEmployee([Parameter(Name = "FirstName", DbType = "nvarchar(20)")] string fname, [Parameter(Name = "LastName", DbType = "nvarchar(20)")]string lname)
    {
        IExecuteResult result 
= this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())),fname,lname);
        
return (int)result.ReturnValue;
    }

    [Function(Name 
= "Employees_Update")]
    
public int UpdateEmployee([Parameter(Name = "ID", DbType = "Int")] System.Nullable<int> iD, [Parameter(Name = "FirstName", DbType = "nvarchar(20)")] string fname, [Parameter(Name = "LastName", DbType = "nvarchar(20)")]string lname)
    {
        IExecuteResult result 
= this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())),iD,fname, lname);
        
return (int)result.ReturnValue;
    }

    [Function(Name 
= "Employees_Delete")]
    
public int DeleteEmployee([Parameter(Name = "ID", DbType = "Int")] System.Nullable<int> iD)
    {
        IExecuteResult result 
= this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), iD);
        
return (int)result.ReturnValue;
    }

好了,方法创建好了,接下来就是在ASP.NET Web Form中对这些方法进行调用。

添加一个DetailsView 控件。对它进行数据的绑定,方法和(1)中的基本一样


private void BindDetailsView()
    {
        
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        NorthwindDb db 
= new NorthwindDb(strConn);
        ISingleResult
<Employee> results = db.GetAllEmployees();
        DetailsView1.DataSource 
= results;
        DetailsView1.DataBind();
    }

 

利用DetailsView 控件对数据执行增加,删除,修改的操作


protected void DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        NorthwindDb db 
= new NorthwindDb(strConn);
        db.UpdateEmployee((
int)DetailsView1.SelectedValue,((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text, ((TextBox)DetailsView1.Rows[2].Cells[1].Controls[0]).Text);
    }
    
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        NorthwindDb db 
= new NorthwindDb(strConn);
        db.InsertEmployee(((TextBox)DetailsView1.Rows[
1].Cells[1].Controls[0]).Text, ((TextBox)DetailsView1.Rows[2].Cells[1].Controls[0]).Text);
    }
    
protected void DetailsView1_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
    {
        
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        NorthwindDb db 
= new NorthwindDb(strConn);
        db.DeleteEmployee((
int)DetailsView1.SelectedValue);
    }

这样通过存储过程对数据操作就搞定了。

源码:aspLINQ2.rar

 

Using LINQ in ASP.NET (3)

我们讨论了如何用LINQ TO SQL查询和处理数据,并却学习了如何用LINQ处理存储过程。在先前的例子中,我们是通过创建实体类和我们的数据相关联的,Visual Studio提供了内嵌的设计模式来处理同样的功能。接下来将讨论如何在项目中使用这些类。

   首先添加一个LINQ to SQL 类文件

它将在我们的App_Code文件夹下添加三个文件。.dbml文件(xml对整个类的映射),.layout文件,.cs文件(包含所有自动生成的代码)。

现在我门使用数据库资源管理器连接我们的数据库,将Employees表拖到DBML设计器上。

 

这样编译器将自动为我们生成一个实体类,你可以删除不需要的字段。

同样的方法,我们可以将添加,删除,更新的存储过程也加入到我们的项目中。

为了对实体类指定添加,更新,删除的操作,可以在CEmployee 类上右击鼠标,选择配置行为,将出现下面的窗口:

接下来你就可以通过存储过程为实体类添加新增,更新,删除的行为。ok,这样就通过Visual Studio为我们的工程创建了实体类。

下面利用所建的实体类来完成和(2)中同样的操作

Code

 

对数据的操作:

Code

 

是不是很方便?LINQ to SQL的使用就说到这里。

posted on 2011-11-30 21:05  缘从心开始  阅读(399)  评论(1编辑  收藏  举报

导航

文章作者:(Super)
文章出处:http://www.cnblogs.com/superai
欢迎转载,转载时请注明出处。谢谢合作。