ASP.NET - The INSERT statement conflicted with the FOREIGN KEY constraint   ASP.NET - The INSERT statement conflicted with the FOREIGN KEY constraint "FK_organization

Asked By Ratandeep Gupta
09-Jun-10 06:24 PM
I wasn't getting this error before. But now when i try to add any more data, it gives me this error when i try to submit the changes to the database. The complete error is:
         
Line 220:                ndb.organizationHierarchies.InsertOnSubmit(noh);
Line 221:
Line 222:                ndb.SubmitChanges();
Line 223:
Line 224:                hfAddressID.Value = ab.addressID.ToString();

Source File: c:\Documents and Settings\!rdgupta\Desktop\padrap2_nocms\padrap\pages\admin\addNewPopup.aspx.cs    Line: 222

Stack Trace:

[SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_organizationHierarchy_organization1". The conflict occurred in database "padrap2", table "dbo.organization", column 'organizationID'.
The statement has been terminated.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1950890
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4846875
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +204
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +954
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
   System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +175
   System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +137
   System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +219
   System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +113
   System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +344
   System.Data.Linq.StandardChangeDirector.DynamicInsert(TrackedObject item) +67
   System.Data.Linq.StandardChangeDirector.Insert(TrackedObject item) +202
   System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +260
   System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) +331
   System.Data.Linq.DataContext.SubmitChanges() +19
   pages_admin_addNewPopup.save_btn_Click_subSite(Object sender, EventArgs e) in c:\Documents and Settings\!rdgupta\Desktop\padrap2_nocms\padrap\pages\admin\addNewPopup.aspx.cs:222
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

The aspx code which tries to add the data on the button click event is:
protected void  save_btn_Click_subSite(object sender, EventArgs e)
    {
            P*********** ndb = new P*********();
            //organizationAddress noa = new organizationAddress();
            organization norg = new organization();
            organizationHierarchy noh = new organizationHierarchy();
             
            int organizationID;
 
            int _addressID = 0;
 
            int.TryParse(hfAddressID.Value, out _addressID);
 
            string _line1 = tbrAddressID1.Text;
            string _line2 = tbrAddressID2.Text;
            string _line3 = tbrAddressID3.Text;
            string _city = tbrCity.Text;
            string _stateCode = ddlStateID.SelectedValue;
            string _countryISO2 = ddlCountryID.SelectedValue;
            string _postalCode = tbrPostalCode.Text;
 
            norg.name = tbNameID.Text;
            organizationID = ndb.organizations.Max(c=>c.organizationID) +1;
            norg.baseID = organizationID;
            norg.organizationID = organizationID;
            int temp = this.OrganizationID;
            string nqry = string.Format(@"
SELECT org.organizationTypeID
FROM
    organization org 
WHERE
    org.organizationID = {0}
", this.OrganizationID);
            norg.organizationTypeID =  ndb.ExecuteQuery<int>(nqry).FirstOrDefault();
            norg.dateCreated = DateTime.Now;
           // norg.createdBy_luserID = 1;
            norg.isActive = true;
            noh.child_organizationID = organizationID;
            noh.parent_organizationID = this.OrganizationID;
            if (cbVerify.Checked)
            {
                JObject jPlacemark = JObject.Parse(ddlVerifySS.SelectedValue);
 
                JsonSerializerSettings jss = new JsonSerializerSettings();
 
                GPlacemark mark = JsonConvert.DeserializeObject<GPlacemark>(ddlVerifySS.SelectedValue, jss);
 
                if (mark != null && mark.AddressDetails != null && mark.AddressDetails.Country != null)
                {
                    GCountry _country = mark.AddressDetails.Country;
 
                    _line2 = "";
                    _line3 = "";
                    _countryISO2 = _country.CountryNameCode;
 
                    if (_country.AdminstrativeArea != null)
                    {
                        _stateCode = _country.AdminstrativeArea.AdministrativeAreaName;
                        GAdministrativeArea _aa = _country.AdminstrativeArea;
 
                        if (_aa.SubAdministrativeArea != null && _aa.SubAdministrativeArea != null)
                        {
                            GLocality _locality = _aa.SubAdministrativeArea.Locality;
 
                            _city = _locality.LocalityName;
                            _postalCode = _locality.PostalCode.PostalCodeNumber;
 
                            if (_locality.Thoroughfare != null)
                                _line1 = _locality.Thoroughfare.ThoroughfareName;
                        }
                    }
 
                }
            }
            var qry = from a in ndb.addresses
                      where
                        (a.addressLine1 == _line1 || string.IsNullOrEmpty(_line1))
                        &&
                        (a.addressLine2 == _line2 || string.IsNullOrEmpty(_line2))
                        &&
                        (a.addressLine3 == _line3 || string.IsNullOrEmpty(_line3))
                        &&
                        (a.city == _city || string.IsNullOrEmpty(_city))
                        &&
                        (a.stateCode == _stateCode || string.IsNullOrEmpty(_stateCode))
                        &&
                        (a.countryISO2 == _countryISO2 || string.IsNullOrEmpty(_countryISO2))
                        &&
                        (a.postalCode == _postalCode || string.IsNullOrEmpty(_postalCode))
                      select a;
 
            int count = qry.Count();
 
            if (count > 0)
            {
                address ab = qry.First();
 
                if (ab.addressID.ToString() != hfAddressID.Value) // then it's a different address already in the system
                {
                    hfAddressID.Value = ab.addressID.ToString();
                }
            }
            else // it's new and we need to add it
            {
                address ab = new address();
 
                if (!string.IsNullOrEmpty(_line1))
                    ab.addressLine1 = _line1;
                if (!string.IsNullOrEmpty(_line2))
                    ab.addressLine2 = _line2;
                if (!string.IsNullOrEmpty(_line3))
                    ab.addressLine3 = _line3;
 
                if (!string.IsNullOrEmpty(_city))
                    ab.city = _city;
                if (!string.IsNullOrEmpty(_stateCode))
                    ab.stateCode = _stateCode;
                if (!string.IsNullOrEmpty(_countryISO2))
                    ab.countryISO2 = _countryISO2;
                if (!string.IsNullOrEmpty(_postalCode))
                    ab.postalCode = _postalCode;
 
                ndb.addresses.InsertOnSubmit(ab);
                ndb.organizations.InsertOnSubmit(norg);
                ndb.organizationHierarchies.InsertOnSubmit(noh);
 
                ndb.SubmitChanges();
 
                hfAddressID.Value = ab.addressID.ToString();
 
                vw_address view = ndb.vw_addresses.SingleOrDefault(add => add.addressID == ab.addressID);
 
                var responseJSON = GGeocode.GetLocation(view.address);
 
                JObject obj = JObject.Parse(responseJSON);
            }
            ndb.Dispose();
            Server.Transfer("********.aspx", false);
        }

Can somebody explain to me why I started getting this error and how to solve it.

Thanks.
  Mash B replied to Ratandeep Gupta
10-Jun-10 12:51 AM
You are trying to insert a record with a key which doesn't exist in the parent (or related) table.
Just cross verify the ID your are passing is correct ( means should present in referencing table)
  Sara J replied to Ratandeep Gupta
10-Jun-10 01:00 AM
It looks like forienkey referenced by your organizationHierarchy table insert statement already exists and violates the contraints.

Check your table and verify whether you have the key exists already. If not if you are doign batch update make sure you are not duplicate rows.
  Ratandeep Gupta replied to Sara J
10-Jun-10 04:01 PM
Okay, on further debugging I found out that organization hierarchy table was having problem and when i tried to submit to database without altering or adding anything to OrganizationHierarchy, it worked, but since the organization and address tables have their identity set to true, the new ID's that they got was 9 higher than the last one. So, somehow, while developing and testing, I ended up making duplicate values, but I cant see them in the database. how do I solve this issue?

thanks
  Ratandeep Gupta replied to Sara J
10-Jun-10 04:23 PM
Ok i got it.. Thanks folks!
Create New Account
help
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4856715 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1121 System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) +192 System.Data.SqlClient 37 System.Web.UI.WebControls.ImageButton.OnCommand(CommandEventArgs e) +111 System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +176 System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +82 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +346 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +3244 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +186 System 56 System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +107 System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +176 System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +31 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +32 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +244 System.Web.UI
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +800131 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +186 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1932 System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +33 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin 36 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI
SqlClient.TdsParser.ThrowExceptionAndWarning() +234 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275 System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33 System.Data.SqlClient.SqlDataReader.get_MetaData() +86 System 34 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563 Version Information