LinqToSql - Save just the last change - Part 2
בהמשך
לפוסט הקודם שבו כתבתי איך לעשות עידכון רק לשינוי האחרון,
דברתי עם אדר לגבי המוטיבציה לעשות את זה, מדוע שנרצה לעדכן רק את האחרון, והגענו להסכמה שיש כאן משהו מוזר,
כי ב Ado הישן והטוב כשרצינו לעשות upadte היינו יכולים לשלוח מערך של DataRow, ולעדכן רק חלק מהנתונים, אז מדוע כשאנחנו מתקדמים ל LinkToSql אנחנו הולכים אחורה מבחינה פונקציונליות ?
בכל מקרה במדה ואנחנו מוכנים לעשות undo לכל השינוים האחרים מלבד האחרון, נוכל להשתמש בפתרון, מהפוסט הקודם,
אבל במדה ולא נרצה לעשות undo, יניב חדד הציע לי, לייצר DataContex חדש, להעביר אליו את השינוי האחרון, ולעשות עליו SubmitChanges,
אז ניסיתי לממש אותו, ומסתבר שזה לא כל כך פשוט, אמנם זה לא הרבה שורות קוד,
אבל לא ברור לי מדוע בקשה כל כך פשוטה, צריכה להיות עם קוד מסובך ולא יפה,
בכל מקרה, הנה הפיתרון: (הדוגמא הייתה על Northwind) (ותסלחו לי על האנגלית המזויעה שלי)
1 public static void UpdateLastChanges()
2 {
3 // Get all changes from the data contex
4 ChangeSet cs = ndc.GetChangeSet();
5
6 // Take the last update
7 Order lastChanget = (Order)cs.Updates[1];
8
9 // Create a new data contex
10 NorthwindDataContext newContex = new NorthwindDataContext();
11
12 // Find the same order in the new data contex by the OrderId
13 Order original = newContex.Orders.Single(
14 item => item.OrderID == lastChanget.OrderID);
15
16 // Get the type of Order
17 // it's for runnig with reflaction and change the properties
18 Type orderType = original.GetType();
19
20 // Get the all modufied members in the order
21 ModifiedMemberInfo[] memberInfos =
22 ndc.Orders.GetModifiedMembers(lastChanget);
23
24 foreach (ModifiedMemberInfo memberInfo in memberInfos)
25 {
26 // Get the PropertyInfo by the name of the change member
27 PropertyInfo originalMemberInfo =
28 orderType.GetProperty(memberInfo.Member.Name);
29
30 // And cahnge the order in the new data contex
31 originalMemberInfo.SetValue(original, memberInfo.CurrentValue, null);
32 }
33
34 // Submit Changes of the new data conex
35 newContex.SubmitChanges();
36
37 // Let's know the old data contex
38 // taht the clast change is saved in the database
39 ndc.Refresh(RefreshMode.OverwriteCurrentValues, cs.Updates[1]);
40 }
השורה האחרונה היא מאוד חשובה,
אנחנו צריכים לעדכן את ה dataContex שאנחנו עובדים איתו, שהשינוי כבר התבצע.