2009-02-09 56 views
15

我有一個程序,我需要保存一個實體對象。問題是我不知道這個實體是否附加到我的datacontext或不。爲了解決這個問題我使用下面的代碼:檢測實體是否附加到datacontext

try 
{ 
    db.ClientUsers.Attach(clientUser); 
    db.Refresh(RefreshMode.KeepCurrentValues, clientUser); 
} 
catch { } 

db.SubmitChanges(); 

我在尋找一個更好的方法,如果實體是屬於一個框架,並且還測試如果一個實體連接到特定的上下文來檢測。

回答

22

我想知道...... GetOriginalEntityState返回一個非連接的對象是什麼?即使它拋出一個異常,這很可能會比刷新快...

(更新) - 測試顯示它返回null:

 Customer cust = new Customer(); 
     Customer orig = ctx.Customers.GetOriginalEntityState(cust); 
     Assert.IsNull(orig); 

     cust = new Customer(); 
     ctx.Customers.Attach(cust); 
     orig = ctx.Customers.GetOriginalEntityState(cust); 
     Assert.IsNotNull(orig); 
     Assert.AreNotSame(cust,orig); 

因此,也許使用GetOriginalEntityState和檢查null返回值...

+3

這太棒了!爲DataContext創建一個漂亮的「IsAttached(Of T)」擴展方法。 – rossisdead 2010-04-16 17:34:50

相關問題