。具有相同键的An对象已存在于ObjectStateManagerObjectStateManager中,无法使用相同的键跟踪多个对象

时间:2010-09-23 20:09:16

标签: asp.net linq entity-framework

我正在尝试简单地更新实体对象并且我得到了这个错误..所有关于错误的谷歌搜索都把我带到复杂的解释......任何人都可以简单地说出来吗?

我正在使用这个简单的教程

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 个答案:

答案 0 :(得分: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正在咆哮,因为您不能有两行具有相同的值表中的主键值。