2009-04-15 57 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