In Entity Framework, how to delete record with foreign key constraint?

asp.net asp.net-mvc entity-framework

Question

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!

1
1
3/25/2013 8:17:49 AM

Accepted Answer

Like AliRiza said, set it in your SQL server. Additionally use this in your DbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<ProjectOptionItems>().WillCascadeOnDelete();
}
5
3/25/2013 8:24:51 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow