locked
Cascade delete entitiyframework core RRS feed

  • Question

  • User1655654435 posted

    I'm a bit confused about this. So By convention, Entity Framework enables cascade delete for non-nullable foreign keys and for many-to-many relationships. 

    if I have a foreign key on one table called "Person" that references another table called "Organization", meaning that one Person can have one Organization. One Organization can have many Persons(So a one to many/many to one relationship).

    What would be the consequences if I delete one Person or one Organization by default?

    If I set the foreign key on the Person model as nullable, like 

    public int? OrganizationID {get; set;};

    What's the effect of that?  and is that the same as disabling cascade delete in the context class, only that in this case the foregn key is not nullable?

    modelBuilder.Entity<Organisasjon>().HasMany(i => i.Persons).WithOne(p => p.Organisasjon).HasForeignKey(r => r.OrganisasjonID).OnDelete(DeleteBehavior.Restrict);

    Thanks for any help

    Now, I have another table called Meeting. This has a many to many relationship with the Person table. So I understand that in .net core I need to use a join table. I call this table "MeetingSignup".

    This table does not need a primary key, I see from the Contoso tutorial in the docs. So I only have PersonID and MeetingID on that one. Now to avoid that the same person is assignet twice to the same meeting I make a composite key in the context class. This works fine. But say I want to delete a MeetingSignup record, will this also be affected by cascade delete so that I need to disable that like I did with the Organization FK?

    Wednesday, April 12, 2017 9:36 AM

All replies

  • User1771544211 posted

    Hi bluMarmalade,

    What's the effect of that?  and is that the same as disabling cascade delete in the context class, only that in this case the foregn key is not nullable?

    Based on my understanding the int? means that the property OrganizationID can be null. Which means that the Person may don't have a related Organization.

    want to delete a MeetingSignup record, will this also be affected by cascade delete so that I need to disable that like I did with the Organization FK?

    The MeetingSignUp table is created by EF automatically to manage the many-to-many relationship between Meeting and SignUp.

    The following link shows how to delete EF many-to-many relationship, please take it as reference.

    http://www.entityframeworktutorial.net/delete-many-to-many-entities-in-entity-framework.aspx

    Best Regards,

    Jean

    Thursday, April 13, 2017 2:15 AM