实体框架:如何在单向相关实体上启用级联删除

时间:2013-08-29 09:00:29

标签: c# entity-framework code-first

有两个实体,如bellow:

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

    public File Logo {get; set;}
    public int? LogoId {get; set;}

    public File Video {get; set;}
    public int? Video {get; set;}

    public ICollection<File> Images {get; set;}
}

public class File
{
    // some file props, such as Id, Name, ...
}

如何为业务删除文件配置级联删除? 请注意,我不需要从FileBusiness的任何导航。

更新:

您可以在下面找到modelBuilder配置:

        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        modelBuilder.Entity<Entities.Business>()
            .HasOptional(b => b.Logo)
            .WithOptionalPrincipal()
            .WillCascadeOnDelete();

        modelBuilder.Entity<Entities.Business>()
            .HasOptional(b => b.Video)
            .WithOptionalPrincipal()
            .WillCascadeOnDelete();

        modelBuilder.Entity<Entities.Business>()
            .HasMany(b => b.Images)
            .WithOptional()
            .WillCascadeOnDelete();

这是我遇到的错误:

  

引入FOREIGN KEY约束   表'文件'上的'FK_dbo.Files_dbo.Businesses_Business_Id1'可能导致   循环或多个级联路径。指定ON DELETE NO ACTION或ON   更新无操作,或修改其他FOREIGN KEY约束。不能   创建约束

1 个答案:

答案 0 :(得分:5)

如果你想使用单独的配置类,你可以试试这样的东西:

  public class BusinessConfiguration : EntityTypeConfiguration<Business>
  {
        public BusinessConfiguration()
        {
            HasMany(x => x.Images).WithOptional().WillCascadeOnDelete();
            HasOptional(x => x.Logo).WithOptional().WillCascadeOnDelete();
            HasOptional(x => x.Video).WithOptional().WillCascadeOnDelete();
        }
  }

如果您未在.WithOptional().WithRequired()内传递lambda,则表示另一方没有导航属性。