none
Weird behaviour with table once removed data being deleted - presumably cascade delete... but parent element not deleted RRS feed

  • Question

  • Can't think of a better way to title this, or even possibly explain it, but here goes...

    I have these entities

    Product, Package,  PackagedProduct,  Orders, OrderItem

    OrderItems (lineitems) are for Products and have a value

    Orders choose a PackageType, which then determines things.

    Problem I'm seeing is when I remote OrderItems (which have a relationship to Product via ProductId) then "PackagedProducts" are being deleted on "SaveChanges()"

    I BELIEVE this is EF trying to be helpful... but I have no evidence.

    My theory is that when I .Remove(theOrderItem), its removing the related PRODUCTS from the chain, and trying to delete it, it can't delete the Product?, but there aren't any rules (in the model) that say you can't remove a PackagedProduct, and so it deletes it from the context and then from the DB when it hits it...

    Anyway my question is if this IS the case, how to confirm this, and what to do about it?

    There is not a DIRECT relationship between Order/OrderItem and PackagedProduct - PackagedProduct just shows how many items fit in a package and what it costs...

    the relationships are:

    between "order > package type" and "orderitem > productid"

    between "packagedProduct >packagetype & productid"

    I could probably stop bashing my head against the keyboard and just make each item directly related to the packagedproduct as this doesn't seem to cause any problems, but you can't mix package types in the one order... so that be "wrong".

    Friday, August 3, 2012 6:00 AM

Answers

  • Hmm... loathe to answer my own question so quickly, but... I finally found the culprit.

    We're using DynamicProxy and so (believe it or not) it looks like a simple "toList()" wasn't as "detached" as we thought.

    There was a routine that was just doing a read operation but then "ToList(); // realise the data and tweak it" and perhaps this works (as expected) when you don't have dynamicproxies or whatever off... as the original coder anticipated?! (not sure)

    Anyway, the tweak looks like it just checks values are there to construct an "in memory" version of things.

    but the in memory operation was replacing the packagedproducts with another "ToList()" set of data that (likely) didn't make EF a happy camper, so it thinks things were deleted.

    I've added "AsNoTracking()" to the "readonly" list and that seems to have stopped the weird behaviour, so I think I will run a few more checks and call that one solved... 

    • Marked as answer by noJedi Friday, August 3, 2012 6:43 AM
    Friday, August 3, 2012 6:43 AM