#眉標=LINQ #副標=剖析LINQ運作機制(5) #大標=實做完整功能的單檔編輯應用程式 #作者=文圖/黃忠成 ============= 程式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 SingleEdit { public partial class Form1 : Form { NorthwindDataContext _context = new NorthwindDataContext(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { bindingSource1.DataSource = _context.Customers; } } } ================ ============= 程式2 private void toolStripButton1_Click(object sender, EventArgs e) { bindingSource1.EndEdit(); _context.SubmitChanges(); }================ ============= 程式3 private void toolStripButton2_Click(object sender, EventArgs e) { bindingSource1.CancelEdit(); }================ ============= 程式4 private void toolStripButton2_Click(object sender, EventArgs e) { bindingSource1.CancelEdit();    _context.Refresh( System.Data.Linq.RefreshMode.OverwriteCurrentValues, bindingSource1.Current); bindingSource1.ResetCurrentItem(); }================ ============= 程式5 using System.Reflection; .................... private void toolStripButton2_Click(object sender, EventArgs e) { bindingSource1.CancelEdit(); object original = ((ITable)bindingSource1.DataSource).GetOriginalEntityState(             bindingSource1.Current); object current = bindingSource1.Current; foreach (PropertyInfo pi in current.GetType().GetProperties()) pi.SetValue(current, pi.GetValue(original,null),null); bindingSource1.ResetCurrentItem(); }================ ==小技巧 =========== 若以SQL Server Profiler觀察,會發現每次SubmitChanges函式呼叫時,LINQ To SQL都會送出一段指令,要避免這種無謂的網路通訊,可以藉助DataContext的GetChangeSet函式,判斷其Deletes、Inserts、Updates、三個屬性的Count屬性,再決定是否呼叫SubmitChanges函式。 ================