Search code examples
entity-frameworkbreezecascadecascading-deletes

Foreign key contstraint and cascaded delete


I have two objects, channel and business unit channel

public class Channel
{
    public int Id { get; set; }

    [Required, MaxLength(50)]
    public string Name { get; set; }
    public int DashboardConfigurationId { get; set; }
    public ICollection<BusUnitChannel> BusUnitChannels { get; set; }
}

public class BusUnitChannel
{
    public int Id { get; set; }
    public int BusinessUnitId { get; set; }
    public int ChannelId { get; set; }
    public BusinessUnit BusinessUnit { get; set; }
    public Channel Channel { get; set; }
}

when I try try to delete a channel, (i'm using breezejs) I get the error

Error: Failed to save changes to server. The UPDATE statement conflicted with the
FOREIGN KEY constraint "FK_dbo.BusUnitChannels_dbo.Channels_ChannelId". The conflict 
occurred in database "PulseDev", table "dbo.Channels", column 'Id'.

Having read other posts on this topic, I've added the following to my DbContext

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Channel>()
        .HasMany(c=>c.BusUnitChannels)
        .WithRequired(buc=>buc.Channel)
        .WillCascadeOnDelete();
}

What am I doing wrong?


Solution

  • Looks like the override method is not working.

    Update your code to:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Channel>()
            .HasMany(c=>c.BusUnitChannels)
            .WithRequired(buc=>buc.Channel)
            .WillCascadeOnDelete();
        base.OnModelCreating(modelBuilder);
    }
    

    or better yet; Set the delete cascade rule in your database. That's the way I prefer it.

    Edit:

    I have tested the code and it worked: Modify BusUnitChannel class as follows:

    public class BusUnitChannel
    {
        public int Id { get; set; }
        public int BusinessUnitId { get; set; }
        [ForeignKey("Channel")]
        public int ChannelId { get; set; }
        public BusinessUnit BusinessUnit { get; set; }
        public virtual Channel Channel { get; set; }
    }
    

    To set a cascade delete in SQL Server:

    expand "BusUnitChannel" table; you'll find the FK constraint under "Keys".Right Click then Modify. a dialog will show; expand "Insert and Update specification"change the "Delete Rule" to "Cascade" You can set the update rule as well.