Deleting an object that is a member of a collection

2 posts, 0 answers
  1. Peter
    Peter avatar
    23 posts
    Member since:
    Sep 2008

    Posted 15 Jul 2009 Link to this post

    The way OpenAccess manages collections is causing me some difficulty when I delete an object that's part of a collection using ObjectScope.Remove - the deleted instance is not removed from any tracked collection that's already been loaded so subsequent accesses of that collection lead to exceptions.

    Here's a simple example.  I have two classes, A and B with a one-to-many relationship, ie A has a field: IList<B> RelatedBs and B has a field A RelatedA.  If I have instances a1 and b1, b2 and b3 such that a1.RelatedBs yields [b1, b2, b3] and execute the code roughly:
        for each (var b in a1.RelatedBs) Trace.WriteLine(b.ToString());
        for each (var b in a1.RelatedBs) Trace.WriteLine(b.ToString());
    then the 2nd pass through the collection fails because it tries to use a deleted object, throwing:
      Telerik.OpenAccess.Exceptions.InvalidOperationException : It is not allowed to read or to write an instance marked for deletion.

    I can make this work by setting the reference field on the B to be null, but that feels clumsy.  Does anyone know a way to get OpenAccess to do this automatically?
    [I can also make it work by removing the instance from the collection, but that's not viable in my real world scenarios - it could cause large collections to be fetched when they were not needed.]

    Best regards, Peter
  2. Thomas
    Thomas avatar
    588 posts

    Posted 17 Jul 2009 Link to this post

    Hi Peter,

    OpenAccess will not do such an automatic removal from _all_ containing collections. However, with managed inverse collections and the [Depend] attribute it is possible to just remove an instance from _one_ collections and get that instance automatically marked for deletion. With inverse collections one is also able to just nullify the inverse reference and remove it from the scope, but this will not remove that instance from other already loaded collections (no depend then!).
    This gets philosophical easily: Its is trivial to know what I reference, but it is hard to know what is referencing me.

    Sincerely yours,
    the Telerik team

    Instantly find answers to your questions on the new Telerik Support Portal.
    Check out the tips for optimizing your support resource searches.
  3. DevCraft banner
Back to Top