In the RC1 of EntityFramework 7, released yesterday, Cascade Delete was added.
To disable it per relationship, I can use :
builder.Entity<Site>().HasOne(e => e.Person)
.WithMany(x => x.Sites).Metadata.DeleteBehavior = DeleteBehavior.Restrict;
I want to disable it globally for a DbContext, but I didn't find a way. How can I do ?
Someone stated on the github project forum that the only way to do it right now is to iterate through all relationships in the method OnModelCreating(ModelBuilder builder)
, and set the DeleteBehavior
property to DeleteBehavior.Restrict
:
foreach (var relationship in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
Right now conventions are not configurable. The current CascadeDelete convention only applies to required relationships. Relationships Conventions: Cascade Delete on efproject.net (Official EF7 docs) You could disable the required relationship explicitly if you understand well the consequences.
modelBuilder.Entity<Site>()
.HasOne(p => p.Person)
.WithMany(b => b.Sites)
.IsRequired(false);
Otherwise (and recommended), you need to set the On Delete behavior explicitly ( as you already discovered).
modelBuilder.Entity<Site>()
.HasOne(p => p.Person)
.WithMany(b => b.Sites)
.OnDelete(DeleteBehavior.Restrict);
If you don’t use Required
on a property in model class, it’s generated as DeleteBehavior.Restrict
by default. Use Required
if you want to use DeleteBehavior.Cascade
. You can see this by generating dummy migrations by using with/without Required.
来源:https://stackoverflow.com/questions/33807879/ef7-rc1-disable-cascade-delete