2009-04-15 50 views
2

以下簡化代碼無法正常工作(因爲它設置檢索對象引用參數)的對象,但它顯示了我想要做的更新在LINQ2SQL記錄與RECORDTYPE

public bool updateEvent(clubEvent newEvent) 
    { 
     TNightCon tCon = new TNightCon(); 
     clubEvent cEv = (from cEvent in tCon.clubEvents 
         where cEvent.EventID == newEvent.EventID 
         select cEvent).First(); 

     // Won't work, but do I have to set all the fields manually? 
     cEv = newEvent; 
     tCon.SubmitChanges(); 
     return true; 
    } 

回答

2

您不需要檢索當前對象來執行您需要執行的操作。如果ID相同,則只需將新對象附加到上下文中即可。這個技巧就變成了讓Linq2SQL將對象視爲「髒」。 Timothy Khouri有a blog post,詳細介紹了在上下文中使用Refresh方法的有用技巧。這是它的樣子。

public bool updateEvent(clubEvent newEvent) 
    { 
     tCon.clubEvents.Attach(newEvent); 
     tCon.Refresh(RefreshMode.KeepCurrentValues, settings) 
     tCon.SubmitChanges(); 
     return true; 
    } 
3

或者,或者,

tCon.ClubEvents.DeleteOnSubmit(cEv); 
    tCon.CLubEvents.InsertOnSubmit(newEvent); 
    tCon.SubmitChanges(); 
+0

這雖然有多安全?刪除和創建記錄之間是否存在查詢將嘗試查找記錄但不存在的機會?或者SQL服務器在處理新請求之前完成這些類型的操作? – Tarks 2009-04-16 00:03:29