Specify ON DELETE NO ACTION in ASP.NET MVC 4 C# Code First

久未见 提交于 2019-11-30 10:52:43

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 );

      }

}

Just make the FK property nullable, then the cascade delete will be gone.

public int? StatusId { get; set; }

After making the changes to the model, make sure you regenerate the migration file by adding the -Force parameter.

Add-Migration MigrationName -Force

Lionfoo

Put this into your MenuEntities class (class that descend from DbContext):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); 
}

add this line to end of the field in the context;

.OnDelete(DeleteBehavior.Restrict);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!