How to define composition(boss, subordinate relationship)

177 views Asked by At

I would like to define recurrent composition relationship. If the boss is removed from the system all his subordinates are removed by cascade update.

By this I mean:

How should I state it in the code?

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

Is that possible in the Entity Framework?

1

There are 1 answers

0
Gert Arnold On

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

So if you load a Person and delete it, you'll get a foreign key violation error if this Person has subordinates. EF won't update these child records (set their FKs to null) automatically.

If however you load a Person and its subordinates and delete the Person, EF will nullify each child's foreign key.

To make this loading a bit easier, you should modify the Person class slightly:

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; }
}

Now you can load a Person and Include() its Subordinates.

By the way, you can't specify cascaded delete/update rules because Sql Server doesn't accept cyclic cascade paths.