I have a method to delete a "project" record in the database, and all the "option items" associated with it.
public bool DeleteProjectById(int id)
{
using (DbContext db = new DbContext(ConfigHelper.Instance().ConnectionString))
{
try
{
foreach (var entity in db.ProjectOptionItems.Where(o => o.ProjectId == id))
db.ProjectOptionItems.DeleteObject(entity);
db.SaveChanges();
var project = db.Projects.SingleOrDefault(o => o.Id == id);
db.Projects.DeleteObject(project);
db.SaveChanges();
return true;
}
catch (Exception e)
{
ErrorLoggingService.Log(this, e);
return false;
}
}
}
This works fine. But if I comment out the first call to db.SaveChanges, which is by the way how I was hoping the code will be, this will result to an SQL exception (The DELETE statement conflicted with the REFERENCE constraint).
Having two calls to SaveChanges() works but surely this is not the way to do it. Please help. Thanks!