tags:

views:

671

answers:

3

I have a base recipe class and I am using a datacontext. I overrode the insert method for the recipe in the datacontext and am trying to insert into its children. Nomatter what I do I cannot get the child to insert.Currently, just the recipe inserts and nothing happens with the child.

    partial void InsertRecipe(Recipe instance)
    {
        // set up the arrays
        for (int x = 0; x < instance.PlainIngredients.Count; ++x)
        {
            instance.TextIngredients.Add(new TextIngredient()
            {
                StepNumber = x + 1,
                Text = instance.PlainIngredients[x]
            });
        }

        this.ExecuteDynamicInsert(instance);
    }

I have tried everything I can think of. I even instantiated another datacontext in the method and after the instance came back from ExecuteDynamicInsert with the id, tried to add it, and I get timeout errors.

+1  A: 

The InsertX/UpdateX/DeleteX methods are called after LINQ to SQL has determined which objects will be included in SubmitChanges.

You would have been getting a timeout using two DataContext most likely because of locking issues between the two transactions.

I can't clearly make out what you are trying to achieve here - normally LINQ to SQL manages the child relationships itself - what are PlainIngredients and TextIngredients?

DamienG
A: 

PlainIngredients is a string list of ingredients. It is exposed to the users. Whenever anyone adds ingredients, they are just adding it to this list. This list, however, is not stored in the database. When someone inserts a recipe, I want to take each PlainIngredient string in the list, and place it into a separate table row (TextIngredients table). That is the loop that you see. Is there an event that fires when you are adding a recipe, but before it is submitted to the db?

Matthew Kruskamp
+1  A: 

I figured it out. Override SubmitChanges in the DataContext, and find all of the inserts and updates that are recipes. Run the algorithm to add children there.

    public override void SubmitChanges(
        System.Data.Linq.ConflictMode failureMode)
    {
        ChangeSet changes = this.GetChangeSet();

        var recipeInserts = (from r in changes.Inserts
                       where (r as Recipe) != null
                       select r as Recipe).ToList<Recipe>();

        var recipeUpdates = (from r in changes.Updates
                       where (r as Recipe) != null
                       select r as Recipe).ToList<Recipe>();

        ConvertTextData(recipeInserts);
        ConvertTextData(recipeUpdates);

        base.SubmitChanges(failureMode);
    }
Matthew Kruskamp