简体   繁体   English

使用Fluent API进行级联删除

[英]Cascade delete using Fluent API

I have two entities. 我有两个实体。 Profile and ProfileImages . ProfileProfileImages After fetching a Profile I want to delete ProfileImages through Profile without it just removing the reference to Profile (setting it to null ). 获取Profile我想通过Profile删除ProfileImages而不删除对Profile的引用(将其设置为null )。 How can this be done with fluent API and Cascading Delete? 如何通过流畅的API和级联删除来完成? Do I set the HasRequired attribute or the CascadeDelete attribute? 我是否设置了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; }
}

You can add this to your DB Context : 您可以将其添加到DB Context

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

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

You can configure cascade delete on a relationship by using the WillCascadeOnDelete method. 您可以使用WillCascadeOnDelete方法在关系上配置级联删除。 If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. 如果依赖实体上的外键不可为空,则Code First会在关系上设置级联删除。 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. 如果依赖实体上的外键可以为空,则Code First不会在关系上设置级联删除,并且当删除主体时,外键将设置为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM