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

时间:2018-03-30 19:03:20

标签: c# asp.net-mvc entity-framework ef-code-first

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

  

INSERT语句与FOREIGN KEY约束冲突   " FK_dbo.Notices_dbo.Colleges_CollegeId&#34 ;.冲突发生在   数据库" aspnet-QuickPly5-20180306011920",表" dbo.Colleges",   专栏' Id'。

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

Collge.cs

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        menubar = MenuBar(self)
        self.config(menu=menubar)

        tk.Tk.wm_title(self, "SampleAPP")
        tk.Tk.iconbitmap(self, default="image/sample.ico")

        container = tk.Frame(self)
        container.grid(sticky="nsew")
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (LoginPage, PatternCPage, PatternManagerPage, MenuPage):

            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(LoginPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

class MenuBar(tk.Menu):

    def __init__(self, parent):
        tk.Menu.__init__(self, parent)

        self.create_menu = tk.Menu(tearoff=0)
        self.manager_menu = tk.Menu(tearoff=0)
        self.add_cascade(label="One", menu=self.create_menu, state="disabled")
        self.add_cascade(label="Two", menu=self.manager_menu, state="disabled")

        self.create_menu.add_command(label="1")
        self.create_menu.add_command(label="2")
        self.create_menu.add_command(label="3")
        self.manager_menu.add_command(label="1")
        self.manager_menu.add_command(label="2")
        self.manager_menu.add_command(label="3")

    def enable_menu(self):
        self.entryconfig("One", state="normal")


class LoginPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.controller = controller

        self.label_username = tk.Label(self, text="Username:: ")
        self.label_password = tk.Label(self, text="Password: ")

        self.entry_username = tk.Entry(self)
        self.entry_password = tk.Entry(self, show="*")
        self.label_username.grid(row=1, column=4, sticky="e")
        self.label_password.grid(row=2, column=4, sticky="e")
        self.entry_username.grid(row=1, column=5, )
        self.entry_password.grid(row=2, column=5, )
        self.entry_username.bind('<Return>', self.login_btn_clicked)
        self.entry_password.bind('<Return>', self.login_btn_clicked)


        self.logbtn = ttk.Button(self, text="Login", command=self.login_btn_clicked)
        self.logbtn.grid(columnspan=10)
        self.logbtn.bind('<Return>', self.login_btn_clicked)


    def database(self):
        self.connection = mysql.connector.connect(user='sample', password='sample',
                                  host='samplehost',
                                  database='sampledb')

        self.cursor = self.connection.cursor()


    def login_btn_clicked(self, event=None):

        self.database()

        # print("Clicked")
        username = self.entry_username.get()
        password = self.entry_password.get()

        # print(username, password)

        if username == "" or password == "":
            tm.showerror("Error", "Empty fields")

        else:
            self.query = ("SELECT * FROM user_db WHERE username=%s AND password=%s")
            self.cursor.execute(self.query, (username, password))
            self.result = self.cursor.fetchall()
            self.cursor.close()

            if len(self.result) > 0:
                tm.showinfo("Access granted", "Logged in!")

                self.controller.show_frame(MenuPage)
                self.controller.enable_menu()

                self.entry_password.delete(0, "end")

            else:
                tm.showerror("Access denied", "Invalid login data")

app = SampleApp()
app.mainloop()

Notice.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; }

}

NoticeController.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; }

    }

表格定义

通知

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

医学院

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

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

我不明白我做错了什么。

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

Debug window screenshot

2 个答案:

答案 0 :(得分:0)

将您的大学课程和通知课程放入这样的课程:

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)

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

创建视图:

@model stackoverflowquestion1.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属性设置为Notice Model。

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

            return View(model);
        }