user3820867 user3820867 - 7 months ago 45
SQL Question

The INSERT statement conflicted with the FOREIGN KEY constraint

I'm currently learning ASP.NET MVC apps. Basically I created a MVC 4 app with EF called Restaurant Review. However when I create a new review it shows an error. I know it must be something I missed.

The error is


The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.ResturantReviews_dbo.Resturants_Resturant_Id". The conflict occurred in database "OdeToFoodDb", table "dbo.Resturants", column 'Id'.
The statement has been terminated.**


Below shows my hierarchy.

Model

public class Resturant
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public virtual ICollection<ResturantReview> Reviews { get; set; }
}

public class ResturantReview
{
public int Id { get; set; }
public int Rating { get; set; }
public string Body { get; set; }
public string ReviewerName { get; set; }
public int ResturantId { get; set; }
}


Controller

public class ReviewsController : Controller
{
private readonly OdeToFoodDb _db = new OdeToFoodDb();

public ActionResult Index([Bind(Prefix = "id")]int restaurantId)
{
var restaurant = _db.Resturants.Find(restaurantId);
if (restaurant != null)
{
return View(restaurant);
}
return HttpNotFound();
}

[HttpGet]
public ActionResult Create(int restaurantId)
{
return View();
}

[HttpPost]
public ActionResult Create(ResturantReview review)
{
if (ModelState.IsValid)
{
_db.Reviews.Add(review);
_db.SaveChanges();
return RedirectToAction("Index", new { id = review.ResturantId });
}
return View(review);
}


View

@model OdeToFood.Models.Resturant

@{
ViewBag.Title = "Index";
}

<h2>Review For @Model.Name</h2>

@Html.Partial("_Reviews", Model.Reviews)
<p>
@Html.ActionLink("Create New", "Create", new {restaurantId = Model.Id})
</p>

Answer

I think you Id property of your Restaurant table is not unique or primary key. Please check that first and try again.

Comments