EF 5, update object gives “A referential integrity constraint violation occurred”

前端 未结 2 1155
滥情空心
滥情空心 2021-02-03 11:27

In my model I\'ve got a bunch of domain objects. Now I\'m having a problem when trying to update a User-object. The User has a foreignkey relation to the Role object. When I upd

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-03 12:03

    For the benefit of searchers, I was getting the same error but found a quick fix.

    I was loading a class with an FK relationship into the view to be edited. Even with no changes, the FK was being dropped and this error occurred. The fix was to include a hidden field into the Razor view that contained the FK. e.g.

    @Html.HiddenFor(model => model.ReleaseInfo.BookId)
    

    Code copied below so you can check if your situation is similar.

    Controller Actions

    public ActionResult Edit(int id = 0)
            {
                Book book = db.Books.Find(id);
                if (book == null)
                {
                    return HttpNotFound();
                }
                ViewBag.Id = new SelectList(db.ReleaseInfo, "BookId", "BookId", book.Id);
                return View(book);
            }
    
            //
            // POST: /Book/Edit/5
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Edit(Book book)
            {
                if (ModelState.IsValid)
                {
                    db.Entry(book).State = EntityState.Modified;
    
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                ViewBag.Id = new SelectList(db.ReleaseInfo, "BookId", "BookId", book.Id);
                return View(book);
            }
    

    Relationships

    Book.cs

      public class Book
        {
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int Id { get; set; }
    
            [Required]
            [MaxLength(100)]
            public string Title { get; set; }
    
    
            public virtual ICollection Authors { get; set; }
    
    
            public virtual ReleaseInfo ReleaseInfo { get; set; }
    
    
            public virtual ICollection ReReleases { get; set; }
    
        }
    

    ReleaseInfo.cs

    public class ReleaseInfo
        {
            // One to one relationship uses Books Key as Key.
            [Key, ForeignKey("Book")]
            public int BookId { get; set; }
    
            [DataType(DataType.Date)]
            [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
            public DateTime ReleaseDate { get; set; }
    
    
            public virtual Book Book { get; set; }
        }
    

提交回复
热议问题