0

I want to delete a post but I get an SqlException:

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Adresler_dbo.Kisi_Kisi_ID". The conflict occurred in database "TestDb", table "dbo.Adresler", column 'Kisi_ID'. The statement has been terminated.

  [Table("Kisi")]
public class Kisiler
{
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    [StringLength(20),Required]
    public String Ad { get; set; }
    [StringLength(20),Required]
    public String Soyad { get; set; }
    [Required]
    public int Yas { get; set; }
    public virtual List<Adresler> Adresler { get; set; }

}
   [Table("Adresler")]
public class Adresler
{
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    [StringLength(300)]
    public string AdresTanim { get; set; }
    public virtual Kisiler Kisi { get; set; }
}

  [HttpPost,ActionName("Sil")]
    public ActionResult SilOk(int? kisiid)
    {

        if (kisiid != null)
        {
            DatabaseContext db = new DatabaseContext();
            Kisiler kisi = db.dbSetKisiler.Where(x => x.ID == kisiid).FirstOrDefault();

            Adresler adres = db.dbSetAdresler.Where(x => x.Kisi.ID == kisi.ID).FirstOrDefault();


            db.dbSetKisiler.Remove(kisi);
            db.dbSetAdresler.Remove(adres);
            db.SaveChanges();

        }
        return RedirectToAction("Index", "Home");
    }

How can I do it?

Youn Elan
  • 2,379
  • 3
  • 23
  • 32
  • Possible duplicate of [Delete statement conflicts with Reference constraint](https://stackoverflow.com/questions/30534421/delete-statement-conflicts-with-reference-constraint) –  Mar 22 '18 at 20:16
  • 1
    So the error is telling you that you have a reference constraint. This means another table is referencing the row you are trying to delete. You need to find this constraint, identify if it is valid, and then determine what course of action you want to take with this row, when deleting the row it references. There are lots of options. The provided link by Amy shows how to trigger cascade delete in entity framework. This one shows how to set it up directly on your sql table: https://stackoverflow.com/questions/6260688/how-do-i-use-cascade-delete-with-sql-server – user7396598 Mar 22 '18 at 20:29

0 Answers0