更为简洁的版本将会发布在博客堂(除去了英文的版本),希望本文能对您有所帮助!

允许转载,麻烦注明出处:http://www.cnblogs.com/hanxianlong 
 原文链接:
http://weblogs.asp.net/scottgu/archive/2007/05/29/linq-to-sql-part-2-defining-our-data-model-classes.aspx

In Part 1 of my LINQ to SQL blog post series I discussed "What is LINQ to SQL" and provided a basic overview of some of the data scenarios it enables.

在我的LINQ to SQL系列博客的第一部分(Part 1)我讲解了“什么是LINQ to SQL"并且提供了一些LINQ to SQL能支持的数据环境。

In my first post I provided code samples that demonstrated how to perform common data scenarios using LINQ to SQL including:
在我的第一篇帖子中,我提供了展示如何用LINQ to SQL来进行一些常用的数据处理,包括如下几个方面:

  • How to query a database
  • 如何查询数据库
  • How to update rows in a database
  • 如何更新数据库中的行
  • How to insert and relate multiple rows in a database
  • 如何在数据库中插入并操作关联操作数据行
  • How to delete rows in a database
  • 如何在数据库中删除记录
  • How to call a stored procedure
  • 如何调用存储过程
  • How to retrieve data with server-side paging
  • 如何查询在服务器端分页的数据

I performed all of these data scenarios using a LINQ to SQL class model that looked like the one below:


所有的这些数据操作,我都是在如下的这个LINQ to SQL 类模型中进行的:

In this second blog post in the series I'm going to go into more detail on how to create the above LINQ to SQL data model.

在本系列的第二篇帖子中,我将更具体地讲解一下如何生成上面这个LINQ to SQL 数据模型。


LINQ to SQL, the LINQ to SQL Designer, and all of the features that I'm covering in this blog post series will ship as part of the .NET 3.5 and Visual Studio "Orcas" release. 

LINQ to SQL,LINQ to SQL设计器,和我在这个博客系列中提到的所有特性都是.NET 3.5中和VS "Orcas"版本中的一部分。

You can follow all of the steps below by downloading either Visual Studio "Orcas" Beta 1 or Visual Web Developer Express "Orcas" Beta1.  Both can be installed and used side-by-side with VS 2005.

你可以从Visual Studio "Orcas" Beta 1Visual Web Developer Express "Orcas" Beta1中下载来跟着如下的操作,两个个都可以和VS2005一起安装。



Create a New LINQ to SQL Data Model

新建一个新的ILNQ to SQL数据模型


You can add a LINQ to SQL data model to an ASP.NET, Class Library or Windows client project by using the "Add New Item" option within Visual Studio and selecting the "LINQ to SQL" item within it:

你可以向ASP.NET,类库或Windows客户端的项目中按照如下方式添加LINQ to SQL数据模型:点击"Add New Item"选项,在弹出的对话框中选择“LINQ to SQL"项:

Selecting the "LINQ to SQL" item will launch the LINQ to SQL designer, and allow you to model classes that represent a relational database.  It will also create a strongly-typed "DataContext" class that will have properties that represent each Table we modeled within the database, as well as methods for each Stored Procedure we modeled.  As I described in Part 1 of this blog post series, the DataContext class is the main conduit by which we'll query entities from the database as well as apply changes back to it.

选择"LINQ to SQL"项将会弹出"LINQ to SQL"设计器,然后允许你制作一个代表了关系型数据库的模型类。它还会生成一个强类型的"DataContext"类,该类会有代表了我们从数据库以代表了我们数据库的每一张数据表的属性,代表了我们数据库中的存储过程的方法。如我在该系列的Part 1 中描述的那样,DataContext类是我们从数据库中查询以及将更新存回至数据库中的一个主要管道。


Below is a screen-shot of an empty LINQ to SQL ORM designer surface, and is what you'll see immediately after creating a new LINQ to SQL data model:

下面是一个空LINQ to SQL 的ORM设计器的屏幕截图,也是在生成了一个新的LINQ to SQL数据模型之后你首先会看到的:

 

Entity Classes

实体类

LINQ to SQL enables you to model classes that map to/from a database.  These classes are typically referred to as "Entity Classes" and instances of them are called "Entities".  Entity classes map to tables within a database.  The properties of entity classes typically map to the table's columns.  Each instance of an entity class then represents a row within the database table.

LINQ to SQL 使你制作一个映射了或映射到数据库的类。这些类被有称为“实体类”并且它们的实例被“实体”。实体类映射了数据库中的数据表。实体的属性映射到表的列。每个实体代表了数据表中的一行记录。


Entity classes defined with LINQ to SQL do not have to derive from a specific base class, which means that you can have them inherit from any object you want.  All classes created using the LINQ to SQL designer are defined as "partial classes" - which means that you can optionally drop into code and add additional properties, methods and events to them.

用LINQ to SQL定义的实体类不用必须继承自某一个特定的基类,这说你可以让它继承自任何一种对象。所有用LINQ to SQL设计器生成的类都被定义为了"局部类“,这意味着你可以选择向局部类中添加代码和添加附加的属性,方法和事件。

Unlike the DataSet/TableAdapter feature provided in VS 2005, when using the LINQ to SQL designer you do not have to specify the SQL queries to use when creating your data model and access layer. 

和VS2005中提供了DataSet/TableAdapter不同,当用LINQ to SQL设计器时,你不必在生成数据模型和访问层时指明SQL查询语句。

Instead, you focus on defining your entity classes, how they map to/from the database, and the relationships between them.  The LINQ to SQL OR/M implementation will then take care of generating the appropriate SQL execution logic for you at runtime when you interact and use the data entities.  You can use LINQ query syntax to expressively indicate how to query your data model in a strongly typed way.

相反,你只需要将注意力集中到你的实体类,以及它们如何映射到/从 数据库,和它们之间的关系上。LINQ to SQL OR/M将会注意如何在你和和该类交互并使用数据实体时生成合适的SQL执行语句逻辑。你可以用强类型的方法来通过LINQ 查询语法来表达如何从数据模型中查询。

Creating Entity Classes From a Database

从数据库中生成实体类

If you already have a database schema defined, you can use it to quickly create LINQ to SQL entity classes modeled off of it.

如果你已经有了一个已定义好的数据库模型,你可以用它很快地来生成一个脱离于它的LINQ to SQL实体类。

The easiest way to accomplish this is to open up a database in the Server Explorer within Visual Studio, select the Tables and Views you want to model in it, and drag/drop them onto the LINQ to SQL designer surface:

实现这个的最简单的方法就是在Vs的Server Explorer窗口中打开一个数据库,选择你想生成模型的数据表和视图,然后将它们通过拖放的方式放到LINQ to SQL设计器上:

 

When you add the above 2 tables (Categories and Products) and 1 view (Invoices)  from the "Northwind" database onto the LINQ to SQL designer surface, you'll automatically have the following three entity classes created for you based on the database schema:

当从"Northwind"数据库中向LINQ to 设计器面板上添加两个如上的如时,你会看到如下的基于你的数据结构的三个实体类:


 

 

Using the data model classes defined above, I can now run all of the code samples (expect the SPROC one) described in Part 1 of this LINQ to SQL series.  I don't need to add any additional code or configuration in order to enable these query, insert, update, delete, and server-side paging scenarios. 

通过上边定义的的数据模型,我现在就可以执行在本系列的第一部分(Part 1)中提及的所有事例代码(除了存储过程那个)。我不用添加任何的其他附加代码或者设置,直接就可以运行那些查询,插入,更新,删除和服务器端分页的代码。



Naming and Pluralization

命名及复数

One of the things you'll notice when using the LINQ to SQL designer is that it automatically "pluralizes" the various table and column names when it creates entity classes based on your database schema.  For example: the "Products" table in our example above resulted in a "Product" class, and the "Categories" table resulted in a "Category" class.  This class naming helps make your models consistent with the .NET naming conventions, and I usually find having the designer fix these up for me really convenient (especially when adding lots of tables to your model).  

有一件事你可能已经注意到了,当用LINQ to SQL设计器生成基于你的数据库结构的实体类时,它会自动地将表和列名变为“复数”。例如:在事例中的“Products"产生了一个"Product"类,"Categories"表产生了一个"Category"类。这些类命名方法使你的模型和.NET 的命名相一致,并且我经常发现让设计器为我完成命名非常地方便(尤其当向模型中添加许多的表时)。

If you don't like the name of a class or property that the designer generates, though, you can always override it and change it to any name you want.  You can do this either by editing the entity/property name in-line within the designer or by modifying it via the property grid:

如果你不喜欢设计器生成的类的名称或属性名称,你也可以重写它将它重命名为你想要的名字。你可以通过如下方式进行重命名:或者在设计器中的已声明的名字内部来修改或者通过属性列来修改:

 

The ability to have entity/property/association names be different from your database schema ends up being very useful in a number of cases.  In particular:

这种将你数据库中结构中的实体/属性/关系的方法命名为不同的名的方法在许多情况下非常有用,特别是:

1) When your backend database table/column schema names change.  Because your entity models can have different names from the backend schema, you can decide to just update your mapping rules and not update your application or query code to use the new table/column name.

1)当原来的数据库中的表/列名变化时。因为你的实体模型根据后端的不同的名字,你可以用新的表/列名称,只更新你映射的规则而不更新你的应用程序或者查询代码。

2) When you have database schema names that aren't very "clean".  For example, rather than use "au_lname" and "au_fname" for the property names on an entity class, you can just name them to "LastName" and "FirstName" on your entity class and develop against that instead (without having to rename the column names in the database).

2)当你的数据库模型的名字不是十分“清晰”时。例如,在开发时,你可以将名字命名为"LastName"和"FirstName",而不用为一个实体类的属性命名为“au_lnname"和"au_fname"(不用重命名数据库中的列名)。


Relationship Associations
关系组织

When you drag objects from the server explorer onto the LINQ to SQL designer, Visual Studio will inspect the primary key/foreign key relationships of the objects, and based on them automatically create default "relationship associations" between the different entity classes it creates.  For example, when I added both the Products and Categories tables from Northwind onto my LINQ to SQL designer you can see that a one to many relationship between the two is inferred (this is denoted by the arrow in the designer):

当你从Server Explorer中拖对象到LINQ to SQL设计器中时,VS将会检测对象的主/外键,并且通过它们在它生成的不同的实体类中生成“关系组织”。例如,当我从Northwind数据库中添加Product和Categories两个表到LINQ to SQL设计器时,你将看到在二者之后将生成一对多的关系(在设计器中通过箭头来表示)

The above association will cause cause the Product entity class to have a "Category" property that developers can use to access the Category entity for a given Product.  It will also cause the Category class to have a "Products" collection that enables developers to retrieve all products within that Category.

上面的关系将会使得Product实体类有一个"Category"属性,开发者可以通过此属性来获取到属性此类别的所有产品集合。

If you don't like how the designer has modeled or named an association, you can always override it.  Just click on the association arrow within the designer and access its properties via the property grid to rename, delete or modify it.

如果你不喜欢设计器为你生成或者命名一个关系,你也可以重写它。只要单击设计器中的关系箭头,通过属性器找到它的属性来重命名,删除或修改它。


Delay/Lazy Loading
延迟/惰加载

LINQ to SQL enables developers to specify whether the properties on entities should be prefetched or delay/lazy-loaded on first access.  You can customize the default pre-fetch/delay-load rules for entity properties by selecting any entity property or association in the designer, and then within the property-grid set the "Delay Loaded" property to true or false.

LINQ to SQL可以让开发者指定在初次调用时就加载还是延迟/惰加载。你可通过在设计器中选择一个实体属性或方法,指定是预先加载还是延迟加载,然后在属性窗口中将“Delay Loaded"属性设置为true或false。

For a simple example of when I'd want to-do this, consider the "Category" entity class we modeled above.  The categories table inside "Northwind" has a "Picture" column which stores a (potentially large) binary image of each category, and I only want to retrieve the binary image from the database when I'm actually using it (and not when doing a simply query just to list the category names in a list).

举个简单的例子,当我想做这些的时,来看一下我们刚才生成的"Category"实体类,Northwind中的categories表有一个"Picture"字段,该字段存储了一个每一个类别的图片(非常大),并且我只想在我用它的时候再从数据库中检索该二进制的图片字段(不是我在做一个列出所有列表的简单查询时就检索出来)

I could configure the Picture property to be delay loaded by selecting it within the LINQ to SQL designer and by settings its Delay Loaded value in the property grid:

我可以通过在LINQ to SQL设计器中选择Picture属性,将它的Delay Loaded的值设置为true。

Note: In addition to configuring the default pre-fetch/delay load semantics on entities, you can also override them via code when you perform LINQ queries on the entity class (I'll show how to-do this in the next blog post in this series).

注意:除了在实体上设置默认的pre-fetch/delay加载之外,你也可以在对实体类写LINQ 查询时通过代码控制它。



Using Stored Procedures

使用存储过程

LINQ to SQL allows you to optionally model stored procedures as methods on your DataContext class.  For example, assume we've defined the simple SPROC below to retrieve product information based on a categoryID:

LINQ to SQL允许你选择地将存储过程作为你的DataContext类的一个方法。例如,假如我们已经定义了一个如下的存储过程,该存储过程通过categoryID来产品的信息:

I can use the server explorer within Visual Studio to drag/drop the SPROC onto the LINQ to SQL designer surface in order to add a strongly-typed method that will invoke the SPROC.  If I drop the SPROC on top of the "Product" entity in the designer, the LINQ to
SQL designer will declare the SPROC to return an IEnumerable<Product> result:

为了添加一个强类型的方法来执行存储过程,我可以用在Vs中的server explorer来拖/放存储过程到LINQ to SQL设计器上。如果我将存储过程放到设计器中的"Product"上,LINQ to SQL设计器将会声明一个返回IEnumberable<Product>结果集的方法。


I can then use either LINQ Query Syntax (which will generate an adhoc SQL query) or alternatively invoke the SPROC method added above to retrieve product entities from the database:

然后我可以或者使用LINQ的查询语法(它会生成adhoc SQL 查询)或者利用执行以上添加的存储过程方法来从数据库中产品实体:

Using SPROCs to Update/Delete/Insert Data

使用存储过程来更新/删除/插入数据


By default LINQ to SQL will automatically create the appropriate SQL expressions for you when you insert/update/delete entities.  For example, if you wrote the LINQ to SQL code below to update some values on a "Product" entity instance:

默认情况下,在你插入/更新/删除实体时,LINQ to SQL将会自动的为你生成合适的SQL语句。例如,当你写了如下的更新"Product"实体对象的一些值的LINQ to SQL代码时:

By default LINQ to SQL would create and execute the appropriate "UPDATE" statement for you when you submitted the changes (I'll cover this more in a later blog post on updates).

默认情况下,当你提交更新时,LINQ to SQL将会生成并执行合适的"Update"语句声明。(我将会有下几篇帖子中来讲解“更新”这一部分)。


You can also optionally define and use custom INSERT, UPDATE, DELETE sprocs instead.  To configure these, just click on an entity class in the LINQ to SQL designer and within its property-grid click the "..." button on the Delete/Insert/Update values, and pick a particular SPROC you've defined instead:
你也选择定义自己的Insert,Update,Delete的存储过程。设置自定义的存储过程的话,在LINQ to SQL设计器的实体类上单击,在属性窗口中点击Delete/Insert/Update之后的“...”按钮,选择你已经定义好的存储过程来替换默认的:

What is nice about changing the above setting is that it is done purely at the mapping layer of LINQ to SQL - which means the update code I showed earlier continues to work with no modifications required.  This avoids developers using a LINQ to SQL data model from having to change code even if they later decide to put in a custom SPROC optimization later.

更改以上设置的好处是,这在LINQ to SQL的映射层很完全地做完了,这意味着我前其展示的更新的代码将会在不更改的情况下继续正常使用。这避免了开发者在使用LINQ to SQL模型时,更改代码来优化程序,即便要添加一个自定义的存储过程。



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提供了一种优秀的,清晰的方法来为你的应用程序制作数据层。一旦你定义了数据模型,你可以对它进行有效的查询,插入,更新和删除。


Using the built-in LINQ to SQL designer within Visual Studio and Visual Web Developer Express you can create and manage your data models for LINQ to SQL extremely fast.  The LINQ to SQL designer also provides a lot of flexibility that enables you to customize the default behavior and override/extend the system to meet your specific needs.

通过VS和Visual Web Developer Express内置的LINQ to SQL设计器,你可以快速地生成数据模型,尤其生成LINQ to SQL模型。LINQ to SQL设计器还提供了许多你能自定义的默认行为进行灵活扩展来满足你的特殊的需求。



In upcoming posts I'll be using the data model we created above to drill into querying, inserts, updates and deletes further.  In the update, insert and delete posts I'll also discuss how to add custom business/data validation logic to the entities we designed above to perform additional validation logic.

在接下来的帖子中,我将会用上边生成的数据模型来进一步的进行演练查询,插入,更新和删除。在更新,插入和删除帖子中我将再次讨论如何向我们设计的实体中添加自定义的业务/数据验证逻辑。

Mike Taulty also has a number of great LINQ to SQL videos that I recommend checking out here.  These provide a great way to learn by watching someone walkthrough using LINQ to SQL in action.

Mike Taulty 还有许多好的Linq to SQL 视频,我已经在这里进行了推荐here。这将为一个初学者提供一个非常方便的道路。

Hope this helps,

Scott

posted on 2007-11-17 20:07  是谁啊?  阅读(4844)  评论(6编辑  收藏  举报