2010-09-23 76 views
0

我試圖簡單地更新實體對象,我得到這個錯誤..所有使用googling我犯的錯誤帶我到複雜解釋......任何人都可以簡單地說出來嗎?。在ObjectStateManagerObjectStateManager中已存在的對象具有相同的鍵已經存在不能使用相同的密鑰追蹤多個對象

我工作的這個簡單的教程

http://aspalliance.com/1919_ASPNET_40_and_the_Entity_Framework_4__Part_2_Perform_CRUD_Operations_Using_the_Entity_Framework_4.5

else 
        { 
         //UPDATE 
         int iFid = Int32.Parse(fid.First().fid.ToString()); 
         oFinancial.fid = iFid; 
         oFinancial.mainqtr = currentQuarter; 
         oFinancial.mainyear = currentYear; 
         oFinancial.qtr = Int32.Parse(currentQuarter); 
         oFinancial.year = Int32.Parse(currentYear); 
         oFinancial.updatedate = DateTime.Now; 
         // ObjectStateEntry ose = null; 
         // if (!dc.ObjectStateManager.TryGetObjectStateEntry(oFinancial.EntityKey, out ose)) 
         // {      
         dc.financials.Attach(oFinancial); 
         // } 

         dc.ObjectStateManager.ChangeObjectState(oFinancial, System.Data.EntityState.Modified); 
        } 

        dc.SaveChanges(); 

這裏是什麼,是在我使用簡單的代碼越往上讓我的主鍵值..可能是一個更好的方式但它的工作原理。

var fid = from x in dc.financials 
        where iPhaseID == x.phaseid && 
         strTaskID == x.ftaskid && 
         strFundType == x.fundtype && 
         iCurrentQuarter == x.qtr && 
         iCurrentYear == x.year 
        select x; 

回答

1

如果oFinancial對象從dc來了,你永遠不分離手動,然後沒有理由調用Attach方法或亂用ObjectStateManager。只要dc知道對象(它除外),然後ObjectStateManager將跟蹤您所做的任何更改並在您致電dc.SaveChanges()時相應地更新它們。

編輯:這裏是你貼什麼重構版本,希望它有助於:

else { 
    //UPDATE 
    // as long as oFinancial was never detatched after you retrieved 
    // it from the "dc", then you don't have to re-attach it. And 
    // you should never need to manipulate the primary key, unless it's 
    // not generated by the database, and you don't already have another 
    // object in the "dc" with the same primary key value. 

    int iFid = Int32.Parse(fid.First().fid.ToString()); 
    oFinancial.fid = iFid; 
    oFinancial.mainqtr = currentQuarter; 
    oFinancial.mainyear = currentYear; 
    oFinancial.qtr = Int32.Parse(currentQuarter 
    oFinancial.year = Int32.Parse(currentYear); 
    oFinancial.updatedate = DateTime.Now; 
} 
dc.SaveChanges(); 

還有一兩件事:如果iFid是主鍵,那麼你不應該惹它,只要這個對象來自dc。我相信問題在於您將主鍵(iFid)重置爲dc中另一個對象的相同值,並且EF4正在吠叫,因爲在表中不能有兩個具有相同主鍵值的行。

+0

是fid是主鍵..但我需要獲得EF的行的主鍵,以便它更新它我會猜測..生病明天看看它 – punkouter 2010-09-23 21:13:13

+0

yup。這似乎解決了它..我正在把東西我甚至不明白......也許有一個更優雅的方式來獲得主鍵雖然? – punkouter 2010-09-23 21:21:49

+0

如果您有財務記錄,您應該已經知道它是什麼。你可以查詢該對象的直流,然後更新任何屬性,然後調用SaveChanges(),並且一切都自動發生:) – 2010-09-23 21:31:23

相關問題