0

I've got the following classes:

public class Discount 
{
    public override int Id { get; set; }
    public virtual IList<Region> Regions { get; set; }
}

public class Region
{
    public override int Id { get; set; }
    public int DiscountId { get; set; }
    public virtual Discount Discount { get; set; }
    public int Region { get; set; }
}

And when I delete a discount, I want it to do a cascading delete on the associated regions, using this code:

foreach (var discount in discounts) {
    context.Discounts.Remove(discount);
}

When calling context.SaveChanges() the following error occurs:

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Region_dbo.Discount_DiscountId". The conflict occurred in database "Portal", table "dbo.Region", column 'DiscountId'.

But if I debug the above for loop, and just after it removes the discount from the context I inspect the removed discount, it shows it has 0 regions. Then when calling context.SaveChanges() it works!

Any idea what's going on, and how I can get it to work when not debugging?

Tom
  • 1,561
  • 4
  • 20
  • 29

1 Answers1

0

OK - I've just realised you can't have cascading deletes when lazily loading objects, which makes sense.

Tom
  • 1,561
  • 4
  • 20
  • 29