使用 Fluent 级联删除 API

Cascade delete using Fluent API

我有两个实体。 ProfileProfileImages。获取 Profile 后,我想通过 Profile 删除 ProfileImages,而不只是删除对 Profile 的引用(将其设置为 null)。如何使用流畅的 API 和级联删除来完成此操作?我是设置 HasRequired 属性还是 CascadeDelete 属性?

public class Profile 
{
    //other code here for entity
    public virtual ICollection<ProfileImage> ProfileImages { get; set; }
}

public class ProfileImage 
{
    // other code here left out        
    [Index]
    public string ProfileRefId { get; set; }

    [ForeignKey("ProfileRefId")]
    public virtual Profile Profile { get; set; }
}

您可以将此添加到您的 DB Context:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Profile>()
    .HasOptional(c => c.ProfileImages)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);
}

在此处阅读更多内容:Enabling Cascade Delete

You can configure cascade delete on a relationship by using the WillCascadeOnDelete method. If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null.