[英]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()
您需要在
_db.SaveChanges()
之前删除ChildTable
项目。
var childItems = _db.ChildTable.Where(c => c.p_id == id);
_db.ChildTable.RemoveRange(childItems );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.