Print Page | Close Window

Deleting entities

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=2419
Printed Date: 30-Aug-2025 at 12:44am


Topic: Deleting entities
Posted By: sky40627
Subject: Deleting entities
Date Posted: 05-Jan-2011 at 4:34am
Hi,
 
I am trying to do the following
 
var q = _manager.UnpaidInvoices;
foreach (var unpaidInvoice in q)
  {
      unpaidInvoice.EntityAspect.Delete();
  }
_manager.SaveChanges();
 
when looking in the database the entities are deleted
 
but somehow they are still present in the entitymanager
 
because when i start adding the new entities i get an error saying that an entity with this key already exists.
 
foreach (var item in list)
{
   UnpaidInvoice ui = UnpaidInvoice.Create(_manager, item.Id);
}
_manager.SaveChanges();
 
also is it necessary to do the savechanges after the delete of the entities ?
 
here under is the create method
 
public static UnpaidInvoice Create(EntityManager pEntityManager, string pId)
        {
            UnpaidInvoice upi = pEntityManager.CreateEntity<UnpaidInvoice>();
            upi.Id = pId;
            upi.EntityAspect.AddToManager();
            return upi;
        }
 
what am I doing wrong here? Why isn't the cache update after the delete ?



Replies:
Posted By: sbelini
Date Posted: 05-Jan-2011 at 6:34pm
Hi sky40627,
 
I was not able to reproduce the issue here.
Here is my test case:
 
[TestMethod]
public void TestDelete() {
  var mgr = new IdeaBladeTest1Entities();
 
  var empToDelete = mgr.Employees.First();
  var id = empToDelete.Id;
  empToDelete.EntityAspect.Delete();
  mgr.SaveChanges(); // Persisting the delete
 
  var newEmp = mgr.CreateEntity<Employee>();
  newEmp.Id = id;
  newEmp.FirstName = "Joe" + DateTime.Now.Ticks.ToString();
  newEmp.LastName = "Doe";
  mgr.AddEntity(newEmp);
  mgr.SaveChanges(); // Storing the new employee
}
 
However, if you comment out the first mgr.SaveChanges() in the code then you will get the exception you described.
In That case, it happens because even though you have deleted the entity, you have not yet persisted the changes by calling mgr.SaveChanges.
 
Can you please provide a solution reproducing the issue?
 
On a second note, why are you trying to recycle PKs? Ideally, a primary key should be unique to one entity (regardless of if the entity has been deleted)



Print Page | Close Window