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

后端 未结 5 511
情歌与酒
情歌与酒 2021-01-01 09:57

How do I specify ON DELETE NO ACTION Foreign Key Constraint in my model designs?

At present, I have:

public class Status
{
    [Required]
    public          


        
相关标签:
5条回答
  • 2021-01-01 10:42

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

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); 
    }
    
    0 讨论(0)
  • 2021-01-01 10:47

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

    public int? StatusId { get; set; }
    
    0 讨论(0)
  • 2021-01-01 10:47

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

    .OnDelete(DeleteBehavior.Restrict);

    0 讨论(0)
  • 2021-01-01 10:52

    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 );
    
          }
    
    }
    
    0 讨论(0)
  • 2021-01-01 11:01

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

    Add-Migration MigrationName -Force

    0 讨论(0)
提交回复
热议问题