简体   繁体   中英

Error while deleting record from multiple table

I have this page where I am trying to delete a record. But when I try to delete a record I am getting an error " The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted. "

Entity:

    public partial class ParentTable
{

    public int p_id { get; set; }
    public string p_titl { get; set; }
    public string p_subtitle { get; set; }
    public string p_message { get; set; }
    public Nullable<System.DateTime> p_date { get; set; }


    public virtual ICollection<ChildTable> childtable { get; set; }
}
public partial class ChildTable
{
    public long id { get; set; }
    public int p_id { get; set; }
    public string message { get; set; }


    public virtual ParentTable parenttable { get; set; }
}

Delete code :

        public ActionResult Delete(int id)
    {            
            var deleteall = _db.ParentTable.Include(p => p.ChildTable).FirstOrDefault(p => p.p_id == id);
            _db.ParentTable.Remove(deleteall);          
            _db.SaveChanges();
             return RedirectToAction("Index");
    }

You need to remove ChildTable items before _db.SaveChanges()

var childItems = _db.ChildTable.Where(c => c.p_id == id);
_db.ChildTable.RemoveRange(childItems );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM