问题
Searching about the cascading behavior of Entity Framework
, if noticed this answer. On short, the OP is searching for a way to perform cascade delete on 1-0 / 1-1 relationships in Entity Framework
, and the best answer contains a snippet on Fluent API applying WillCascadeOnDelete(true);
On the DB Context's modelBuilder.
On the selected answer, a user (CodeMonkey) mentioned:
(...) Some have suggested [Required] for cascading delete. This indeed works, but of course, only if it is actually required
My question is, if the relation is set to 1-1 (using [Required] or even without setting the relation as optional to EntityTypeConfiguration
) with required dependencies, is cascade delete performed by default, without having to set it to Fluent API, as mentioned on the comment?
回答1:
If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null. The multiplicity and cascade delete behavior detected by convention can be overridden by using the fluent API.
Code First Conventions
来源:https://stackoverflow.com/questions/30033217/is-cascade-delete-automatically-performed-in-entity-framework-1-1-required-rel