外键约束添加级联删除

时间:2014-02-01 12:37:27

标签: entity-framework breeze cascade cascading-deletes

我有两个对象,频道和业务单位频道

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

当我尝试删除频道时,(我正在使用breezejs)我收到错误

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'.

阅读了有关此主题的其他帖子后,我已将以下内容添加到我的DbContext

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

我做错了什么?

2 个答案:

答案 0 :(得分:1)

看起来覆盖方法无效。

将您的代码更新为:

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

或更好;在数据库中设置删除级联规则。这就是我喜欢的方式。

修改

我测试了代码并且它有效: 修改BusUnitChannel类,如下所示:

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

在SQL Server中设置级联删除:

展开“BusUnitChannel”表;你会在“键”下找到FK约束。右键单击然后单击修改。 将显示一个对话框;展开“插入和更新规范”将“删除规则”更改为“级联” 您也可以设置更新规则。

答案 1 :(得分:0)

让我们尝试另一种方式。删除以前的BusUnitChannel声明并更新频道,如下所示:

modelBuilder.Entity<Channel>()
            .HasMany(c=>c.BusUnitChannels)
            .WithRequired(buc=>buc.Channel)
            .WillCascadeOnDelete(true); # pass true here