6

有两个实体,如下所示:

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, ...
}

如何为业务删除文件配置级联删除?请考虑我不需要任何导航 from Fileto Business

更新:

您可能会发现 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 UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。无法创建约束

4

1 回答 1

5

If you like to use seperate configuration classes you could try something like that:

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

When you do not pass a lambda within .WithOptional() or .WithRequired() means the other side has no navigation properties.

于 2013-08-29T09:07:46.923 回答