473,566 Members | 3,309 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint

2 New Member
I have a problem and I don't know why am I getting this bug.

Expand|Select|Wrap|Line Numbers
  1. CREATE TABLE Course(
  2.     IdCourse int IDENTITY (1,1) NOT NULL PRIMARY KEY,
  3.     NameCourse nvarchar(50) NOT NULL,
  4.     Description nvarchar(250) NOT NULL,
  5.     Date datetime NOT NULL,
  6.     Full BIT NULL DEFAULT 0
  7. )
  8.  
  9. CREATE TABLE Application
  10. (
  11.     IdApplication int IDENTITY (1,1) NOT NULL PRIMARY KEY,
  12.     Date datetime NOT NULL,
  13.     Name nvarchar(25) NOT NULL,
  14.     Surname nvarchar(25) NOT NULL,
  15.     Adress nvarchar(50) NOT NULL,
  16.     Email nvarchar(320) NOT NULL,
  17.     Telephone varchar(15) NOT NULL,
  18.     IdCourse int FOREIGN KEY REFERENCES Course(IdCourse),
  19.     Status INT not nulL
  20. )
  21.  
  22.  
  23. public ActionResult Application(int id)
  24.         {
  25.             ViewBag.Course = (
  26.                 from c in db.Course
  27.                 where c.IdCourse == id
  28.                 select s.NameCourse).FirstOrDefault();
  29.             Application application = new Application();
  30.             return View(application);
  31.         }
  32.  
  33. [HttpPost]
  34.         [ValidateAntiForgeryToken]
  35.         public ActionResult Application([Bind(Include = "IdApplication,Name,Surname,Adress,Email,Telephone")] Application application)
  36.         {
  37.             Course course = new course();
  38.             application.IdCourse = course.IdCourse;
  39.             int applicationId = application.IdApplication;
  40.  
  41.             if (ModelState.IsValid)
  42.             {
  43.                 db.Applications.Add(Application);
  44.                 db.SaveChanges();
  45.                 return RedirectToAction("Index");
  46.             }
  47.  
  48.             return View(application);
  49.         }
  50.  
My view
Expand|Select|Wrap|Line Numbers
  1. @model Aplikacija.Models.Applicaton
  2.  
  3. @{
  4.     <strong>@ViewBag.Course</strong>
  5. }
  6.  
  7.  
  8. @using (Html.BeginForm())
  9. {
  10.     @Html.AntiForgeryToken()
  11.  
  12.     <div class="form-horizontal"> <hr />
  13.         @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  14.         @Html.HiddenFor(model => model.IdApplication)
  15.  
  16.         <div class="form-group">
  17.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
  18.             <div class="col-md-10">
  19.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
  20.                 @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
  21.             </div> </div> <div class="form-group">
  22.             @Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
  23.             <div class="col-md-10">
  24.                 @Html.EditorFor(model => model.Surname, new { htmlAttributes = new { @class = "form-control" } })
  25.                 @Html.ValidationMessageFor(model => model.Surname, "", new { @class = "text-danger" })
  26.             </div> </div> <div class="form-group">
  27.             @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
  28.             <div class="col-md-10">
  29.                 @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
  30.                 @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
  31.             </div> </div> <div class="form-group">
  32.             @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
  33.             <div class="col-md-10">
  34.                 @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
  35.                 @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
  36.             </div> </div> <div class="form-group">
  37.             @Html.LabelFor(model => model.Telephone, htmlAttributes: new { @class = "control-label col-md-2" })
  38.             <div class="col-md-10">
  39.                 @Html.EditorFor(model => model.Telephone, new { htmlAttributes = new { @class = "form-control" } })
  40.                 @Html.ValidationMessageFor(model => model.Telephone, "", new { @class = "text-danger" })
  41.             </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-primary" /> </div> </div> </div>
  42. }
  43.  
  44. <div>
  45.     @Html.ActionLink("Back to List", "Index")
  46. </div>
  47.  
  48. @section Scripts {
  49.     @Scripts.Render("~/bundles/jqueryval")
  50. }
Jun 8 '19 #1
2 2337
zmbd
5,501 Recognized Expert Moderator Expert
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint
Is that the full error message?

Typically, this would indicate that you have a value in the column for the foreign key reference to another table that is not also in the primary key column of the referenced table.

Without the full error message that's about as far as we can offer...
Jun 9 '19 #2
ezra89
2 New Member
I changed my HttpPost and there is no exception anymore. It just gives me new id of the Course table and I don't want that. I need to place it in the row that I chose in ViewBag from GET.

Expand|Select|Wrap|Line Numbers
  1. [HttpPost]
  2.         [ValidateAntiForgeryToken]
  3.         public ActionResult Application(Application application)
  4.         {
  5.             application.Course = new Course();
  6.             if (ModelState.IsValid)
  7.             {
  8.                 db.Applications.Add(application);
  9.                 db.SaveChanges();
  10.                 return RedirectToAction("Index");
  11.             }
  12.  
  13.             ViewBag.Course = new SelectList(db.Courses, "IdCourse", "NameCourse", application.IdCourse);
  14.             return View(application);
  15.         }
Thank you for your reply.
Jun 10 '19 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

3
3831
by: J. Muenchbourg | last post by:
The block of code below shows how I am inserting field values into my dbase table: strSQLStatement = "INSERT INTO tblArticles (handid,ArticleDate,sport,articleheader, fpick,articleText) "_ & "SELECT '" & handid & "' As handid, '" _ & ArticleDate & "' As ArticleDate, '" _ & sport & " As sport, " _ & articleheader & "' As articleheader, '"...
2
12953
by: Tim::.. | last post by:
Can someone please tell me why I keep getting the following error from the code below! Error: INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK_tblOfficePageContent_tblPageContent'. The conflict occurred in database 'CPNCMS', table 'tblPageContent', column 'pageID'. The statement has been terminated. I cant seem to see...
2
3179
by: Geoffrey KRETZ | last post by:
Hello, I'm wondering if the following behaviour is the correct one for PostGreSQL (7.4 on UNIX). I've a table temp_tab with 5 fields (f1,f2,f3,...),and I'm a launching the following request : INSERT INTO temp_tab VALUES (1,2,3)
0
1976
by: macupryk | last post by:
{System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ProjectResponse__ProjectQuestionId". The conflict occurred in database "RG_ProjectData", table "dbo.ProjectQuestion", column 'ProjectQuestionId'. The statement has been terminated. public void ProjectResponseandRespondentToDB(DataRow...
1
21035
by: filip1150 | last post by:
I'm trying to find if there is any performance diference between explicitly using a sequence in the insert statement to generate values for a column and doing this in an insert trigger. I noticed that th eaccess plan for the 2 situations is quite different. For the case where the trigger is in place, the optimizer applies 2 extra residual...
3
45318
by: weird0 | last post by:
I have two tables accounts and ATM and i am trying to insert a tuple in ATM with accountId as foreign key. But even this simple work,I encounter the following error: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ATM_Accounts". The conflict occurred in database "G:\DOCUMENTS AND...
3
7241
by: haiminnu | last post by:
I have created Two tables 1]EmployeeTable -------------------------- EmpID EmpName AccessLevelID 2]AccessLevelTable -----------------------------
2
7327
by: ksenthilbabu | last post by:
Hey All, I am using MSSQL -2005 with VB6. I have created a master table tblCompany and detail Table tblDetail having foreign key relationship. When i try to insert a value within a TRANSACTION I am getting Error No. -2147217873 at Line No. 0 (The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tblDetail_tblCompany". The...
1
3816
by: bougie | last post by:
i have two tables projects and proposals in project I have column ID and in proposal I have column ID too and there is a one to one realtionship between these tables the primary key in this realtion is the project.ID and foreign key is in proposal.ID and thses tow column proposal.ID and project.id does not allow null. the problem is there is...
2
15346
by: Good Guy | last post by:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Customers_Contact". The conflict occurred in database "BreakAway", table "dbo.Contact", column 'ContactID'. The statement has been terminated. Hi, all. This is my maiden post. Some background: I am doing a C# project using Entity Framework 4.0 in Visual Studio 2010 and SQL...
0
7673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7893
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8109
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7953
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6263
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1202
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.