0

我正在研究 Entity Framework 4.1 。此处使用 AddObject() 将控件添加到数据库中并使用 SaveChange() 方法保存该控件。

但是,一旦我删除了添加的控件并尝试再次添加相同的控件,我就会一次又一次地收到此错误(存储更新、插入或删除语句影响了意外的行数(0)。实体可能已被修改或删除,因为实体是已加载。刷新 ObjectStateManager 条目。)但无法添加它。一旦我关闭我的应用程序然后尝试添加然后我就可以添加该控件。

我试图在这里和那里搜索很多问题,但找不到解决方案。因为我是实体框架领域的新手。

4

1 回答 1

0

As in this scenario i was calling SaveChange() method of Entity framework object context after every operation like add, delete and modification. But i was getting exception back to back.It got solved by By calling method like this public void Save(object entity) { using (var transaction = Connection.BeginTransaction()) {

            try
            {
                SaveChanges();
                transaction.Commit();
             }
             catch (OptimisticConcurrencyException)
             {
                 if (ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Deleted || ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Modified)
                        this.Refresh(RefreshMode.StoreWins, entity);
                  else if (ObjectStateManager.GetObjectStateEntry(entity).State == EntityState.Added)
                        Detach(entity);
                  AcceptAllChanges(); 
                  transaction.Commit();
              }

        }
    }
于 2012-12-15T11:18:57.560 回答