views:

31

answers:

1

Hi all,

I am trying to persist the collection of child elements, the solution works but I would like to ask the more experienced people if the approach is the right one?

public bool InsertNewActionHistory(ActionHistory actionHistory)
    {
        bool result = false;

        using (TransactionScope transactionScope = new TransactionScope())
        {
            this.ActionHistories.AddObject(actionHistory);

            if (actionHistory is ActionUpdate)
            {
                foreach (ActionUpdateDetail updateDetail in ((ActionUpdate)actionHistory).ActionUpdateDetails)
                {
                    ActionUpdateDetails.AddObject(updateDetail);
                }
            }

            this.CommitChanges();
            transactionScope.Complete();
            result = true;
        }

        return result;
    }
A: 

If ActionUpdateDetail is related to ActionUpdate via a navigation property, then you don't need 3/4 of the code. You could just do:

public bool InsertNewActionHistory(ActionHistory actionHistory)
{
    this.ActionHistories.AddObject(actionHistory);
    return true;
}

Navigation properties ensure that related objects are added together.

Note that this can be harder if you use POCO proxies or pure POCOs. Beginners with the EF should probably stick with DB-first or model-first until you learn the rules of the road.

Craig Stuntz
Hi Craig, it is a POCO scenario, DB First approach. Beleive it or not I have managed to sort it out without the unneseccary code. I have no idea where the problem was. At first attempt the child, i.e. navigation properties did not persis at all?! Then I decided to try with the transaction scope and have ended up with the presented code. Once I removed, gradually, all the unnecessary code it started working as it should. The method CommitChanges has a single call to context's SaveChanges method. It could be that the transaction scope, or something else, had blocked saving the children.
bignermo
I will try to go back and reproduce the ackward behavior and will share it if I succeed. Anyway, thanks a lot for your help :)
bignermo