INSERT语句与FOREIGN KEY冲突,但调试窗口显示正确的值

时间:2022-09-26 08:26:04

Hello guys I am new with asp.net mvc ANDcurrently working on my college project which is a college portal and using entity framework code first approach. However I am getting an error **

大家好,我是asp.net mvc的新手,目前在我的大学项目中工作,这是一个大学门户网站,并使用实体框架代码第一种方法。但是我收到错误**

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'.

INSERT语句与FOREIGN KEY约束“FK_dbo.Notices_dbo.Colleges_CollegeId”冲突。冲突发生在数据库“aspnet-QuickPly5-20180306011920”,表“dbo.Colleges”,列“Id”中。

** I searched the whole web for solution everyone of them suggests that the value to be inserted should be present in primary table before entering data to the foreign key table. My model classes are as follows

**我在整个网络上搜索解决方案,他们每个人都建议在将数据输入外键表之前,要插入的值应该存在于主表中。我的模型类如下

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 Definition

Notice

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);

College

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)
);

when i run the application normally i get the exception from the title but in the debug window when i checked it showed CollegeId = 1 (only have one row in the table) and NoticeId = 6 (have few notices already). I can correctly add data to the table manually without getting any error.

当我正常运行应用程序时,我从标题中获取异常但在调试窗口中,当我检查它时显示CollegeId = 1(表中只有一行)和NoticeId = 6(已经没有通知)。我可以手动正确地向表中添加数据而不会出现任何错误。

I don't understand what i am doing wrong.

我不明白我做错了什么。

Thanks in advance. (sorry for my English)

提前致谢。 (对不起我的英语不好)

Debug window screenshot

调试窗口截图

2 个解决方案

#1


0  

I think your problem from view. I rewrite code. And It works following code.

我认为你的问题来自于观点。我重写了代码。它遵循代码。

CREATE VIEW:

@model *question1.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")
}

And I changed code:

我改变了代码:

[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);
        }

And Index controllers: Include methods set College property to Notice Model.

和索引控制器:包含方法将College属性设置为Notice Model。

// GET: Notice
        public ActionResult Index()
        {
            var model = _context.Notice.Include(i => i.College);

            return View(model);
        }

#2


0  

Put in your College class and Notice class like this:

把你的大学课和通知课放在这样的:

public class College
{
 //...

 public ICollection<Notice> Notice{ get; set; }

}

public class Notice
{
 //...

 [ForeignKey("College")]
 public int CollegeId { get; set; }
 public College College { get; set; }
}

#1


0  

I think your problem from view. I rewrite code. And It works following code.

我认为你的问题来自于观点。我重写了代码。它遵循代码。

CREATE VIEW:

@model *question1.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")
}

And I changed code:

我改变了代码:

[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);
        }

And Index controllers: Include methods set College property to Notice Model.

和索引控制器:包含方法将College属性设置为Notice Model。

// GET: Notice
        public ActionResult Index()
        {
            var model = _context.Notice.Include(i => i.College);

            return View(model);
        }

#2


0  

Put in your College class and Notice class like this:

把你的大学课和通知课放在这样的:

public class College
{
 //...

 public ICollection<Notice> Notice{ get; set; }

}

public class Notice
{
 //...

 [ForeignKey("College")]
 public int CollegeId { get; set; }
 public College College { get; set; }
}