I got two tables, one User
and Comment
. Both User
and Comment
got Id
as Primary Key. Comment
also have a FK key for User
Id so called CreatorUserID
. Once I try to edit a Comment
row I get the following error:
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Comment_User". The conflict occurred in database "XX", table "dbo.User", column 'Id'.
I'm not touching FK CreatorUserId
in Comment
table. I also made sure to enable Cascade in Update and Delete for FK-relationships in SQL Server.
This is how my Edit action looks like:
public ActionResult Edit(Guid? id) {
Comment comment = db.Comment.Find(id);
if (review == null) {
return HttpNotFound();
}
return View(comment);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,CreatorUserID,Description,Title")] Comment comment) {
if (ModelState.IsValid) {
db.Entry(comment).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(comment);
}
Additional info:
Database-first
Using Guids for Id's.
This is how url looks like before I click update which result error:
http://localhost:41003/Comment/Edit/8cab7ab2-3184-e611-9d7a-6c71d98d2a40
User-Table
Id(Guid) PK
Email(nvarchar)
Password(nvarchar)
Comment-table
Id(Guid) PK
CreatorUserID(Guid) FK
Description(nvarchar) // this and title is the only thing I'm trying to edit
Title(nvarchar)
What am I doing wrong? I just want to Update Description
and Title
. I don't touch Id
or CreatorUserID
during Update.
View: (I have only included form controls for the properties I am editing)
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>