Entity Framework Code First 5 Cascade Delete on many to many tables error

前端 未结 1 1021
一生所求
一生所求 2020-12-31 23:26

I\'ve this model

public class State
{
    public State()
    {
        this.Promotions = new List();
        this.Branches = new List

        
相关标签:
1条回答
  • 2021-01-01 00:06

    Ok, I understood the problem. It is not to have a many to many relationship, the problem is this

    State -> Promotion -> PromotionStore
    State -> Branch -> BranchPromotion
    State -> Store -> StorePromotion
    

    and then Store, Branch and Store have FK to State. So if I delete a State PromotionStore can be reached by 1st and 3rd possibilities.

    What I ended up doing is turning off cascade delete for State and deleting the related records manually like this:

    public override void Delete(State state)
    {
       DbContext.Entry(state).Collection(x => x.Promotions).Load();
       DbContext.Entry(state).Collection(x => x.Stores).Load();
       DbContext.Entry(state).Collection(x => x.Branches).Load();
    
       var associatedPromotions = state.Promotions.Where(p => p.StateId == state.Id);
       associatedPromotions.ToList().ForEach(r => DbContext.Set<Promotion>().Remove(r));
    
       var associatedStores = state.Stores.Where(e => e.StateId == state.Id);
       associatedStores.ToList().ForEach(e => DbContext.Set<Store>().Remove(e));
    
       var associatedBranches = state.Branches.Where(s => s.StateId == state.Id);
       associatedBranches.ToList().ForEach(s => DbContext.Set<Branch>().Remove(s));
    
       base.Delete(state);
    }
    
    0 讨论(0)
提交回复
热议问题