tags:

views:

72

answers:

1

I have three tables: Context, Component and ComponentContext. The ComponentContext table links the Component and Context into an N:M relationship.

I'm working on a C# project which imports a bunch of data into these tables. It uses an Entity model and as a result, I only see an Component entity and a Context entity within my code.

Now, using only these entities, is it possible to delete the contents of all three tables? I could, for example use this:

foreach (var obj in CPE.Context) { CPE.DeleteObject(obj); }

To delete all Context records. (CPE is the Context entity model.) This fails, of course, since Context has relations to Components. So I need another method.

(And yes, I can use SQL to do the same but It's for a "Proof of Usability" for the entity model so I want to do it as much within the model as possible.)

A: 

And then I noticed the stupidity I made in my code. It complained about a reference to another table as reason to not delete the Context records. Since I just added the new ComponentContext table, I blamed that one but I should really read those error messages more careful the next time. (There was another table that linked to the Context table.)

Anyway, to delete these relations, this code is enough:

foreach (var obj in CPE.Components.ToList())
{
    obj.Context.Load();
    foreach (var child in obj.Context.ToList()) { obj.Context.Remove(child); }
    CPE.DeleteObject(obj);
}

I use the ToList() out of habit, btw. It tends to avoid a few exceptions related to the direction in which .NET will read records. Now it first fills a list, then walks through the list in whatever direction I prefer...

Workshop Alex