views:

81

answers:

2

Hi,

I'm currently in a situation where I need to delete entities without having access to the associated ObjectContext. I read about identifying relationships and they seem to be exactly what I need: I want to delete an object, once it is no longer referenced by its "parent" object.

I am using Visual Studio 2010 Premium to generate my database from an edmx file. As far as I understand, I need to include the foreign key of my "parent" object in the primary key of my "child" object table. However, I cannot find a way to tell Visual Studio to do this.

Can someone please help me out on this? Am I completely on a wrong path or am I just missing a setting somewhere?

Thanks,

Chris

A: 

No, you are in the right path. What you need to do is in the EDM designer, after creating your 2 entities (Parent and Child), right click on the Parent Entity and select Add => Association... and then specify Multiplicity and Navigation property names, and click Ok. You'll see that VS create an association in between which will result on a relationship between these 2 table later on when you generate a database from your model.
Do not create a property like ParentID on your Child entity as it will be automatically created by the designer once you create the association.
Furthermore, you can right click on the association in the EDM designer and Select Properties and Select "Cascade" on "End2 OnDelete" option so that the child will be deleted when the parent is deleted.

Morteza Manavi
That only works when I delete the parent object. I cannot delete the child (no object context) and I must not delete the parent (still needed). All I can do is remove the relationship and when I do that, it doesn't delete the child. Cascade on delete only works when I actually delete the parent object; it does not delete the child, when I remove the relationship. Using your solution gives me an error message: "A relationship from the 'ParentChild' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Child' must also in the 'Deleted' state."
Chris
A: 

I finally figured it out:

Go to your Child entity and create a scalar property ParentId. Set this property as entity key (making it a primary key, together with your Id property of your Child entity). Next go to your ParentChild relationship and add a referential constraint. Principal for the constraint is your Parent and Dependant is your Child. Dependant property must be the property you just created on your Child (i.e. ParentId). Save everything and you're good to go.

Basically this is described as "scenario 2" in this blog post: http://mocella.blogspot.com/2010/01/entity-framework-v4-object-graph.html

Chris