The INSERT statement conflicted with the FOREIGN KEYconstraint "FK_dbo.Qlogs_dbo.Categories_CategoryId". The conflictoccurred in database "MvcQlog", table "dbo.Categories",column 'CategoryId'.The statement has been terminated.
说明:执行当前Web请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关错误以及代码中导致的出处的详细信息。
异常详细信息:System.Data.SqlClient.SqlExceotion:The INSERT statement conflicted with the FOREIGN KEY constraint “FK_dbo.Qlogs_dbo.Categories_CategoryId”.The conflict occurred in database “MvcQlog”,table “dbo.Categories”,column “CategoryId”.The statement has been terminated.
源错误:
行 56 : // qlog.CategoryId = 1;
行 57 : db.Qlogs.Add(qlog);
行 58 : db.SaveChanges();
行 59 : return RedirectToAction("Index");
行 60 : }
源文件:e:\CSharp\EF\MvcQlog\Controllers\HomeController.cs 行:58
问题:qlog中有个Categories表结构是NULL,且qlog的外键是Categories的主键
解决方案:qlog的Category初始化一个对象如:
public ActionResult Create(Qlog qlog)
{
if (ModelState.IsValid)
{
qlog.Category = new Category();
qlog.CategoryId = 1;
db.Qlogs.Add(qlog);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(qlog);
}