INSERT 语句与 FOREIGN KEY 冲突,但 debug window 显示正确的值
The INSERT statement conflicted with the FOREIGN KEY, but debug window shows correct values
大家好,我是 asp.net mvc 的新手,目前正在从事我的大学项目,这是一个大学门户网站,使用 entity framework 代码优先方法。但是我收到一个错误 **
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_dbo.Notices_dbo.Colleges_CollegeId". The conflict occurred in
database "aspnet-QuickPly5-20180306011920", table "dbo.Colleges",
column 'Id'.
**
我在整个网络上搜索解决方案,每个人都建议在将数据输入到外键 table 之前,要插入的值应该存在于主 table 中。我的模型类如下
Collge.cs
public class College
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Phone { get; set; }
[Required]
public string Address { get; set; }
}
Notice.cs
public class Notice {
public int Id { get; set; }
[Required]
public string Title { get; set; }
public string Description { get; set; }
public string ImagePath { get; set; }
[Required]
public DateTime DatePosted { get; set; }
//public bool IsPublic { get; set; }
public College College { get; set; }
public int CollegeId { get; set; }
}
NoticeController.cs
[HttpPost]
public ActionResult ProcessForm(Notice notice, HttpPostedFileBase file)
{
if (file != null)
{
var fileName = Guid.NewGuid() + "-" + file.FileName;
notice.ImagePath = Server.MapPath(Path.Combine("~/uploads/notice/" + fileName));
file.SaveAs(notice.ImagePath);
}
if (notice.Id == 0)
{
notice.DatePosted = DateTime.Now;
_context.Notice.Add(notice);
}
else
{
var noticeInDb = _context.Notice.Single(n => n.Id == notice.Id);
notice.Title = noticeInDb.Title;
notice.Description = noticeInDb.Description;
notice.ImagePath = noticeInDb.ImagePath;
//notice.IsPublic = noticeInDb.IsPublic;
}
_context.SaveChanges();
return View("Index");
}
Table定义
通知
CREATE TABLE [dbo].[Notices] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (MAX) NOT NULL,
[Description] NVARCHAR (MAX) NULL,
[ImagePath] NVARCHAR (MAX) NULL,
[DatePosted] DATETIME NOT NULL,
[CollegeId] INT NOT NULL,
CONSTRAINT [PK_dbo.Notices] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.Notices_dbo.Colleges_CollegeId] FOREIGN KEY ([CollegeId]) REFERENCES [dbo].[Colleges] ([Id]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_CollegeId]
ON [dbo].[Notices]([CollegeId] ASC);
大学
CREATE TABLE [dbo].[Colleges] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NOT NULL,
[Email] NVARCHAR (MAX) NOT NULL,
[Phone] NVARCHAR (MAX) NOT NULL,
[Address] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_dbo.Colleges] PRIMARY KEY CLUSTERED ([Id] ASC)
);
当我 运行 应用程序正常时,我从标题中得到异常,但 在调试 window 中,当我检查它时显示 CollegeId = 1 ( table) 和 NoticeId = 6 中只有一行(已经很少有通知了)。我可以手动正确地将数据添加到 table 而不会出现任何错误。
我不明白我做错了什么。
提前致谢。
(对不起我的英语)
Debug window screenshot
输入你的学院 class 并通知 class 像这样:
public class College
{
//...
public ICollection<Notice> Notice{ get; set; }
}
public class Notice
{
//...
[ForeignKey("College")]
public int CollegeId { get; set; }
public College College { get; set; }
}
我觉得你的问题从观点上看。我重写代码。它按照代码工作。
创建视图:
@model Whosebugquestion1.Models.Notice
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("ProcessForm", "Notice", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Notice</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<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>
<div class="form-group">
@Html.LabelFor(model => model.ImagePath, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ImagePath, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ImagePath, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DatePosted, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DatePosted, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DatePosted, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CollegeId, "CollegeId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBox("CollegeId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CollegeId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
我更改了代码:
[HttpPost]
public ActionResult ProcessForm(Notice notice, HttpPostedFileBase file)
{
if (file != null)
{
var fileName = Guid.NewGuid() + "-" + file.FileName;
notice.ImagePath = Server.MapPath(Path.Combine("~/uploads/notice/" + fileName));
file.SaveAs(notice.ImagePath);
}
if (notice.Id == 0)
{
//notice.DatePosted = DateTime.Now;
_context.Notice.Add(notice);
}
else
{
_context.Entry(notice).State = EntityState.Modified;
//var noticeInDb = _context.Notice.Single(n => n.Id == notice.Id);
//notice.Title = noticeInDb.Title;
//notice.Description = noticeInDb.Description;
//notice.ImagePath = noticeInDb.ImagePath;
//notice.IsPublic = noticeInDb.IsPublic;
}
//_context.Notice.Add(notice);
_context.SaveChanges();
return View("Index", _context.Notice);
}
和索引控制器:包括将 College 属性 设置为通知模型的方法。
// GET: Notice
public ActionResult Index()
{
var model = _context.Notice.Include(i => i.College);
return View(model);
}
大家好,我是 asp.net mvc 的新手,目前正在从事我的大学项目,这是一个大学门户网站,使用 entity framework 代码优先方法。但是我收到一个错误 **
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Notices_dbo.Colleges_CollegeId". The conflict occurred in database "aspnet-QuickPly5-20180306011920", table "dbo.Colleges", column 'Id'.
** 我在整个网络上搜索解决方案,每个人都建议在将数据输入到外键 table 之前,要插入的值应该存在于主 table 中。我的模型类如下
Collge.cs
public class College
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Phone { get; set; }
[Required]
public string Address { get; set; }
}
Notice.cs
public class Notice {
public int Id { get; set; }
[Required]
public string Title { get; set; }
public string Description { get; set; }
public string ImagePath { get; set; }
[Required]
public DateTime DatePosted { get; set; }
//public bool IsPublic { get; set; }
public College College { get; set; }
public int CollegeId { get; set; }
}
NoticeController.cs
[HttpPost]
public ActionResult ProcessForm(Notice notice, HttpPostedFileBase file)
{
if (file != null)
{
var fileName = Guid.NewGuid() + "-" + file.FileName;
notice.ImagePath = Server.MapPath(Path.Combine("~/uploads/notice/" + fileName));
file.SaveAs(notice.ImagePath);
}
if (notice.Id == 0)
{
notice.DatePosted = DateTime.Now;
_context.Notice.Add(notice);
}
else
{
var noticeInDb = _context.Notice.Single(n => n.Id == notice.Id);
notice.Title = noticeInDb.Title;
notice.Description = noticeInDb.Description;
notice.ImagePath = noticeInDb.ImagePath;
//notice.IsPublic = noticeInDb.IsPublic;
}
_context.SaveChanges();
return View("Index");
}
Table定义
通知
CREATE TABLE [dbo].[Notices] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (MAX) NOT NULL,
[Description] NVARCHAR (MAX) NULL,
[ImagePath] NVARCHAR (MAX) NULL,
[DatePosted] DATETIME NOT NULL,
[CollegeId] INT NOT NULL,
CONSTRAINT [PK_dbo.Notices] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.Notices_dbo.Colleges_CollegeId] FOREIGN KEY ([CollegeId]) REFERENCES [dbo].[Colleges] ([Id]) ON DELETE CASCADE
);
GO
CREATE NONCLUSTERED INDEX [IX_CollegeId]
ON [dbo].[Notices]([CollegeId] ASC);
大学
CREATE TABLE [dbo].[Colleges] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NOT NULL,
[Email] NVARCHAR (MAX) NOT NULL,
[Phone] NVARCHAR (MAX) NOT NULL,
[Address] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_dbo.Colleges] PRIMARY KEY CLUSTERED ([Id] ASC)
);
当我 运行 应用程序正常时,我从标题中得到异常,但 在调试 window 中,当我检查它时显示 CollegeId = 1 ( table) 和 NoticeId = 6 中只有一行(已经很少有通知了)。我可以手动正确地将数据添加到 table 而不会出现任何错误。
我不明白我做错了什么。
提前致谢。 (对不起我的英语)
Debug window screenshot
输入你的学院 class 并通知 class 像这样:
public class College
{
//...
public ICollection<Notice> Notice{ get; set; }
}
public class Notice
{
//...
[ForeignKey("College")]
public int CollegeId { get; set; }
public College College { get; set; }
}
我觉得你的问题从观点上看。我重写代码。它按照代码工作。
创建视图:
@model Whosebugquestion1.Models.Notice
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("ProcessForm", "Notice", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Notice</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<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>
<div class="form-group">
@Html.LabelFor(model => model.ImagePath, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ImagePath, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ImagePath, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DatePosted, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DatePosted, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DatePosted, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CollegeId, "CollegeId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBox("CollegeId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CollegeId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
我更改了代码:
[HttpPost]
public ActionResult ProcessForm(Notice notice, HttpPostedFileBase file)
{
if (file != null)
{
var fileName = Guid.NewGuid() + "-" + file.FileName;
notice.ImagePath = Server.MapPath(Path.Combine("~/uploads/notice/" + fileName));
file.SaveAs(notice.ImagePath);
}
if (notice.Id == 0)
{
//notice.DatePosted = DateTime.Now;
_context.Notice.Add(notice);
}
else
{
_context.Entry(notice).State = EntityState.Modified;
//var noticeInDb = _context.Notice.Single(n => n.Id == notice.Id);
//notice.Title = noticeInDb.Title;
//notice.Description = noticeInDb.Description;
//notice.ImagePath = noticeInDb.ImagePath;
//notice.IsPublic = noticeInDb.IsPublic;
}
//_context.Notice.Add(notice);
_context.SaveChanges();
return View("Index", _context.Notice);
}
和索引控制器:包括将 College 属性 设置为通知模型的方法。
// GET: Notice
public ActionResult Index()
{
var model = _context.Notice.Include(i => i.College);
return View(model);
}