开发者

Implementing identifying relationships with EF4

开发者 https://www.devze.com 2023-01-16 06:53 出处:网络
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 w

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开发者_如何学Python 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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号