Asp.net System.Data.Entity.Infrastructure.DbUpdateException

时间:2018-03-22 20:13:47

标签: sql asp.net-mvc sqlexception

我想删除帖子,但是我收到了SqlException:

  

DELETE语句与REFERENCE约束冲突   “FK_dbo.Adresler_dbo.Kisi_Kisi_ID”。冲突发生在数据库中   “TestDb”,表“dbo.Adresler”,列“Kisi_ID”。声明有   已被终止。

  [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");
    }

我该怎么做?

0 个答案:

没有答案