EntityFramework: How to configure Cascade-Delete to nullify Foreign Keys

后端 未结 2 961
萌比男神i
萌比男神i 2020-12-05 04:22

EntityFramework\'s documentation states that the following behavior is possible:

If a foreign key on the dependent entity is nullable, Code First does

2条回答
  •  無奈伤痛
    2020-12-05 05:17

    After following @Slauma's great answer I was still getting same error as OP.

    So don't be as naive as me and think that the examples below will end up with same result.

    dbCtx.Entry(principal).State = EntityState.Deleted;
    dbCtx.Dependant.Where(d => d.PrincipalId == principalId).Load();
    
    // code above will give error and code below will work on dbCtx.SaveChanges()
    
    dbCtx.Dependant.Where(d => d.PrincipalId == principalId).Load();
    dbCtx.Entry(principal).State = EntityState.Deleted;
    

    First load the children into context before setting entity state to deleted (if you are doing it that way).

提交回复
热议问题