閱讀Stephens' C#教材第三十八章筆記 介紹LINQ to SQL的操作。
Chapter 38 LINQ to SQL
本章將介紹LINQ的其中一個主題:LINQ to SQL,讓你能使用類似LINQ to Objects的方式對SQL SERVER資料庫進行操作。詳細的資料請參考微軟網頁
LINQto SQL操作的基本步驟
- 連線到資料庫
- 建立LINQ to SQL類別
- 撰寫程式
- 使用LINQ查詢
連線到資料庫的步驟跟第三十五章介紹的類似,但是在第四個步驟資料來源的類型,要選擇Microsoft SQL Server,如下圖
在連線資料庫之前,請先執行作者提供的BuildCustomerDatabase程式,這隻程式會根據你所提供的Server位置建立一個CustomerDatabase資料庫。
如果你的資料庫是安裝SQL Server Express Edition的版本,記得要加上\SQLEXPRESS,因為這個版本的資料庫實體會需要多這串字才能正確指到。
然後依照第三十五章介紹的步驟,建立CustomerDatabaseConnectionString連線字串,然後我們可以在伺服器總管看見資料連接的畫面如下
接下來的任務是建立LINQ to SQL類別,首先在方案總管中,新增項目,選擇新增LINQ to SQL類別,檔名為CustomerClasses.dbml。
開啟CustomerClasses.dbml,將資料表Customer以拖曳方式拉入,會自動產生Customer資料類別,裡面每一個欄位在方案總管的屬性視窗都可以進行屬性的操作。
其中比較關鍵的屬性有:Name(名稱), Nullable(可為Null), Server Data Type(伺服器資料型別), Source(來源)
當設定完成,儲存確認後,方案會產生一個CustomerClassesDataContext類別,對應到SQL Server中的Customer資料表。
MakeCustomerData程式示範使用CustomerClassesDataContext類別新增資料,程式碼如下:
// Add a new Customers record.
private void addButton_Click(object sender, EventArgs e)
{
// Get the database.
using (CustomerClassesDataContext db =
new CustomerClassesDataContext())
{
// Make a new Customer object.
Customers cust = new Customers();
cust.FirstName = firstNameTextBox.Text;
cust.LastName = lastNameTextBox.Text;
cust.Balance = decimal.Parse(balanceTextBox.Text);
cust.DueDate = DateTime.Parse(dueDateTextBox.Text);
// Add it to the table.
db.Customers.InsertOnSubmit(cust);
// Submit the changes.
db.SubmitChanges();
}
// Prepare to add the next customer.
firstNameTextBox.Clear();
lastNameTextBox.Clear();
balanceTextBox.Clear();
dueDateTextBox.Clear();
firstNameTextBox.Focus();
}
在上一章曾以FindCustomers程式示範使用LINQ查詢,其中一段的查詢如下:
// Display customers with negative balances.
var negativeQuery =
from Customer cust in customers
where cust.Balance < 0
//orderby cust.Balance ascending, cust.FirstName
select cust;
negativeListBox.DataSource = negativeQuery.ToArray();
如果在LINQ to SQL則會改成如下:
// Display customers with negative balances.
var negativeQuery =
from Customers cust in db.Customers
where cust.Balance < 0
//orderby cust.Balance ascending, cust.FirstName
select String.Format("{0} {1}\t{2:C}\t{3:d}",
cust.FirstName, cust.LastName,
cust.Balance, cust.DueDate);
negativeListBox.DataSource = negativeQuery.ToArray();
LINQ to Objects與LINQ to SQL的查詢運作大部分相同,有一個很不同的地方如下:
首先是LINQ to SQL支援nullable型態。null的意涵在資料庫中代表未知,例如:血型人人都有,如果不知道血型又不能用空白代替,空白代表沒有,
就會填入null,表示還不知道,沒有資料。如果有一個nullable的int欄位表示除了可放入整數,還可以放入null,表示尚不清楚是何整數?
但是nullable型態只支援數值型態,因為參考型態的變數如String等,早就支援null。
要宣告一個變數支援nullable型態,在宣告時使用?,例如:
int? numCourses = null;
LinqToSqlAccess程式中示範使用Access的Customer.mdb當作資料庫,使用LINQ to SQL的方式操作