65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 LINQ to SQL 进行简单的 GridView 绑定

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (4投票s)

2009年2月28日

CPOL

4分钟阅读

viewsIcon

116826

downloadIcon

1633

使用 LINQ to SQL 实现 Lambda 表达式或存储过程的 GridView 绑定。

screen1.jpg

引言

本文对于所有使用 ASP.NET 3.5 GridView 控件并希望使用 LINQ to SQL(利用 Lambda 表达式或预编译的存储过程)来绑定数据的用户将非常有帮助。

背景

dbml.jpg - Click to enlarge image

在创建上述 UI 之前,有必要先创建 LINQ to SQL 环境。您首先要做的是通过服务器资源管理器连接到数据库。然后,您需要通过右键单击解决方案资源管理器中的网站,选择“添加新项...”,然后在“模板”中选择“LINQ to SQL 类”,来向您的项目添加一个 LINQ to SQL 类。Visual Studio 将创建 *.dbml*.dbml.layout*.designer.cs 文件。这些文件基本上是您刚刚创建的 DataContext 类的图形表示、HTML 和代码隐藏。

现在只需将您希望 GridView 显示的表从服务器资源管理器中的数据库拖放到 *.dbml 文件上。DataContext 类将创建映射代码,该代码基本上是您刚刚选择的表的局部类。

 public System.Data.Linq.Table<User> Users
 {
  get
  {
   return this.GetTable<User>();
  }
 }
[Table(Name="dbo.Users")]
public partial class User : INotifyPropertyChanging, INotifyPropertyChanged
{ 
 private static PropertyChangingEventArgs emptyChangingEventArgs = 
				new PropertyChangingEventArgs(String.Empty);
 
 private System.Guid _UserID;
 
 private System.Data.Linq.Binary _Sid;
 
 private int _UserType;
 
 private int _AuthType;
 
 private string _UserName;
 
    #region Extensibility Method Definitions
    partial void OnLoaded();
    partial void OnValidate(System.Data.Linq.ChangeAction action);
    partial void OnCreated();
    partial void OnUserIDChanging(System.Guid value);
    partial void OnUserIDChanged();
    partial void OnSidChanging(System.Data.Linq.Binary value);
    partial void OnSidChanged();
    partial void OnUserTypeChanging(int value);
    partial void OnUserTypeChanged();
    partial void OnAuthTypeChanging(int value);
    partial void OnAuthTypeChanged();
    partial void OnUserNameChanging(string value);
    partial void OnUserNameChanged();
    #endregion
 
 public User()
 {
  OnCreated();
 }
 
 [Column(Storage="_UserID", DbType="UniqueIdentifier NOT NULL", IsPrimaryKey=true)]
 public System.Guid UserID
 {
  get
  {
   return this._UserID;
  }
  set
  {
   if ((this._UserID != value))
   {
    this.OnUserIDChanging(value);
    this.SendPropertyChanging();
    this._UserID = value;
    this.SendPropertyChanged("UserID");
    this.OnUserIDChanged();
   }
  }
 }
 
 [Column(Storage="_Sid", DbType="VarBinary(85)", UpdateCheck=UpdateCheck.Never)]
 public System.Data.Linq.Binary Sid
 {
  get
  {
   return this._Sid;
  }
  set
  {
   if ((this._Sid != value))
   {
    this.OnSidChanging(value);
    this.SendPropertyChanging();
    this._Sid = value;
    this.SendPropertyChanged("Sid");
    this.OnSidChanged();
   }
  }
 }
 
 [Column(Storage="_UserType", DbType="Int NOT NULL")]
 public int UserType
 {
  get
  {
   return this._UserType;
  }
  set
  {
   if ((this._UserType != value))
   {
    this.OnUserTypeChanging(value);
    this.SendPropertyChanging();
    this._UserType = value;
    this.SendPropertyChanged("UserType");
    this.OnUserTypeChanged();
   }
  }
 }
 
 [Column(Storage="_AuthType", DbType="Int NOT NULL")]
 public int AuthType
 {
  get
  {
   return this._AuthType;
  }
  set
  {
   if ((this._AuthType != value))
   {
    this.OnAuthTypeChanging(value);
    this.SendPropertyChanging();
    this._AuthType = value;
    this.SendPropertyChanged("AuthType");
    this.OnAuthTypeChanged();
   }
  }
 }
 
 [Column(Storage="_UserName", DbType="NVarChar(260)")]
 public string UserName
 {
  get
  {
   return this._UserName;
  }
  set
  {
   if ((this._UserName != value))
   {
    this.OnUserNameChanging(value);
    this.SendPropertyChanging();
    this._UserName = value;
    this.SendPropertyChanged("UserName");
    this.OnUserNameChanged();
   }
  }
 }

很快我们将使用此表来绑定 GridView 以显示所有记录,或使用 Lambda 表达式通过“Where”子句仅选择一条记录。作为示例,我们将使用存储过程实现相同目的。我已创建了一个作为示例的数据库。

CREATE PROCEDURE [dbo].[spGetUser]
@UserName nvarchar(260)

AS

BEGIN

    	SELECT UserID, UserName
	FROM Users
	WHERE UserName = @UserName

END

为此,您需要在服务器资源管理器中的数据库中创建一个存储过程,然后将其拖放到 *.dbml 文件上。现在 DataContext 类将创建存储过程的方法代码以及其局部类。

[Function(Name="dbo.spGetUser")]
 public ISingleResult<spGetUserResult> spGetUser
	([Parameter(Name="UserName", DbType="NVarChar(260)")] string userName)
 {
  IExecuteResult result = this.ExecuteMethodCall
	(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), userName);
  return ((ISingleResult<spGetUserResult>)(result.ReturnValue));
 }
public partial class spGetUserResult
{ 
 private System.Guid _UserID;
 
 private string _UserName;
 
 public spGetUserResult()
 {
 }
 
 [Column(Storage="_UserID", DbType="UniqueIdentifier NOT NULL")]
 public System.Guid UserID
 {
  get
  {
   return this._UserID;
  }
  set
  {
   if ((this._UserID != value))
   {
    this._UserID = value;
   }
  }
 }
 
 [Column(Storage="_UserName", DbType="NVarChar(260)")]
 public string UserName
 {
  get
  {
   return this._UserName;
  }
  set
  {
   if ((this._UserName != value))
   {
    this._UserName = value;
   }
  }
 }

Using the Code

既然我们已经准备好了 LINQ to SQL 环境,让我向您展示使用我们刚刚创建的 DataContext 类绑定 GridView 控件有多么简单。首先,我们必须实例化 DataContext 类,然后我们就可以使用它的方法和属性了。让我们看下面的示例代码。

ReportingServicesDataContext rpt = new ReportingServicesDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {      
        if (!IsPostBack)
        {
            GridView1.DataSource = rpt.Users.ToList();
            BindGrid("Binded");
        }
    }

如上所示,我们将 DataContext 变量 rpt 实例化为 ReportingServicesDataContext()。在 Page Load 事件中,GridView 控件的 DataSource 属性现在使用了 rpt 对象的用户表(Users table)和 LINQ 本身的 ToList() 方法。

请注意,Users 表现在是 rpt 对象的属性,它代表了表的映射,而 ToList() 方法用于强制立即查询执行并返回一个包含查询结果的 List(T)。因此,当调用 GridView 控件的 DataBind() 方法时,它将返回 Users 表的所有行,如上所示。

现在,让我们看看如何使用 Lambda 表达式过滤 Users 表的结果并将其绑定到 GridView,如下所示。

lambda.jpg

下面是实现此目的的示例代码。

protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = rpt.Users.Where(u => u.UserName=="Everyone").ToList();
        BindGrid("Binded using Lambda");
    }

在这里,我们过滤结果以仅获取 UserName 等于“Everyone”的记录。请注意,LINQ 的 Where() 方法通过注入 Lambda 表达式作为谓词来实现此结果。仅此而已!

现在,让我们使用之前创建的存储过程来实现相同的结果。我们应该得到以下结果。

StoreProc.jpg

以下是示例代码

protected void Button2_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = rpt.spGetUser("Everyone").ToList();
        BindGrid("Binded using Stored Procedure");
    }

还记得当我们将存储过程从服务器资源管理器拖放到 *.dbml 文件上时,您的 DataContext 创建了一个名为 [Function(Name="dbo.spGetUser")] 的函数和一个名为 spGetUserResult 的局部类吗? 好了,您现在可以看到它的实际应用了! 

spGetUser() 是 rpt 对象的一个方法,它需要一个参数 @UserName。 在我们的例子中,我们使用 @UserName="Everyone",然后 rpt 对象会为您处理一切,包括调用存储过程、传递参数并获取结果。 请注意,局部类 spGetUserResult 将根据查询定义要显示的列。 

这真是太酷了!

现在,这是 BindGrid() 的示例代码。

private void BindGrid(string label)
    {
        GridView1.DataBind();
        Label2.Text = label;
    }

这里没什么特别的,只是调用 GridViewDataBind() 方法并显示标签文本。

这就是使用 LINQ to SQL 技术进行简单的 GridView 绑定的全部内容!

希望您觉得本文有用,编码愉快,玩得开心!

历史

  • 2009年2月28日:初次发布
© . All rights reserved.