2

I have a problem to handle the delete operation in C# / EF. This is my code. I can delete record that is no problem. I have only problems with record that are used in other records. So he throw an exception and the user see a messagebox. But the record is still marked as delete so when I do another SaveChanges, I get a exception. Is it possible to change back the state of the record to not deleted?

public void Remove()
    {
        try
        {
            Klant deleteKlant = dbContext.Klanten.First(i => i.KlantId == Klant.KlantId);
            dbContext.Klanten.Remove(deleteKlant);
            dbContext.SaveChanges();
        }
        catch (Exception)
        {
            throw new ArgumentException("Wissen mislukt");
        }
    }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Kris Martele
  • 29
  • 1
  • 7
  • Look here: http://stackoverflow.com/questions/10535377/dbcontext-and-rejectchanges Use 'RejectChanges' method from the last answer. – Sasha Truf May 08 '15 at 21:12

1 Answers1

0

First you should keep your dbContext objects short lived if at all possible. You will run into huge problems if you keep them around, as they hold a strong pointer to every object created using them.

Second you should check whether it is valid to delete a record before you try to delete it, that way you never get an exception in the first place.

Guvante
  • 18,775
  • 1
  • 33
  • 64
  • How can you check if a record is used in the database? – Kris Martele May 08 '15 at 21:12
  • @KrisMartele: It depends on what you mean by "used". For instance if a `Klant` can have a `KlantCourse` which associates it will a `Course` object, you would have to search for `KlantCourse` objects with matching `KlantId`. It requires effort but allows very detailed error messages as you know exactly where the `Klant` is in use. – Guvante May 08 '15 at 21:34