@Eranga is right that this is done using the ON DELETE CASCADE parameter for the relationship in the database, but you use the first approach to the code, and EF creates the database for you, so the problem is that your model is incorrectly defined because EF didn't create a cascading rule for you.
Why? Because of this:
public class Direction { public int DirectionId { get; set; } public string Abbreviation { get; set; } public virtual Forecast Forecast { get; set; } public virtual List<Transport> Transports { get; set; } }
Abbreviation is a FK property and it is NULL! So EF looks at your model and sees that you have defined a Direction object that can have an Abbreviation value of null, and because of this it can exist as an orphan. Change it to:
public class Direction { public int DirectionId { get; set; } [Required] public string Abbreviation { get; set; } public virtual Forecast Forecast { get; set; } public virtual List<Transport> Transports { get; set; } }
and removing Forecast will remove all associated Direction and Transport instances. Stop is a different story because it is the parent Forecast object, so it will never be deleted using Forecast .
Edit:
Another point - you do not want to add ON DELETE CASCADE to your relationship manually, because EFs must know about allowed cascading deletes. EF uses this information if you have related objects associated.
If you put the rule manually in the database, you should use free mapping and tell EF about this rule. When you forcefully delete a cascade in a fluent api, you do not need to manually make it in the database - it will be created automatically during the rest of the database.
source share