How to determine the composition (boss, subordinate relationships)

I would like to define the current relationship of the composition. If a boss is removed from the system, all of his subordinates will be removed through a cascading update.

By this I mean:

How do I specify this in code?

public class Person{
     public int Id {get;set;}
     public virtual Person Person {get;set}
}

      

Is this possible in Entity Framework?

+3


source to share


1 answer


It is not documented anywhere as far as I know, but the Entity Framework only creates / updates / deletes the entities it loaded .

So, if you download Person

and remove it, you will get a foreign key violation error if it Person

has subordinates. EF will not update these child records (automatically install their FKs).

If you load Person

both its subordinates and delete Person

, EF invalidates every child foreign key.

To make this loading a little easier, you must modify the class a little Person

:



public class Person
{
    public int Id { get; set; }

    public virtual Person Boss { get; set; }

    [InverseProperty("Boss")] // Use one FK field for Boss and Subordinates 
    public virtual ICollection<Person> Subordinates { get; set; }
}

      

You can now download Person

and Include()

it Subordinates

.

By the way, you cannot specify cascading delete / update rules as Sql Server does not accept circular cascading paths.

+1


source







All Articles