[英]BulkInsert: The INSERT statement conflicted with the FOREIGN KEY constraint
[英]The INSERT statement conflicted with the FOREIGN KEY constraint
我目前正在學習 ASP.NET MVC 應用程序。 基本上,我使用 EF 創建了一個名為 Restaurant Review 的 MVC 4 應用程序。 但是,當我創建新評論時,它顯示錯誤。 我知道這一定是我錯過的東西。
錯誤是
INSERT 語句與 FOREIGN KEY 約束“FK_dbo.ResturantReviews_dbo.Resturants_Resturant_Id”沖突。 沖突發生在數據庫“OdeToFoodDb”、表“dbo.Resturants”、“Id”列中。 該語句已終止。**
下面顯示了我的層次結構。
模型
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; }
}
控制器
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);
}
看法
@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>
我認為您的Restaurant
表的Id
屬性不是唯一鍵或主鍵。 請先檢查並重試。
我認為餐館有問題。 嘗試添加檢查是否存在已審核的餐廳。 而且我還建議為您的模型添加驗證屬性,例如[Required]
。
此問題可能是由實體框架引起的。 檢查您的 Review 實體中是否有 Restaurant 字段。 如果是這樣,請在保存評論之前為其分配 null(只需將 ID 留在 RestaurantId 字段內)。
在某些情況下,EF 認為分離的實體是一個新實體(例如,如果我們正在獲取內部有餐廳的評論)並嘗試將其添加到數據庫中,但由於完全相同的實體已存在而獲得異常。 如果我們不需要它,我們必須阻止它保存餐廳,所以我們應該只保存評論。
另外,正如其他人提到的,您可能只是對不存在的餐廳添加評論(不確定您是否是這種情況,我想這種問題很容易檢測到)
如果它對您有幫助/沒有幫助,請告訴我。
添加以下屬性
public int RestaurantId { get; set; }
在RestaurantReview
模型類中。
和 Update-Database -Verbose 在包管理器控制台中
現在構建並運行。 它將解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.