我正在尝试简单地更新实体对象并且我得到了这个错误..所有关于错误的谷歌搜索都把我带到复杂的解释......任何人都可以简单地说出来吗?
我正在使用这个简单的教程
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;
答案 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正在咆哮,因为您不能有两行具有相同的值表中的主键值。