1. 建立一個Windows表單專案。
2. 加入LINQ to SQL類別,命為Northwind.dbml。
3. 開啟Server Explorer工具,連接到Northwind資料庫,然後將Region資料表拖曳到LINQ to SQL設計畫面左方的區塊之中。
4. 在伺服器總管,Northwind.dbml檔案方案滑鼠右鍵,選取「View Code」,Visual Studio 2008將會建立一個Northwind.cs檔案,其中包含一個NorthwindDataContext部分類別的定義。
5. 在NorthwindDataContext類別的大括號中,輸入partial一個字,Visual Studio會自動列出所有可以改寫的部分方法,包含InsertRegion、OnCreated、DeleteRegion與UpdateRegion方法,選取任一方法後,按Tab鍵,Visual Studio會自動產生方法的函式定義。
6. 修改Northwind.cs
1 using System.Data;
2 using System.Data.SqlClient;3 namespace CustomLTSQL {
4 partial class NorthwindDataContext {5 partial void InsertRegion(Region instance) {
6 SqlConnection cn = new SqlConnection(this.Connection.ConnectionString);7 SqlCommand cmd = new SqlCommand("Insert into Region values(@RegionID,@RegionDescription)", cn);
8 cmd.Parameters.AddWithValue("@RegionID", instance.RegionID);9 cmd.Parameters.AddWithValue("@RegionDescription", instance.RegionDescription);
10 cn.Open();11 cmd.ExecuteNonQuery();
12 cn.Close();13 }
14 partial void DeleteRegion(Region instance) {15 SqlConnection cn = new SqlConnection(this.Connection.ConnectionString);
16 SqlCommand cmd = new SqlCommand("delete from Region where RegionID=@RegionID", cn);17 cmd.Parameters.AddWithValue("@RegionID", instance.RegionID);
18 cn.Open();19 cmd.ExecuteNonQuery();
20 cn.Close();21 }
22 partial void UpdateRegion(Region instance) {23 SqlConnection cn = new SqlConnection(this.Connection.ConnectionString);
24 SqlCommand cmd = new SqlCommand("update Region set RegionDescription=@RegionDescription where RegionID=@RegionID", cn);25 cmd.Parameters.AddWithValue("@RegionID", instance.RegionID);
26 cmd.Parameters.AddWithValue("@RegionDescription", instance.RegionDescription);27 cn.Open();
28 cmd.ExecuteNonQuery();29 cn.Close();
30 }31 }
32 }7. 在表單中加入三個Button,分別為Insert、Update、Delete,然後在其Click事件處理常式加入以下程式,分別進行新增、刪除、修改資料的動作:
1 using System;2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;5 using System.Drawing;
6 using System.Linq;7 using System.Text;
8 using System.Windows.Forms;9 namespace CustomLTSQL {
10 public partial class Form1 : Form {11 public Form1() {
12 InitializeComponent();13 }
14 private void button1_Click(object sender, EventArgs e) {15 NorthwindDataContext db = new NorthwindDataContext();
16 Region r = new Region();17 r.RegionID = 999;
18 r.RegionDescription = "new Region";19 db.Regions.InsertOnSubmit(r);
20 db.SubmitChanges();21 }
22 private void button2_Click(object sender, EventArgs e) {23 NorthwindDataContext db = new NorthwindDataContext();
24 Region reg = (from r in db.Regions25 where r.RegionID==999
26 select r).Single<Region>();27 db.Regions.DeleteOnSubmit(reg);
28 db.SubmitChanges();29 }
30 private void button3_Click(object sender, EventArgs e) {31 NorthwindDataContext db = new NorthwindDataContext();
32 Region reg = (from r in db.Regions33 where r.RegionID == 999
34 select r).Single<Region>();35 reg.RegionDescription = "Super new Region";
36 db.SubmitChanges();37 }
38 }39 }
沒有留言:
張貼留言