Entity Framework delete child object

后端 未结 2 2025
时光说笑
时光说笑 2020-12-21 18:10

I have two tables without any cascade deleting. I want to delete parent object with all child objects. I do it this way

//get parent object
return _dataConte         


        
相关标签:
2条回答
  • 2020-12-21 18:28

    It is enough to set the

    <OnDelete Action="Cascade" />
    for the master association end in the CSDL part of the model.
    In this case your code will work.

    0 讨论(0)
  • 2020-12-21 18:43

    My situation was slightly different, and it took a while to get it right so I thought it worth documenting. I have two related tables, Quote and QuoteExtension:

    • Quote (Parent, Primary Key QuoteId)
    • QuoteExtension (Calculated fields for Quote, Primary and Foreign Key QuoteId)

    I didn't have to set the OnDelete action to get it to work - but Craig's comment (if I could vote that up more I would!) led me to discover the issue. I was attempting to delete the Quote when QuoteExtension was not loaded. Therefore I found two ways that worked:

    var quote = ent.Quote.Include("QuoteExtension").First(q => q.QuoteId == 2311);
    ent.DeleteObject(quote);
    ent.SaveChanges();
    

    Or:

    var quote = ent.Quote.First(q => q.QuoteId == 2311);
    if (quote.QuoteExtension != null)
        ent.Refresh(RefreshMode.ClientWins, quote.QuoteExtension);
    ent.DeleteObject(quote);
    ent.SaveChanges();
    

    Interestingly trying to delete QuoteExtension manually didn't work (although it may have if I had included ent.SaveChanges() in the middle - this tends to happen only at the end of a unit of work in this system so I wanted something that didn't rely on this.

    0 讨论(0)
提交回复
热议问题