#眉標=LINQ #副標=剖析LINQ運作機制(4) #大標=迎接ORM的時代 ─ LINQ To SQL #作者=文圖/黃忠成 ============= 程式1 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace LinqToSqlAtWinForm { public partial class Form1 : Form { private DataClasses1DataContext db = new DataClasses1DataContext(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { dataGridView1.DataSource = from s1 in db.Customers where s1.CustomerID == "VINET" select s1; } } }================ ============= 程式2 private void button1_Click(object sender, EventArgs e) { db.SubmitChanges(); }================ ============= 程式3 [Column(Storage="_CompanyName", DbType="NVarChar(40) NOT NULL", CanBeNull=false)] public string CompanyName { get {     return this._CompanyName; } set { if ((this._CompanyName != value)) { this.OnCompanyNameChanging(value); this.SendPropertyChanging(); this._CompanyName = value; this.SendPropertyChanged("CompanyName"); this.OnCompanyNameChanged(); } } }================ ============= 程式4 (CustomerExt.cs) using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LinqToSqlAtWinForm { partial class Customer { partial void OnValidate() { if (CustomerID.Length < 3) throw new Exception("Customer ID length can't less then 3"); } } }================ ============= 程式5 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LinqToSqlAtWinForm { partial class Customer { partial void OnCustomerIDChanging(string value) { if (value.Length < 3) throw new Exception("Customer ID length can't less then 3"); } } }================ ============= 程式6 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace LINQToSQLAtWinForm2 { public partial class Form1 : Form { private DataClasses1DataContext db = new DataClasses1DataContext(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { dataGridView1.DataSource = from s1 in db.Orders select s1; } private void dataGridView1_SelectionChanged(object sender, EventArgs e) { Order dataItem = dataGridView1.CurrentRow.DataBoundItem as Order; dataItem.Order_Detail.Load(); dataGridView2.DataSource = dataItem.Order_Detail; } } }================