实体框架4.3和级联删除

时间:2012-03-12 10:05:31

标签: c# .net entity-framework-4

是否可以在此对象模型上进行级联删除?

public class Entity
{
    [Key, Column("Id"), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
}

public class Comment : Entity
{
    public string Text { get; set; }
}

public class Owner : Entity
{
    public Owner()
    {
        Pets = new List<Pet>();
        Comments = new List<Comment>(); 
    }

    public string Name { get; set; }
    public virtual ICollection<Pet> Pets { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

public class Pet : Entity
{
    public Pet()
    {
        Comments = new List<Comment>();    
    }

    public virtual Owner Owner { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
    public string Name { get; set; }
}

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

    modelBuilder.Entity<Pet>()
        .HasOptional(d => d.Owner)
        .WithMany(d => d.Pets)
        .WillCascadeOnDelete(true);
}

此模型将生成一个数据库,当所有者被删除时,该数据库将级联删除Pets。但它不会级联删除Comment,它只会从Comments表中删除FK。如果我尝试相应地修改约束。

ALTER TABLE [dbo].[Comments]  WITH CHECK ADD  CONSTRAINT [FK_Comments_Pets_Pet_Id]     FOREIGN KEY([Pet_Id])
REFERENCES [dbo].[Pets] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Comments] CHECK CONSTRAINT [FK_Comments_Pets_Pet_Id]
GO

ALTER TABLE [dbo].[Comments]  WITH CHECK ADD  CONSTRAINT [FK_Comments_Owners_Owner_Id]     FOREIGN KEY([Owner_Id])
REFERENCES [dbo].[Owners] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Comments] CHECK CONSTRAINT [FK_Comments_Owners_Owner_Id]
GO

出现以下sql错误。

Introducing FOREIGN KEY constraint 'FK_Comments_Pets_Pet_Id' on table 'Comments' may   cause cycles or multiple cascade paths

这使我得出结论,创建的模型不能支持级联删除,我不得不分开删除注释。或者我在这里错过了什么?

1 个答案:

答案 0 :(得分:2)

是的,该模型不支持SQL Server中的直接级联删除,因为即使您没有考虑它,您的数据库表示也支持与Comment和{{Owner相关联的相同Pet行1}}。如果您随后删除Owner,则会触发级联删除至Comment,而宠物和Pet将触发级联删除至Comment以及=> SQL服务器不支持多个级联路径。

这通常通过手动删除或单独的数据库触发器处理删除相关记录来处理。