使用Fluent API进行级联删除

4
我有两个实体,一个是“Profile(资料)”,另一个是“ProfileImages(资料图片)”。在获取了“Profile(资料)”之后,我想通过“Profile(资料)”删除“ProfileImages(资料图片)”,而不仅仅是将它的引用设为“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; }
}
1个回答

3
您可以将此内容添加到您的DBContext中:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Profile>()
    .HasOptional(c => c.ProfileImages)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);
}

点击此处阅读更多:启用级联删除

您可以使用WillCascadeOnDelete方法在关系上配置级联删除。如果从属实体上的外键不可为空,则Code First会在关系上设置级联删除。如果从属实体上的外键可为空,则Code First不会在关系上设置级联删除,当主体被删除时,外键将被设置为null。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接