Sunny Patel

Sunny Patel

  • NA
  • 3
  • 952

Foreign Key Issues

Apr 18 2016 7:42 AM
Hi Guys,
 
I am currently learning MVC/ Entity Framework. I getting an issue when I am trying to insert a Id to the database. Here are my models below including my controller/view
 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.
 
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 virtual int ResturantId { get; set; }
}
 
Controller:
OdeToFoodDb _db = new OdeToFoodDb();
public ActionResult Index(int id)
{
var restaurant = _db.Resturants.Find(id);
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 { restaurantId = review.ResturantId });
}
return View(review);
}
protected override void Dispose(bool disposing)
{
_db.Dispose();
base.Dispose(disposing);
}
 

Answers (2)