在本文中,将探讨如何使用LINQ(Language Integrated Query)来创建类和应用程序。LINQ是一种集成在.NET语言中的查询语言,它允许开发者以声明式的方式处理数据。将从创建一个简单的地址簿应用程序开始,该程序将展示如何使用LINQ进行数据库操作。
首先,将使用Visual Studio的LINQ toSQL类生成器来创建类。将这个类命名为_AddressBook.dbml。在设计视图中,将数据库中的Addresses表拖放到设计面板上,并将其重命名为Addresses。接下来,需要设置_AddressBookDataContext的属性,确保它们具有正确的命名空间,并且连接字符串是从web.config文件中获取的。
接下来,将创建一个名为AddressBook的包装类,它将包装_AddressBook。这个类非常简单,它只初始化对象并提供对表的简单访问。需要注意的是,确保命名空间与_AddressBook使用的一致,并且AddressBookConnectionString在web.config中。
using System.Configuration;
namespace Clarity.Database
{
public class AddressBook
{
private _AddressBookDataContext _AddressBook;
public AddressBook()
{
string conn = ConfigurationManager.ConnectionStrings["AddressBookConnectionString"].ToString();
_AddressBook = new _AddressBookDataContext(conn);
}
public System.Data.LINQ.Table<addresses> Addresses
{
get { return _AddressBook.Addresses; }
}
}
}
将展示如何通过LINQ轻松访问表。如果想要完整的应用程序,请查看文章末尾。现在,将进行初始化和访问数据库的繁琐步骤。
private AddressBook thisAddressBook = new AddressBook();
现在,可以通过thisAddressBook对象完全访问数据库。使用这个对象,可以通过操作一个简单的泛型类来查询、插入、更新和删除数据库表中的项目。
将使用ASP.NET来加载数据到GridView控件中。
private void LoadGrid()
{
GridView1.DataSource = thisAddressBook.Addresses.OrderBy(c => c.LastName);
GridView1.DataBind();
}
这个查询将按LastName字段排序的数据输出到数据源中。在lambda表达式(c => c.LastName)中,c代表对象,也可以使用obj,如(obj => obj.LastName)。选择的任何对象名称都可以工作;只需要在整个表达式中保持一致即可。
将加载表中的数据子集到数据源中,其中LastName字段必须以filter变量指定的内容开始。
private void LoadGrid(string filter)
{
GridView1.DataSource = thisAddressBook.Addresses.Where(c => c.LastName.StartsWith(filter));
GridView1.DataBind();
}
将展示如何删除GridView中的记录。
protected void GridView1_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
Addresses thisAddress = thisAddressBook.Addresses.First(x => x.ID == id);
thisAddressBook.Addresses.DeleteOnSubmit(thisAddress);
thisAddressBook.SubmitChanges();
}
第四行的赋值(Address thisAddress ...)查询数据库中指定ID的第一个出现,并将其分配给thisAddress。然后,thisAddressBook对象(表)被告知从表中删除该条目并保存更改。
这个函数接受一个已更改或新的Addresses对象,并将其更新或插入到表中。
protected void AddressUpdated(object sender, UserData.UpdateEvent e)
{
Addresses thisAddress;
int id = e.Address.id;
// 如果这个值是0,则添加一条记录
if (id != 0)
thisAddress = thisAddressBook.Addresses.First(x => x.ID == id);
else
thisAddress = new Addresses();
thisAddress.FirstName = e.Address.FirstName;
thisAddress.LastName = e.Address.LastName;
thisAddress.Address1 = e.Address.Address1;
thisAddress.City = e.Address.City;
thisAddress.State = e.Address.State;
thisAddress.Zip = e.Address.Zip;
thisAddress.Email = e.Address.Email;
if (id != 0)
thisAddressBook.Addresses.SubmitChanges();
else
thisAddressBook.Addresses.InsertOnSubmit(thisAddress);
thisAddressBook.SubmitChanges();
}
对查询实际命令数据库执行的操作感兴趣。它是在加载所有记录后再进行过滤吗?它是定制查询以仅获取请求的信息吗?让看看结果...
LoadQuery的结果:
SELECT [t0].[id], [t0].[FirstName], [t0].[LastName], [t0].[Address1], [t0].[City], [t0].[State], [t0].[Zip], [t0].[Email] FROM [dbo].[Addresses] AS [t0] ORDER BY [t0].[LastName]
Filtered Query的结果:
exec sp_executesql N'SELECT [t0].[id], [t0].[FirstName], [t0].[LastName], [t0].[Address1], [t0].[City], [t0].[State], [t0].[Zip], [t0].[Email] FROM [dbo].[Addresses] AS [t0] WHERE [t0].[LastName] LIKE @p0 ORDER BY [t0].[LastName]', N'@p0 nvarchar(2)', @p0=N'H%'
Delete Query的结果:
exec sp_executesql N'DELETE FROM [dbo].[Addresses] WHERE ([id] = @p0) AND ([FirstName] = @p1) AND ([LastName] = @p2) AND ([Address1] = @p3) AND ([City] = @p4) AND ([State] = @p5) AND ([Zip] = @p6) AND ([Email] = @p7)', N'@p0 int,@p1 nvarchar(5),@p2 nvarchar(5),@p3 nvarchar(15),@p4 nvarchar(10),@p5 nvarchar(2),@p6 nvarchar(5),@p7 nvarchar(15)', @p0=4,@p1=N'Kelly', @p2=N'Smith', @p3=N'123 Fake Street', @p4=N'Manchester', @p5=N'NH', @p6=N'03102', @p7=N'kelly@gmail.com'
Insert Query的结果:
exec sp_executesql N'INSERT INTO [dbo].[Addresses]([FirstName], [LastName], [Address1], [City], [State], [Zip], [Email]) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6) SELECT [t0].[id] FROM [dbo].[Addresses] AS [t0] WHERE [t0].[id] = (SCOPE_IDENTITY())', N'@p0 varchar(7),@p1 varchar(6),@p2 varchar(15),@p3 varchar(9),@p4 varchar(2),@p5 varchar(5),@p6 varchar(18)', @p0=N'John', @p1=N'Smith', @p2=N'123 Fake Street', @p3=N'Somewhere', @p4=N'CT', @p5=N'03102', @p6=N'nobody@nowhere.com'