views:

21

answers:

0

I have an app that uses EF POCO for accessing data. Everything works great, yet there is one problem with unit testing. Imagine two related classes:

public class Brother
{
    public virtual Sister Sister { get; set; }
}

public class Sister
{
    public virtual ICollection<Brother> Brothers { get; set; }
}

The problem here is that if we have an instance of Brother with the related entity set to some other entity then ObjectContext.DeleteObject() throws the common "Colletion was modified" ONLY in the unit test project (unit testing is done by the build-in VS framework). The problem does not occur in the project itself. Example code that fails:

public void TheTestThatFails()
{
    Brother bro = MyContextInst.CreateObject<Brother>();
    Sister sis = MyContextInst.CreateObject<Sister>();
    sis.Brothers.Add(bro);
    MyContextInst.AddToBrothers(bro);
    MyContextInst.AddToSisters(sis);
    MyContextInst.SaveChanges();

    // The following will throw a "Collection was modified" ex
    MyContextInst.DeleteObject(sis);

    // Yet if we disconnect the object graph everything is fine
    // The following will work fine:
    bro.Sister = null;
    MyContextInst.DeleteObject(sis);
}

Where does this come from? As far as I can tell the environment is exactly the same (I have come to actually making unit tests and the project use same DB, same user, same everything).

Why cannot EF handle the object graph in the unit test project? Why does it ONLY fail in unit testing?.. I am completely puzzled.

  • Note how there is no user-code mentioning collections - the exception must come from within the EF code?..

EDIT: After investigation: * this happens if the collection is at least 1-many (edited the code) * it seems that the more safe way of cascade deleting would be to remove the children objects first (Brothers), then clear the collection of the parent (Sister) and only after that delete it from the context as there is something inside EF itself that tries to connect the entities and removes stuff from something else. The question is solved for me at the moment.