程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> NBearV3 Step by Step教程——ORM篇

NBearV3 Step by Step教程——ORM篇

編輯:關於.NET

版本

1.7 [2006-1-16]

簡介

本教程演示如何基於NBearV3的ORM模塊開發一個Web應用程序的全過程。本教程演示的實體關系包括:繼承、1對1關聯、1對多關聯,多對多關聯。同時,本教程還演示如何設計實體屬性為nullable類型或符合類型。

注:所謂nullable類型主要是針對之類型而言的,.Net2.0位所有的值類型支持nullable,設為nullable的值類型,允許是null的,這樣,就可以映射數據庫中的null;而符合類型指這個屬性是一個復合類型,但是,保存到數據庫的時候,整個復合類型序列化後保存為一個數據表的字段的值。

目標

通過本教程,讀者應能夠掌握使用NBearV3的ORM模塊進行應用程序設計的基本過程,以及開發過程中,NBearV3提供的相關工具的使用方法。

代碼

本教程演示創建的所有工程和代碼,包含於可以從sf.net下載的NBearV3最新源碼zip包中的tutorials\ORM_Tutorial目錄中。因此,在使用本教程的過程中如有任何疑問,可以直接參考這些代碼。

時間

<45分鐘。

正文

Step 1 下載NBearV3最新版本

1.1訪問http://sf.net/projects/nbear,下載NBearV3的最新版本到本地目錄。

1.2 將下載的zip文件解壓至C:\,您將看到,加壓後的NBearV3目錄中包括:dist、doc、cases、src等目錄。其中,在本教程中將會使用的是dist目錄,該目錄下包含所有release編譯版本的dll和exe。

Step 2 創建應用程序解決方案

2.1 打開VS2005開發環境,新建一個空的解決方案sln。

2.2 向sln中添加兩個新建的C#類庫工程,兩個類庫工程的名稱分別為EntityDesigns和Entities,刪除IDE自動創建的Class1.cs文件。

2.3 向sln中新建一個名叫website的ASP.NET Web應用程序,為website添加一個Web.config文件。

Step 3 設計實體及關系

3.1 在2.2創建的EntityDesigns工程中,新建一個名為ClassDiagram.cd的類圖文件。注:如果您的IDE不支持類圖設計,或者您更習慣寫代碼,您也可以參照下面的步驟直接創建代碼。

3.2為EntityDesigns工程添加到dist目錄下的NBear.Common.Design.dll的引用。因為下面的每一個設計實體接口必須繼承自NBear.Common.Design.Entity這個接口。在Entities工程中創建一個名為UserName的struct包含FirstName和LastName兩個string類型的Field。同時在Entities工程中創建一個名為UserStatus的枚舉類型,包含兩個枚舉選項:Availale和Deleted。注:這兩個類型將用於後面的設計實體的設計。之所以這兩個類型定義在Entities工程中而不是EntityDesigns工程中是,最終,所有生成的實體將放在Entities工程,且Entities工程最後對EntityDesigns工程是沒有依賴關系的。

3.3 雙擊ClassDiagram.cd打開設計界面,您現在就可以設計實體了。注意,所有的設計實體必須是接口。為了使用3.2創建的類型,需要讓Entit一Designs工程引用Entities工程。

3.4 向類圖中添加一個User接口,繼承自NBear.Common.Design.Entity。添加屬性ID,Name,Status和Birthday。類型分別為Guid、UserName、UserStatus和DateTime?。注意,這裡的Name和Status的類型為3.2創建的自定義符合類型UserName和枚舉類型UserStatus。而Birthday屬性的類型為一個Nullable類型的DateTime?。注意DateTime後面的問號,表示這個類型實際是一個Nullable<DateTime>,也就是說,Birthday類型如果不賦初始值的話,它的值為null。

3.5 向類圖中再添加一個LocalUser接口,繼承自NBear.Common.Design.Entity。添加屬性LoginName和Password。類型都為string。

3.6 從工具欄添加繼承線條,讓LocalUser繼承User。

3.7 向類圖中添加一個UserProfile接口,繼承自NBear.Common.Design.Entity。添加屬性ID,UserID和ProfileContent。類型分別為Guid,Guid和string。注:這裡的ProfileContent僅僅象征型的代表profile數據,用於演示1對1關聯,實際的項目中可能會有更多屬性。

3.8 從工具欄添加關聯線條,讓User包含一個名叫Profile的UserProfile類型的屬性。這樣我們就1對1關聯了User和UserProfile實體。注:如果操作圖形設計界面覺得麻煩,也可以切換到源代碼界面,直接編碼。

3.9 向類圖中添加一個LocalUserPhone接口,繼承自NBear.Common.Design.Entity。添加屬性ID,UserID,Description,Number。類型分別為Guid,Guid,string和string。

3.10 從工具欄添加關聯線條,讓LocalUser包含一個名叫Phones的類型為LocalUserPhone[]的數組類型的屬性。這樣我們就1對多關聯了LocalUser和UserPhone。

3.11 向類圖添加一個Group接口,繼承自NBear.Common.Design.Entity。添加屬性ID,Name。類型分別為Guid和string。

3.12 從工具欄添加關聯線條,讓User包含一個名叫Groups的類型為Group[]的數組類型的屬性。注意,這裡我們要實現的是多對多關聯,所以下面我們還要建一個UserGroup關聯實體來連接這個多對多關系。

3.13 向類圖添加一個UserGroup接口,繼承自NBear.Common.Design.Entity。添加屬性UserID和GroupID。類型都是Guid。

設計完的實體關系圖,應該類似下面這樣:

Step 4 設置設計實體元數據

4.1 切換到源代碼視圖。首先,我們要為除了關聯實體UserGroup之外(對於關聯實體,凡是標記為RelationKey的屬性,會被自動認為是復合主鍵)的所有設計實體的主鍵設置PrimaryKey這個Attribute,可以為多主鍵實體的每個主鍵添加該屬性。如果不正確設置主鍵,代碼生成工具將不能正確生成數據庫創建腳本。例如,對於User實體的ID屬性,設置後的代碼象下面這樣:

[PrimaryKey]
Guid ID
{
get;
set;
}

注:大家可能有疑問,為什麼這裡主鍵ID能不能是int,並且是自增長的只讀屬性呢?答案是完全可以的,完全可以設置某個ID屬性為下面這樣,無需額外設置,它將映射到一個自增長只讀的int類型的數據庫字段:

[PrimaryKey]
int ID
{
get;
}
4.2 在後面的步驟生成實體對應的數據庫創建腳本時,對於數值類型,nullable類型和枚舉類型,NBear能夠自動將他們對應到數據庫的對應類型,但是,對string類型,一般需要指定其映射到數據庫時的具體類型和長度。當然,也可以不指定,如果不指定,則string類型默認被映射為nvarchar(127)。例如,對於UserProfile的ProfileContent屬性,我們添加下面的Attribute,設置其映射到數據庫的類型為ntext:

[SqlType("ntext")]
string ProfileContent
{
get;
set;
}

又如,對於LocalUserPhone的Number屬性,我們添加下面的Attribute,設置其映射到數據庫的類型為nvarchar(20):

[SqlType("nvarchar(20)")]
string Number
{
get;
set;
}

4.2 對於User的Name這個UserName類型的復合類型,我們也需要設置其SqlType,一般設為ntext,因為,默認情況下復合類型被序列化為XML,並保存於對應的數據庫字段。另外,復合類型還必須使用CompoundUnit這個Attribute標記,所以User的Name屬性需要被設置成下面這樣:

[CompoundUnit]
[SqlType("ntext")]
UserName Name
{
get;
set;
}

注:繼承關系不需要特別設置,NBear可以識別接口的自然繼承關系,但是,注意,不要讓一個設計實體接口繼承超過一個基類接口,否則,NBear將不能識別這種繼承關系。換句話說,NBear不支持多根繼承。之所以有這個限制是因為,後面,所有這些設計實體接口會被自動生成為class形式的實體代碼,而class是不支持多根繼承的。

4.3 對於User和UserProfile的1對1關聯,我們需要為User接口的Profile屬性設置下面的Attributes(這些Attribues都包含於NBear.Common.Design中,因此,需要注意在代碼中using NBear.Common.Design):

[FkQuery("UserID", Contained = true, LazyLoad = false)]
UserProfile Profile
{
get;
set;
}

其中,FkQuery代表這個屬性是一個1對1外鍵關聯,參數UserID表示,在UserProfile實體中,UserID為對應的外鍵。LazyLoad=false容易理解,表示這個屬性不是知道訪問才載入數據的,而是,在實例化User對象的時候,就自動載入Profile屬性的數據。當然,如果需要,也可以將LazyLoad設為true。另外,可以像下面這樣設置UserProfile的UserID屬性為外鍵,則生成的數據庫腳本將包含外鍵引用完整性檢測:

[FriendKey(typeof(User))]
Guid UserID
{
get;
set;
}

4.4 對於LocalUser和LocalUserPhone的1對多關聯,我們需要為LocalUser接口的Phones屬性設置下面對的Attributes:

[FkQuery("UserID", Contained=true, LazyLoad=true)]
LocalUserPhone[] Phones
{
get;
set;
}

這裡LocalUser和LocalUserPhones是1對多外鍵關聯。Contained=true表示Phones跟隨LocalUser級聯更新。

4.5 對於User和Group的多對多關聯,我們為User.Groups屬性設置下面的Attributes:

[ManyToManyQuery(typeof(UserGroup), OrderBy="{Name} DESC", LazyLoad=true)]
Group[] Groups
{
get;
set;
}

我們可以看到,和前面的1對1和1對多關聯相比,多對多關聯的主要區別是必須設置ManyToManyQuery的構造函數參數,指定關聯實體為UserGroup。這裡的OrderBy並不是必須的,如果不指定,則載入的Group按默認規則排序。

4.6 另外,還需要設置UserGroup這個關聯實體的屬性如何與User和Group的屬性進行關聯。我們需要對UserGroup這個實體關聯接口及它的屬性設定下面的Attributes:

[Relation]
public interface UserGroup : NBear.Common.Design.Entity
{
[RelationKey(typeof(User))]
Guid UserID
{
get;
set;
}

[RelationKey(typeof(Group))]
Guid GroupID
{
get;
set;
}
}

注意,首先,關聯實體必須使用Relation這個Attribute修飾。其次,每一個關聯屬性的用於關聯的屬性,必須使用RelationKey這個Attribute修飾。RelationKey的唯一參數指定這個屬性關聯到哪一個實體。例如,這裡,UserGroup的UserID屬性關聯到User實體;而GroupID屬性則關聯到Group實體。

4.7 對於LocalUser的Password,我們可以添加NotNull和SerializationIgnore這兩個Attribute,顯式地設置其對應字段為非空,並且,保證其不會被包含在默認的XML序列化中。設置到設計實體的SerializationIgnore,會在最終生成的實體中用XmlIngore標識。

[SqlType("nvarchar(50)")]
[NotNull]
[SerializationIgnore]
string Password
{
get;
set;
}

Step 5 從實體設計代碼生成實體代碼、實體配置文件和數據庫生成腳本

5.1 至此,所有的實體的設計就完畢了。編譯EntityDesigns工程。

5.2 運行dist目錄中的NBear.Tools.EntityDesignToEntity.exe工具,載入EntityDesigns工程編譯生成的EntityDesigns.dll。

5.3 點擊Generate Entities按鈕,將生成的代碼保存到Entities工程中的一個名叫Entities.cs的新代碼文件。並為Entities工程添加到dist\NBear.Common.dll的引用。

5.4 點擊Generate Configuration按鈕,將生成的代碼保存到website工程下的名為EntityConfig.xml的新文件中。

5.5 點擊Generate DB Script按鈕,將生成的代碼保存到website工程下的名為db.sql的新文件,可以在某個新建的SQL Server數據庫中執行這些腳本,創建對應於所有實體的數據庫腳本。

Step 6 使用實體及NBear.Data.Gateway訪問數據庫

6.1 現在我們就可以使用前面生成的實體了。我們先要讓website工程引用Entities工程,以及dist/NBear.Data.dll。

6.2 我們還需要設置website的Web.config文件,添加一個entityConfig section以包含EntityConfig.xml這個實體配置文件,並設置數據庫連接字串。下面是設置完的Web.config,注意,粗體的部分都是我們添加的代碼(注意,這裡的connectionstring連接到SQL Server數據庫的tempdb數據庫,我們需要對tempdb數據庫執行5.5生成的數據庫創建腳本,另外也注意修改數據庫登錄密碼。):

<?xml version="1.0"?>
<configuration>
<configSections>
<section name="entityConfig" type="NBear.Common.EntityConfigurationSection, NBear.Common" />
</configSections>
<entityConfig>
<includes>
<add key="Sample Entity Config" value="~/EntityConfig.xml" />
</includes>
</entityConfig>
<appSettings/>
<connectionStrings>
<add name="DbName" connectionString="Server=(local);Database=tempdb;Uid=sa;Pwd=sa" providerName="NBear.Data.SqlServer.SqlDbProvider"/>
</connectionStrings>
<system.web>
<compilation debug="false" />
<authentication mode="Windows" /
</system.web>
</configuration>

6.3 好了,現在,我們就可以隨心所欲的訪問數據庫了。將下面的代碼添加至website工程的Default.aspx.cs文件(您也可以直接打開tutorials\ ORM_Tutorial\website目錄下的Default.aspx.cs,從那裡復制代碼)。這些代碼演示了一個非常典型的創建和級聯更新有復雜關系的實體的過程,並伴有詳細解說。關於Gateway支持的更多方法的介紹,可以參考doc目錄下的SDK類庫文檔。

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Entities;
using NBear.Common;
using NBear.Data;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//init a Gateway, the param "tempdb" is the connectionstring name set in Web.config
Gateway gateway = new Gateway("tempdb");  //youcan also use gateway = Gateway.Default, which maps to the last connectionstring in Web.config

create & save a LocalUser#region create & save a LocalUser

WriteLine("Create a new local user and set property values.");
LocalUser newLocalUser = new LocalUser();
newLocalUser.ID = Guid.NewGuid();
newLocalUser.Password = "12345";
//by default, newUser.Birthday equals null, because it is DateTime? type, which means when saved in database, its value is dbnull.
//newUser.Birthday = null

//if you want to set a compoundunit property like User.Name, you must create the compoundunit type first, and then assign it to the property
//you should not assign value directly to the compoundunit property's property like "newUser.Name.FirstName = XXX",
//or, a compile-time warning will be thrown
WriteLine("Create & set the user name.");
UserName newUserName = new UserName();
newUserName.FirstName = "teddy";
newUserName.LastName = "ma";
newLocalUser.Name = newUserName; //must create the compoundunit type first, and then assign it to the property

newLocalUser.Status = UserStatus.Available;

//create and assign the 1 to 1 related Profile property
UserProfile newUserProfile = new UserProfile();
newUserProfile.ID = Guid.NewGuid(); //create it first
newUserProfile.UserID = newLocalUser.ID;
newUserProfile.ProfileContent = "some sample content";
newLocalUser.Profile = newUserProfile;  //assign it to the property

//create two phones and assign the 1 to many related Phones property
WriteLine("Create & set the local user phones");
LocalUserPhone[] newPhones = new LocalUserPhone[2];
newPhones[0] = new LocalUserPhone();  //create first phone
newPhones[0].Description = "home";
newPhones[0].ID = Guid.NewGuid();
newPhones[0].UserID = newLocalUser.ID;
newPhones[0].Number = "111";
newPhones[1] = new LocalUserPhone();  //create second phone
newPhones[1].Description = "work";
newPhones[1].ID = Guid.NewGuid();
newPhones[1].UserID = newLocalUser.ID;
newPhones[1].Number = "222";
LocalUserPhoneArrayList newPhoneList = new LocalUserPhoneArrayList();
newPhoneList.AddRange(newPhones);
newLocalUser.Phones = newPhoneList;  //assign it to the property

//create a group and assign it to the Groups property
WriteLine("Create & set the user groups.");
Group newGroup = new Group();
newGroup.ID = Guid.NewGuid();
newGroup.Name = "new group";
GroupArrayList groupList = new GroupArrayList();
groupList.Add(newGroup);
newLocalUser.Groups = groupList; //another way to add a item to array property

//save newLocalUser
WriteLine("Save the new local user.");
gateway.Save<LocalUser>(newLocalUser); //do you know what is happening when saving the new local user?

#endregion

Check saving result#region Check saving result

WriteLine("");
WriteLine("After we saved the local user.");

//let find the saved local user by id first
LocalUser theSavedLocalUser = gateway.Find<LocalUser>(newLocalUser.ID);
if (theSavedLocalUser != null) WriteLine("We found the saved local user itself.");

//a local user is also a user, right? then could we find the saved local user as a user?
User theSavedLocalUserAsUser = gateway.Find<User>(newLocalUser.ID);
if (theSavedLocalUser != null) WriteLine("We found the saved local user itself as a user.");

//was the 1 to 1 related user profile saved on the new local user's saving?
if (theSavedLocalUser.Profile != null && theSavedLocalUser.Profile.ID == newLocalUser.Profile.ID) WriteLine("We found the 1 to 1 related user profile of the saved local user was also saved.");

//were the 1 to many related local user phones saved on the new local user's saving?
if (theSavedLocalUser.Phones != null && theSavedLocalUser.Phones[0].ID == newLocalUser.Phones[0].ID && theSavedLocalUser.Phones[1].ID == newLocalUser.Phones[1].ID)
WriteLine("We found the 1 to many related local user phones of the saved local user were also saved.");

//were the many to many related user group and the usergroup relation entity saved on the new local user's saving?
if (theSavedLocalUser.Groups != null && theSavedLocalUser.Groups.Count > 0 && theSavedLocalUser.Groups[0].ID == newLocalUser.Groups[0].ID)
WriteLine("We found the many to many related local user group of the saved local user was also saved.");  //is the line really executed?? it should not.
else
WriteLine("Oh! many to many related local user group of the saved local user was NOT saved!! Do you know why? - It is NOT because it is many to many related while profile and phones are 1 to 1 or 1 to many. It is not because you are not Teddy, either. :) It IS because in the entity design of User, the Groups property is NOT marked with the [Contained] attribute.");

//save an uncontained property's value
WriteLine("To save an uncontained property value, such as user's Groups, you have to manually do this.");
WriteLine("Firstly, you should save the group it self.");
gateway.Save<Group>(newGroup);
WriteLine("Furthermore, you have to create & save a usergroup relation entity manually. Let's do it.");
UserGroup newUserGroup = new UserGroup();  //create the new usergroup relation entity instance
newUserGroup.UserID = theSavedLocalUser.ID;
newUserGroup.GroupID = newGroup.ID;
gateway.Save<UserGroup>(newUserGroup); //do the saving
WriteLine("Let's find the saved local user again. Was the group saved this time?");
theSavedLocalUser = gateway.Find<LocalUser>(newLocalUser.ID);
if (theSavedLocalUser.Groups != null && theSavedLocalUser.Groups.Count > 0 && theSavedLocalUser.Groups[0].ID == newLocalUser.Groups[0].ID)
WriteLine("Yes, conguratulation! This time, we found the many to many related local user group of the saved local user was finally saved.");

//to see the saved user name details
WriteLine("Do you want to know the saved user name's details, which is a compoundunit property? Ok, show you what you want, in fact, it is serialized as xml by the NBear.Common.SerializationManager class, looks like:");
WriteLine(SerializationManager.Serialize(theSavedLocalUser.Name));
WriteLine("Ok, I heard you considering whether you can save it into some other format because you do not want it to be XML? You do have chance to control this!!");
WriteLine("What youshould do is easily register a custom serialize/deserialize delegate method pair.");
SerializationManager.RegisterSerializeHandler(typeof(UserName), new SerializationManager.TypeSerializeHandler(CustomSerializeUserName), new SerializationManager.TypeDeserializeHandler(CustomDeserializeUserName));
WriteLine("Let's save the user name again.");
theSavedLocalUser.Name = newUserName;
gateway.Save<LocalUser>(theSavedLocalUser);
WriteLine("What does the details of the user name now become? It becomes:");
WriteLine(SerializationManager.Serialize(theSavedLocalUser.Name));
WriteLine("Cool!~~ Right? But remember, in real project, you must register the custom serialize/deserialize delegate method pair at application started up. For example, in Application_Start().");
WriteLine("Thank you so much for having completed this tutorial. You can look up the appendixes, for more information about the usage of the Gateway.");
WriteLine("See you later!");
WriteLine("Warm regards,");
WriteLine("Teddy " + DateTime.Now.ToShortDateString());
SerializationManager.UnregisterSerializeHandler(typeof(UserName));

#endregion
}

private void WriteLine(string str)
{
Response.Write(Server.HtmlEncode(str) + "<br /><br />");
}

private string CustomSerializeUserName(object name)
{
UserName userName = (UserName)name;
return userName.FirstName + "," + userName.LastName;
}

private object CustomDeserializeUserName(string data)
{
string[] splittedData = data.Split(',');
UserName userName = new UserName();
userName.FirstName = splittedData[0];
userName.LastName = splittedData[1];
return userName;
}
}

6.4

運行以上代碼,您將得到類似到下面的結果:

Create a new local user and set property values.
Create & set the user name.
Create & set the local user phones
Create & set the user groups.
Save the new local user.

After we saved the local user.
We found the saved local user itself.
We found the saved local user itself as a user.
We found the 1 to 1 related user profile of the saved local user was also saved.
Oh! many to many related local user group of the saved local user was NOT saved!! Do you know why? - It is NOT because it is many to many related while profile and phones are 1 to 1 or 1 to many. It is not because your are not Teddy, either. :) It IS because in the entity design of User, the Groups property is NOT marked with the [Contained] attribute.
To save an uncontained property value, such as user's Groups, you have to manually do this.
Firstly, you should save the group it self.
Furthermore, you have to create & save a usergroup relation entity manually. Let's do it.
Let's find the saved local user again. Was the group saved this time?
Yes, conguratulation! This time, we found the many to many related local user group of the saved local user was finally saved.
Do you want to know the saved user name's details, which is a compoundunit property? Ok, show you what you want, in fact, it is serialized as xml by the NBear.Common.SerializationManager class, looks like:
<?xml version="1.0" encoding="utf-16"?> <UserName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <FirstName>teddy</FirstName> <LastName>ma</LastName> </UserName>
Ok, I heard you considering whether you can save it into some other format because you do not want it to be XML? You do have chance to control this!!
What youshould do is easily register a custom serialize/deserialize delegate method pair.
Let's save the user name again.
What does the details of the user name now become? It becomes:
teddy,ma
Cool!~~ Right? But remember, in real project, you must register the custom serialize/deserialize delegate method pair at application started up. For example, in Application_Start().
Thank you so much for having completed this tutorial. You can look up the appendixes, for more information about the usage of the Gateway.
See you later!
Warm regards,
Teddy 2006-11-3
正文結束。

附錄

1 關於ConnectionStrings的設置

這裡定義了五個ConnectionString,分別對應MS Access、MS SQL Server、SQL Server 2005、MySql和Oracle數據庫。

<connectionStrings>
<add name="TestAccessDb" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Teddy\NBear\skeleton\Simple\website\App_Data\TestAccessDb.mdb" providerName="NBear.Data.MsAccess.AccessDbProvider"/>
<add name="Northwind" connectionString="Server=(local);Database=Northwind;Uid=sa;Pwd=sa" providerName="NBear.Data.SqlServer.SqlDbProvider"/>
<add name="Northwind2" connectionString="Server=(local);Database=Northwind;Uid=sa;Pwd=sa" providerName="NBear.Data.SqlServer9.SqlDbProvider9"/>
<add name="MySql" connectionString="Dsn=mysqltest;database=test;option=3;server=localhost;uid=root;password=sa" providerName="NBear.Data.MySql.MySqlDbProvider"/>
<add name="Oracle" connectionString="Data Source=localhost;User ID=system;Password=sa;Unicode=True" providerName="NBear.Data.Oracle.OracleDbProvider"/>
</connectionStrings>

2 關於Gateway的初始化和連接多數據庫

除了使用Gateway.Default之外,還可以下面兩種方式實例化Gateway:

1)使用配置文件中的ConnectionString的name屬性對應的名稱來初始化Gateway。例如,

public static Gateway Northwind = new Gateway("Northwind");
public static Gateway TestAccessDb = new Gateway("TestAccessDb");

我們可以像這樣實例化多個Gateway對應不同的ConnectionString。

2)如果您不將ConnectionString定義於應用程序的配置文件中,那麼,就需要直接提供ConnectionString來初始化了。下面是幾個典型的初始化示例:

Gateway TestDbAccess = new Gateway(DatabaseType.MsAccess, @"C:\Teddy\NBear\skeleton\Simple\website\App_Data\TestAccessDb.mdb");
Gateway Northwind = new Gateway(DatabaseType.SqlServer, @"Server=(local);Database=Northwind;Uid=sa;Pwd=sa");
Gateway Northwind2 = new Gateway(DatabaseType.SqlServer9, @"Server=(local)\SQLEXPRESS;Database=Northwind;Uid=sa;Pwd=sa");
Gateway.Default = new Gateway(DatabaseType.MySql, "Dsn=mysqltest;database=test;option=3;server=localhost;uid=root;password=sa");
Gateway.Default = new Gateway(DatabaseType.Oracle, "Data Source=localhost;User ID=system;Password=sa;Unicode=True");

注意以上的代碼使用了Gateway構造函數的另一個重載版本,接受一個DatabaseType參數和一個ConnectionString。這五行示例分別實例化了對應於MSAccess、MS SQL Server 2000、MS SQL Server 2005、MySql和Oracle的數據庫的Gateway。

//本文結束。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved