#眉標=LINQ #副標=剖析LINQ運作機制(7) #大標= LINQ To SQL與N-Tier應用程式 #作者=文/圖 黃忠成 #引言= ============= 程式1 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace WCFDataService { [ServiceContract] public interface IDataService { [OperationContract] Customer[] GetAllData(); } public class DataService : IDataService { #region IDataService Members public Customer[] GetAllData() { NorthwindDataContext context = new NorthwindDataContext(); return (from s1 in context.Customers select s1).ToArray(); } #endregion } } ================ ============= 程式2 private void Window_Loaded(object sender, RoutedEventArgs e) { var result = (from s1 in client.GetAllData() orderby s1.CustomerID select s1).ToList(); bindingList = new BindingList( (IList)result); DataContext = bindingList; view = CollectionViewSource.GetDefaultView(DataContext); } ================ ============= 程式3 using System; using System.ComponentModel; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace WpfDataConsumer { public class TrackingContext { ……………. public void Initialize(IList objs) { _states.Clear(); _update_original = typeof(TUpdate).GetProperty("Original"); _update_current = typeof(TUpdate).GetProperty("Current"); _update_state = typeof(TUpdate).GetProperty("State"); foreach (T item in objs) { object updateData = Activator.CreateInstance(typeof(TUpdate), false); _update_original.SetValue(updateData, CloneObject(item),null); _update_current.SetValue(updateData, item, null); _update_state.SetValue(updateData, WpfDataConsumer.DataService.UpdateState.UnChanged, null); ((INotifyPropertyChanged)item).PropertyChanged += new PropertyChangedEventHandler(TrackingContext_PropertyChanged); _states.Add(item, (TUpdate)updateData); } }     void TrackingContext_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (_states.ContainsKey((T)sender)) { object o = _states[(T)sender]; DataService.UpdateState state =             (DataService.UpdateState)_update_state.GetValue(o, null); if (state == WpfDataConsumer.DataService.UpdateState.Insert) return; _update_state.SetValue(o,             WpfDataConsumer.DataService.UpdateState.Update, null); } } } } ================ ============= 程式4 public void UpdateData(UpdateData[] updatedData) { NorthwindDataContext context = new NorthwindDataContext(); try { foreach (UpdateData item in updatedData) { if (item.State == UpdateState.Insert) context.Customers.InsertOnSubmit((Customer)item.Current); } foreach (UpdateData item in updatedData) { if (item.State == UpdateState.Update) context.Customers.Attach((Customer)item.Current, (Customer)item.Original); } foreach (UpdateData item in updatedData) { if (item.State == UpdateState.Delete) { context.Customers.Attach((Customer)item.Current); context.Customers.DeleteOnSubmit((Customer)item.Current); } } context.SubmitChanges(); } finally { context.Dispose(); } } =============