本系列为ScottGu的博客之LINQ to SQL系列,应博客堂邀请,本文译ScottGu的LINQ to SQL系列之Part(1- n)
为大家共享学习资料实在是一种乐趣!

本文同步发表在ScottGu的中文博客上
http://blog.joycode.com/scottgu/archive/2007/11/17/111496.aspx



 Over the last few months I wrote a series of blog posts that covered some of the new language features that are coming with the Visual Studio and .NET Framework "Orcas" release.  Here are pointers to the posts in my series:

在过去的几个月中我写了一系列涵盖了在VS和.NET Framework "Orcas" release 版中的一些新特性的帖子,下面是这些帖子的链接:

 

The above language features help make querying data a first class programming concept.  We call this overall querying programming model "LINQ" - which stands for .NET Language Integrated Query.

以上语言帮助将查询数据理解为一个类编程的理念。我们称这个总的查询编程模型为“LINQ”--它指的是.NET 语言集合查询。

Developers can use LINQ with any data source.  They can express efficient query behavior in their programming language of choice, optionally transform/shape data query results into whatever format they want, and then easily manipulate the results.  LINQ-enabled languages can provide full type-safety and compile-time checking of query expressions, and development tools can provide full intellisense, debugging, and rich refactoring support when writing LINQ code.

开发者可以在任何的数据源上使用LINQ。他们可以在编程语言中表达高效地查询行为,选择将查询结果转换或形成任何形式的他们想要转换为的结果集,然后非常方便地操作这个结果集。有LINQ功能的语言能完全的类型安全和查询表达式的编译时检查,并且开发工具提供了在写LINQ代码时完全的智能感知,调试,和重构的支持。

LINQ supports a very rich extensibility model that facilitates the creation of very efficient domain-specific operators for data sources.  The "Orcas" version of the .NET Framework ships with built-in libraries that enable LINQ support against Objects, XML, and Databases.

LINQ 支持这样一个非常广泛的的扩展模型:该模型是针对不同的数据源而生成不同的高效的操作因子。.NET Framework“Orcas"版本内嵌了LINQ语言对对象,XML和数据库的支持的词典。


What Is LINQ to SQL?

什么是LINQ to SQL?

LINQ to SQL is an O/RM (object relational mapping) implementation that ships in the .NET Framework "Orcas" release, and which allows you to model a relational database using .NET classes.  You can then query the database using LINQ, as well as update/insert/delete data from it.

LINQ to SQL 是O/RM(对象关系映射)在.NET Framework“Orcas" release中的的一种实现,它允许你用.NET 的类来生成一个关系型的数据库。然后你可以用LINQ对从该对象中对数据库进行查询,更新/插入/删除。

LINQ to SQL fully supports transactions, views, and stored procedures.  It also provides an easy way to integrate data validation and business logic rules into your data model.

LINQ to SQL完全支持事务,视图和存储过程。它还提供了一种方便地在你的数据模型中对集合数据验证和业务逻辑规则的进行验证的方法。

Modeling Databases Using LINQ to SQL:

LINQ to SQL 构造数据库:

Visual Studio "Orcas" ships with a LINQ to SQL designer that provides an easy way to model and visualize a database as a LINQ to SQL object model.  My next blog post will cover in more depth how to use this designer (you can also watch this video I made in January to see me build a LINQ to SQL model from scratch using it). 

VS "Orcas"中内置了一个提供了一种简单地将数据库可视化地转换为LINQ to SQL关系模型的设计器。我下一篇博客将会更深入一些来介绍怎么使用该设计器(你可以看这个我在1月份录制地关于如何使用它的录像  watch this video

Using the LINQ to SQL designer I can easily create a representation of the sample "Northwind" database like below:

通过LINQ to SQL设计器我可以方便地设计出如下的作为事例的"Northwind"数据库模型:

My LINQ to SQL design-surface above defines four entity classes: Product, Category, Order and OrderDetail.  The properties of each class map to the columns of a corresponding table in the database.  Each instance of a class entity represents a row within the database table.

上图定义了四个实体类:Product, Category, Order and OrderDetail.  每个类的属性都映射到数据库中相应的表中。每个类的实例代表了数据表中的一行记录。

The arrows between the four entity classes above represent associations/relationships between the different entities.  These are typically modeled using primary-key/foreign-key relationships in the database.  The direction of the arrows on the design-surface indicate whether the association is a one-to-one or one-to-many relationship.  Strongly-typed properties will be added to the entity classes based on this.  For example, the Category class above has a one-to-many relationship with the Product class.  This means it will have a "Categories" property which is a collection of Product objects within that category.  The Product class then has a "Category" property that points to a Category class instance that represents the Category to which the Product belongs.

在上图中,四个实体类中的箭头代表了各个实体之间的关系。它们主要是根据数据库中的主键/外键关系生成的。设计器上的箭头的指向表明了该关系是一对一还是一对多的关系。基于此,强类型的属性将会被加入到此实体类中。例如,上边的Category类和Product类之间有一个“一对多”的关系。这意味着我可以有一个"Categories"属性,该属性代表了所有的在该类中的产品对象集合。Product类将会有一个"Category"属性来指向一个Category 类的实例,该Category类的实例表明了了产品所属的类别。

The right-hand method pane within the LINQ to SQL design surface above contains a list of stored procedures that interact with our database model.  In the sample above I added a single "GetProductsByCategory" SPROC.  It takes a categoryID as an input argument, and returns a sequence of Product entities as a result.  We'll look at how to call this SPROC in a code sample below.

LINQ to SQL设计器的右侧是跟我们的数据库模型交互的存储过程。上边的例子中我添加了一个“GetProductsByCategory”存储过程。它有一个categoryID作为输入参数,返回一个产品序列。下面的事例代码将展示如何调用该存储过程。

Understanding the DataContext Class

了解DataContext类

When you press the "save" button within the LINQ to SQL designer surface, Visual Studio will persist out .NET classes that represent the entities and database relationships that we modeled.  For each LINQ to SQL designer file added to our solution, a custom DataContext class will also be generated.  This DataContext class is the main conduit by which we'll query entities from the database as well as apply changes.  The DataContext class created will have properties that represent each Table we modeled within the database, as well as methods for each Stored Procedure we added.

当你点击LINQ to SQL设计器上的“save"按钮时,VS将会保存代表了我们的实体和数据库关系的类。对于每一个LINQ to SQL设计器加入到我们的解决方案的文件,也会生成一个自定义的DataContext类。

For example, below is the NorthwindDataContext class that is persisted based on the model we designed above:

例如,下图就是基于我们上边设计的模型而生成的的NorthwindDataContext类:

LINQ to SQL Code Example

LINQ to SQL 代码事例

Once we've modeled our database using the LINQ to SQL designer, we can then easily write code to work against it.  Below are a few code examples that show off common data tasks:

用LINQ to SQL 设计器生成我们的数据库模型之后,我们就可以很方便地写代码对数据库进行操作。下边是一些展示了一些常用的数据库操作的代码:

1) Query Products From the Database

1)从数据库中查询 出Products


The code below uses LINQ query syntax to retrieve an IEnumerable sequence of Product objects.  Note how the code is querying across the Product/Category relationship to only retrieve those products in the "Beverages" category:

下面的代码用LINQ to SQL 查询语法来查询Product对象序列。注意代码是如何通过Product/Category关系来仅查出那些类别是"Beverages"的产品:
C#:

VB:

2) Update a Product in the Database

2)更新数据库中的一条产品记录


The code below demonstrates how to retrieve a single product from the database, update its price, and then save the changes back to the database:
下面的代码展示了如何从数据库中查询出单一的一条产品记录,更新它的价格,然后将更改保存至数据库:


C#:

VB:

Note: VB in "Orcas" Beta1 doesn't support Lambdas yet.  It will, though, in Beta2 - at which point the above query can be rewritten to be more concise.
注意:VB在"Orcas" Beta1中尚不支持lambdas。但是在Beta2中它就会支持了--那时代码就会能写得更为简洁一些。


3) Insert a New Category and Two New Products into the Database

3)向数据库中插入一条新的Category和两条新的Products

The code below demonstrates how to create a new category, and then create two new products and associate them with the
category.  All three are then saved into the database.

如下的代码展示了如何生成一个新的category,然后生成两条和该category相关联的产品,然后这三条记录被保存至数据库。

Note below how I don't need to manually manage the primary key/foreign key relationships. Instead, just by adding the Product objects into the category's "Products" collection, and then by adding the Category object into the DataContext's "Categories" collection, LINQ to SQL will know to automatically persist the appropriate PK/FK relationships for me. 

注意下边我如何不用手动地去维护主/外键关系,取而代之的是我只向categorys的"Products"集合中添加了两个Product记录,然后通过向DataContext的"Categories"集合中添加这个Category对象,LINQ to SQL将会知道自动是为我加上PK/FK的关系。


C#

VB:

4) Delete Products from the Database

4)从数据库中删除Products

The code below demonstrates how to delete all Toy products from the database:

下面的代码展示了如何从数据库中删除所有的玩具产品:


C#:

VB:

5) Call a Stored Procedure
5)调用存储过程

The code below demonstrates how to retrieve Product entities not using LINQ query syntax, but rather by calling the "GetProductsByCategory" stored procedure we added to our data model above.  Note that once I retrieve the Product results, I can update/delete them and then call db.SubmitChanges() to persist the modifications back to the database.

下面的代码展示了如何不用LINQ的查询语法查询Product实体,而是通过调用我们向数据模型中添加的“GetProductsByCategory”存储过程。注意,一旦我查询出了Product结果集,我可以更新/删除它们,然后再调用 db.SubmitChanges()来将这些更新提交到数据库。



C#:

VB:

6) Retrieve Products with Server Side Paging

6)查询在服务器端分页的产品


The code below demonstrates how to implement efficient server-side database paging as part of a LINQ query.  By using the Skip() and Take() operators below, we'll only return 10 rows from the database - starting with row 200.
下面的代码展示了如何实现作为LINQ语言一部分的高效地服务器端分页。通过用下面的Skip()和Take()操作符,我们从数据库中只查询出从200行开始的10条记录:

C#:

VB:

Summary
总结

LINQ to SQL provides a nice, clean way to model the data layer of your application.  Once you've defined your data model you can easily and efficiently perform queries, inserts, updates and deletes against it. 

LINQ to SQL提供了一种优秀、明了的方法来为你的应用程序来建立数据层。一旦你定义了数据模型,你就可以方便而且有效地对它进行查询,插入,更新和删除。

Hopefully the above introduction and code samples have helped whet your appetite to learn more.  Over the next few weeks I'll be continuing this series to explore LINQ to SQL in more detail.

希望以上的介绍和事例代码能够刺激你的胃口,让你学习到更多。在接下来的几周里我会在该系列中更具体地探索LINQ to SQL。
Hope this helps,

Scott

posted on 2007-11-16 12:40  是谁啊?  阅读(3731)  评论(7编辑  收藏  举报