2010-09-23 80 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

相关问题