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

旧时模样 提交于 2019-11-30 14:32:38

问题


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

At present, I have:

public class Status
{
    [Required]
    public int StatusId { get; set; }

    [Required]
    [DisplayName("Status")]
    public string Name { get; set; }
}

public class Restuarant
{
    public int RestaurantId { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    [EmailAddress]
    public string Email { get; set; }
    [Required]
    public string Telephone { get; set; }
    [Required]
    public int StatusId { get; set; }
    public List<Menu> Menus { get; set; }

    // NAVIGATION PROPERTIES
    public virtual Status Status { get; set; }
}

public class Menu
{
    public int MenuId { get; set; }

    [Required]
    public int RestaurantId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public int StatusId { get; set; }

    // NAVIGATION PROPERTIES
    public virtual Status Status { get; set; }
    public virtual Restaurant Restaurant { get; set; }
}

And my DbContext:

public class MenuEntities : DbContext
{
    public DbSet<Status> Statuses { get; set; }
    public DbSet<Restaurant> Restaurants { get; set; }
    public DbSet<Menu> Menus { get; set; }
}

As you can see:

  • a Restaurant has many menus
  • a Restaurant has one status
  • a Menu belongs to 1 restaurant
  • Both Restaurants and Menus have 1 status. (Live, Invisible, Draft)

Naturally, if a status is deleted, I certainly don't want to cascade as this will muck everything up.

UPDATE:

Mark Oreta mentions using the following in his example below:

modelBuilder.Entity<FirstEntity>() 
    .HasMany(f => f.SecondEntities) 
    .WithOptional() 
    .WillCascadeOnDelete(false); 

Where do I put this code? Within my MenuEntities / DbContext class? Can anybody provide an example of this being used?

UPDATE: Got this bit working now, however this has created a multiplicity constraint error when trying to seed the DB...

Multiplicity constraint violated. The role 'Menu_Status_Source' of the relationship 'LaCascadaWebApi.Models.Menu_Status' has multiplicity 1 or 0..1.

My Database Initialiser:

http://pastebin.com/T2XWsAqk


回答1:


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

      }

}



回答2:


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

public int? StatusId { get; set; }



回答3:


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

Add-Migration MigrationName -Force




回答4:


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

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



回答5:


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

.OnDelete(DeleteBehavior.Restrict);




回答6:


To achieve apply this on all the entities, modify foreign keys DeleteBehavior to Restrict. We do this in OnModelCreating() method of AppDbContext class

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    foreach (var foreignKey in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
    {
        foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
    }
}

Build the solution. Add a new migration and update the database.



来源:https://stackoverflow.com/questions/12868912/specify-on-delete-no-action-in-asp-net-mvc-4-c-sharp-code-first

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