How do I specify ON DELETE NO ACTION Foreign Key Constraint in my model designs?
At present, I have:
public class Status
{
[Required]
public
Put this into your MenuEntities
class (class that descend from DbContext
):
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
Just make the FK property nullable, then the cascade delete will be gone.
public int? StatusId { get; set; }
add this line to end of the field in the context;
.OnDelete(DeleteBehavior.Restrict);
You can either disable it for your entire context by removing the cascade delete convention in the OnModelCreating method:
protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
or, you can do it per relationship using a fluent mapping (also in the OnModelCreating):
EDIT: you would put it in your menu entities
public class MenuEntities : DbContext
{
public DbSet<Status> Statuses { get; set; }
public DbSet<Restaurant> Restaurants { get; set; }
public DbSet<Menu> Menus { get; set; }
protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Entity<Menu>()
.HasRequired( f => f.Status )
.WithRequiredDependent()
.WillCascadeOnDelete( false );
modelBuilder.Entity<Restaurant>()
.HasRequired( f => f.Status )
.WithRequiredDependent()
.WillCascadeOnDelete( false );
}
}
After making the changes to the model, make sure you regenerate the migration file by adding the -Force parameter.
Add-Migration MigrationName -Force