ScottGu’s 部落格之--LINQ to SQL 第二部分-定義資料模型類--LINQ to SQL (Part 2 – Defining our Data Model C

來源:互聯網
上載者:User
更為簡潔的版本將會發布在部落格堂(除去了英文的版本),希望本文能對您有所協助!

允許轉載,麻煩註明出處: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 1或Visual 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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.