locked
Delete - Submit - Insert -> Cannot add an entity that already exists

    Question

  • HI,

     

       Why does the following fail with 'Cannot add an entity that already exists' ?

     

    Code Snippet

    User u = User[0];

    db.Users.DeleteOnSubmit(users[0]);

    db.SubmitChanges();

    db.Users.InsertOnSubmit(u);

     

     

        Examining the database after the SubmitChanges confirms that the user has in fact been deleted, so why can't I add the user back?

     

    --

    Dan

    Wednesday, July 02, 2008 3:42 PM

Answers

  • The DataContext remembers the objects even after they are deleted. They are considered 'dead' objects and cannot be used again.  You can, however, create a new object instance with the same info and use that.

    Wednesday, July 02, 2008 5:01 PM

All replies

  • The DataContext remembers the objects even after they are deleted. They are considered 'dead' objects and cannot be used again.  You can, however, create a new object instance with the same info and use that.

    Wednesday, July 02, 2008 5:01 PM
  •  Matt Warren - MSFT wrote:

    The DataContext remembers the objects even after they are deleted. They are considered 'dead' objects and cannot be used again.  You can, however, create a new object instance with the same info and use that.

     

    Out of interest, why are they still referenced, and how are they ever collected by the GC ?

     

    --

    Dan

    Wednesday, July 02, 2008 8:06 PM
  •  Matt Warren - MSFT wrote:

    The DataContext remembers the objects even after they are deleted. They are considered 'dead' objects and cannot be used again.  You can, however, create a new object instance with the same info and use that.

     

    So, yep, you're right they hang around forever, and can't be collected, so it's trivial to write a program that runs out of memory :-(

     

    Doesn't seem right to me, why is it hanging onto them, they've been deleted ....

     

    Code Snippet

    [TestMethod]

    public void TestLinqSQL()

    {

    DataClasses1DataContext db = new DataClasses1DataContext();

    var q = from p in db.Users where p.Name == "Dan" select p;

    for (int i = 0; i < 1000000; i++)

    {

    if (q.Count() == 0)

    {

    for (int j = 0; j < 100000; j++)

    {

    User u = new User();

    u.ID = Guid.NewGuid();

    u.Name = "Dan";

    db.Users.InsertOnSubmit(u);

    }

    db.SubmitChanges();

    }

    db.Users.DeleteAllOnSubmit(q);

    db.SubmitChanges();

    }

    }

     

     

    --

    Dan

Thursday, July 03, 2008 7:27 PM