MsDotNet raja

MsDotNet raja

  • NA
  • 10
  • 2.4k

Insert records into table which has foreign key relationship

Mar 31 2016 9:56 AM
Hi, i have two tables as
 
Event_Schedule:
*Event_Schedule_Id( Auto Inc PK)
*Event_Id(FK)
*Title
 
Event_Create:
*Event_Id(Auto Inc PK) 
*Event_Name 
 
I am using Linq to insert data into Event_Schedule based on Event_Id. Before that I need to select the  Event_Name from dropdownlist. On selecting Event_Name, the particular records of Event shud be fall using Event_Id(it is not getting). And I am unable to insert the data, it is hitting the error as "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Event_Schedules_Event_Create". The conflict occurred in database "XYZ_Database", table "dbo.Event_Create", column 'Event_Id'." please help me to resolve this issue(also help with the updating record), its an urgent help. Thanks in Advance.
 
My Insert Code is as follows:
 
using (XYZ dbContext = new XYZ())
{
TextBox txtName = (TextBox)gridEventSched.FooterRow.FindControl("txt_Name_insert");
TextBox txtStarttime = (TextBox)gridEventSched.FooterRow.FindControl("txt_Stime_insert");
TextBox txtEndtime = (TextBox)gridEventSched.FooterRow.FindControl("txt_Etime_insert");
TextBox txtCreatedBy = (TextBox)gridEventSched.FooterRow.FindControl("txt_Cby_insert");
Event_Schedule evntSch = new Event_Schedule();
evntSch.Title = txtName.Text;
evntSch.Starttime = Convert.ToDateTime(txtStarttime.Text);
evntSch.Endtime = Convert.ToDateTime(txtEndtime.Text);
evntSch.CreatedBy = txtCreatedBy.Text;
// Insert into database
dbContext .Event_Schedules.InsertOnSubmit(evntSch);
dbContext .SubmitChanges();
// Refresh Gridview for reflecting new row
BindGridView();
}
 

Answers (2)