Конфликт инструкции update с ограничением foreign key

Recently I tried to add a one-to-many relationship in my MVC application via Entity Framework Code First. I added the relationship to bind an Administrator name from a dropdown list to the current application that is being filled out. So I have one table for the administrator names and one for the actual application information. The application and dropdown list of admin names seem to work fine and all information is going into my database on submit, but when I try to Edit the application, I get the following error:

The UPDATE statement conflicted with the FOREIGN KEY constraint The conflict occurred in database table «dbo.Administrator», column ‘AdministratorId’

I’ve tried setting my Id columns to «Not Null», but this did not solve the issue.

Model:

public class Administrator
{

    public int AdministratorId{ get; set; }
    public string AdministratorName{ get; set; }

}

public class Application
{
    public Application()
    {
        GetDate = DateTime.Now;
    }

    public int ApplicationId { get; set; }

    [DisplayName("Marital Status")]
    public bool? MaritalStatus { get; set; }

    [Required]
    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [DisplayName("Middle Initial")]
    public string MiddleInitial { get; set; }
     [Required]
    [DisplayName("Last Name")]
    public string LastName { get; set; }

    [DisplayName("Date Submitted")]
    public DateTime GetDate { get; set; }

    public int AdministratorId{ get; set; }

    public virtual Administrator Administrator{ get; set; }
}

Controller (Index):

 public ActionResult Index()
    {
        ViewBag.LoanOfficerId = new SelectList(db.Administrators, "AdministratorId", "AdministratorName");
        return View();
    }

    // POST: Applications/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index([Bind(Include = "AdministratorId,FirstName,MiddleInitial,LastName,")] Application application)
    {



        if (ModelState.IsValid)
        {
ViewBag.AdministratorId= new SelectList(db.Administrators, "AdministratorId",     "AdministratorName", application.Administrator);
            db.Applications.Add(application);
            db.SaveChanges();

            return RedirectToAction("Thanks");
        }


        return View(application);
    }

I have a table called patient_address, which reference a PK key in patient table. But if I try to run one of the following statements :

update patient set id_no='7008255601088' where id_no='8008255601089'
update patient_address set id_no='7008255601088' where id_no='8008255601089'

I get this error message:

«The UPDATE statement conflicted with the REFERENCE constraint
«FK__patient_a__id_no__27C3E46E». The conflict occurred in database
«PMS», table «dbo.patient_address», column ‘id_no’.» or «The
UPDATE statement conflicted with the FOREIGN KEY constraint
«FK__patient_a__id_no__27C3E46E». The conflict occurred in database
«PMS», table «dbo.patient», column ‘id_no’.» .

Does any body know the possible cause ? Thanks.

MackM's user avatar

MackM

2,9065 gold badges31 silver badges45 bronze badges

asked May 25, 2014 at 14:39

chosenOne Thabs's user avatar

chosenOne ThabschosenOne Thabs

1,4803 gold badges21 silver badges39 bronze badges

5

This error is encountered when the primary key of a table is updated but it is referenced by a foreign key from another table and the update specific is set to No action. The No action is the default option.

If this is your case and No action is set on the update operation you can change the foreign-key definition to Cascade.

Right click your foreign key and select Modify. In the Foreign key relationships dialog under the INSERT and UPDATE specifics set the UPDATE rule on Cascade:

enter image description here

You can also set the rule using T-SQL:

ALTER TABLE YourTable
DROP Constraint Your_FK
GO

ALTER TABLE YourTable
ADD CONSTRAINT [New_FK_Constraint]
FOREIGN KEY (YourColumn) REFERENCES ReferencedTable(YourColumn)
ON DELETE CASCADE ON UPDATE CASCADE
GO 

Hope this helps

answered May 25, 2014 at 15:14

Milica Medic Kiralj's user avatar

5

If you don’t want to change your table structure, you can run the following query:

ALTER TABLE [UserStore] 
NOCHECK CONSTRAINT FK_UserStore_User_UserId

ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT  FK_UserIdentity_User_UserId

BEGIN TRAN

UPDATE  [user] 
SET Id = 10
WHERE Id = 9

UPDATE  [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9

UPDATE  [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9

COMMIT TRAN

ALTER TABLE [UserStore] 
CHECK CONSTRAINT FK_UserStore_User_UserId

ALTER TABLE UserIdentity 
CHECK CONSTRAINT FK_UserIdentity_User_UserId

answered Jul 11, 2019 at 21:12

Bartho Bernsmann's user avatar

Bartho BernsmannBartho Bernsmann

2,3931 gold badge25 silver badges34 bronze badges

It sometimes happens when you try to Insert/Update an entity while the foreign key that you are trying to Insert/Update actually does not exist. So, be sure that the foreign key exists and try again.

answered Feb 6, 2019 at 10:06

Masoud Darvishian's user avatar

In MySQL

set foreign_key_checks=0;

UPDATE patient INNER JOIN patient_address 
ON patient.id_no=patient_address.id_no 
SET patient.id_no='8008255601088', 
patient_address.id_no=patient.id_no 
WHERE patient.id_no='7008255601088';

Note that foreign_key_checks only temporarily set foreign key checking false. So it need to execute every time before update statement. We set it 0 as if we update parent first then that will not be allowed as child may have already that value. And if we update child first then that will also be not allowed as parent may not have that value from which we are updating. So we need to set foreign key check.
Another thing is that if you are using command line tool to use this query then put care to mention spaces in place where i put new line or ENTER in code. As command line take it in one line, so it may happen that two words stick as patient_addressON which create syntax error.

answered Aug 6, 2016 at 3:41

YATIN GUPTA's user avatar

This was the solution for me:

-- Check how it is now
select * from patient
select * from patient_address

-- Alter your DB
alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient 
set id_no='7008255601088'
where id_no='8008255601088'

alter table patient_address nocheck constraint FK__patient_a__id_no__27C3E46E
update patient_address 
set id_no='7008255601088'
where id_no='8008255601088'

-- Check how it is now
select * from patient
select * from patient_address

answered Nov 8, 2018 at 23:28

Francesco Mantovani's user avatar

Reason is as @MilicaMedic says. Alternative solution is disable all constraints, do the update and then enable the constraints again like this. Very useful when updating test data in test environments.

exec sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

update patient set id_no='7008255601088' where id_no='8008255601088'
update patient_address set id_no='7008255601088' where id_no='8008255601088'

exec sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

Source:

https://stackoverflow.com/a/161410/3850405

answered Apr 3, 2019 at 10:37

Ogglas's user avatar

OgglasOgglas

62.2k37 gold badges329 silver badges419 bronze badges

I would not change the constraints,
instead, you can insert a new record in the table_1 with the primary key (id_no = 7008255601088). This is nothing but a duplicate row of the id_no = 8008255601088. so now patient_address with the foreign key constraint (id_no = 8008255601088) can be updated to point to the record with the new ID(ID which needed to be updated), which is updating the id_no to id_no =7008255601088.

Then you can remove the initial primary key row with id_no =7008255601088.

Three steps include:

  1. Insert duplicate row for new id_no
  2. Update Patient_address to point to new duplicate row
  3. Remove the row with old id_no

answered Jan 15, 2016 at 18:14

Charan Raj's user avatar

Charan RajCharan Raj

4715 silver badges8 bronze badges

I guess if you change the id_no, some of the foreign keys would not reference anything, thus the constraint violation.
You could add initialy deffered to the foreign keys, so the constraints are checked when the changes are commited

jezzah's user avatar

jezzah

911 silver badge9 bronze badges

answered May 25, 2014 at 14:45

wastl's user avatar

wastlwastl

2,64314 silver badges27 bronze badges

3

The «UPDATE statement conflicted with the FOREIGN KEY constraint» error in SQL Server is a common issue faced by many database developers. This error occurs when an update operation is attempted on a table with a foreign key constraint, and the updated data violates the constraint. The foreign key constraint enforces referential integrity in the database by ensuring that the values in the referenced columns are valid and exist in the parent table.

Method 1: Check the Constraint

To fix the SQL error on update when encountering a FOREIGN KEY constraint, you can use the «Check the Constraint» method. This method involves checking the constraint that is causing the error and modifying it accordingly. Here are the steps to do this:

  1. Identify the constraint that is causing the error. This can be done by looking at the error message or by checking the table’s constraints.

  2. Check the constraint to see if it is set to «CASCADE». If it is, then the error is likely caused by a circular reference. In this case, you will need to modify the constraint to remove the circular reference.

  3. If the constraint is not set to «CASCADE», then you can modify the constraint to allow updates to the foreign key. This can be done using the «WITH CHECK CHECK» option.

Here is an example of how to modify a constraint to allow updates to the foreign key:

ALTER TABLE [dbo].[Orders] WITH CHECK CHECK CONSTRAINT [FK_Orders_Customers]

In this example, the «Orders» table has a foreign key constraint named «FK_Orders_Customers». The «WITH CHECK CHECK» option is used to modify the constraint to allow updates to the foreign key.

Here is another example of how to modify a constraint to remove a circular reference:

ALTER TABLE [dbo].[Orders] NOCHECK CONSTRAINT [FK_Orders_Customers]
ALTER TABLE [dbo].[Customers] NOCHECK CONSTRAINT [FK_Customers_Orders]
ALTER TABLE [dbo].[Orders] WITH CHECK CHECK CONSTRAINT [FK_Orders_Customers]
ALTER TABLE [dbo].[Customers] WITH CHECK CHECK CONSTRAINT [FK_Customers_Orders]

In this example, the «Orders» and «Customers» tables have foreign key constraints that reference each other. The «NOCHECK» option is used to temporarily disable the constraints, and then the constraints are modified to remove the circular reference using the «WITH CHECK CHECK» option.

By following these steps and modifying the constraint accordingly, you can fix the SQL error on update when encountering a FOREIGN KEY constraint.

Method 2: Use SET NULL or SET DEFAULT

To fix the SQL error on update when the UPDATE statement conflicts with the FOREIGN KEY constraint, you can use either SET NULL or SET DEFAULT. Here are the steps to do it:

  1. Identify the foreign key constraint that is causing the error. You can do this by looking at the error message or by querying the system tables.

  2. Determine whether you want to set the referencing column to NULL or to a default value. If you choose to set it to a default value, you need to define the default value first.

  3. Use the ALTER TABLE statement to modify the foreign key constraint and specify the ON UPDATE clause with either SET NULL or SET DEFAULT.

Here’s an example code for setting the referencing column to NULL:

ALTER TABLE [dbo].[ReferencingTable] 
  DROP CONSTRAINT [FK_ReferencingTable_ReferencedTable]

ALTER TABLE [dbo].[ReferencingTable] 
  WITH CHECK ADD CONSTRAINT [FK_ReferencingTable_ReferencedTable] 
  FOREIGN KEY([ReferencedColumn])
  REFERENCES [dbo].[ReferencedTable] ([ReferencedColumn])
  ON UPDATE SET NULL
  ON DELETE CASCADE

And here’s an example code for setting the referencing column to a default value:

ALTER TABLE [dbo].[ReferencingTable] 
  ADD CONSTRAINT [DF_ReferencingTable_ReferencedColumn] 
  DEFAULT ('DefaultValue') FOR [ReferencedColumn]

ALTER TABLE [dbo].[ReferencingTable] 
  DROP CONSTRAINT [FK_ReferencingTable_ReferencedTable]

ALTER TABLE [dbo].[ReferencingTable] 
  WITH CHECK ADD CONSTRAINT [FK_ReferencingTable_ReferencedTable] 
  FOREIGN KEY([ReferencedColumn])
  REFERENCES [dbo].[ReferencedTable] ([ReferencedColumn])
  ON UPDATE SET DEFAULT ('DefaultValue')
  ON DELETE CASCADE

Note that the ON DELETE clause is added for completeness. It specifies what action to take when the referenced row is deleted. In this example, it is set to CASCADE, which means that the referencing rows will also be deleted.

Method 3: Disable the Constraint and Re-enable it

To fix the «UPDATE statement conflicted with the FOREIGN KEY constraint» error in SQL Server, you can disable the constraint and re-enable it after the update is done. Here are the steps to do it:

-- Step 1: Disable the foreign key constraint
ALTER TABLE [child_table] NOCHECK CONSTRAINT [FK_child_table_parent_table]

-- Step 2: Update the child table
UPDATE [child_table] SET [column_name] = [new_value] WHERE [condition]

-- Step 3: Re-enable the foreign key constraint
ALTER TABLE [child_table] CHECK CONSTRAINT [FK_child_table_parent_table]

In the above code, replace [child_table], [FK_child_table_parent_table], [column_name], [new_value], and [condition] with the actual names and values for your database.

The NOCHECK CONSTRAINT statement disables the foreign key constraint, allowing you to update the child table without triggering the error. The CHECK CONSTRAINT statement re-enables the foreign key constraint after the update is done.

Note that disabling the constraint can lead to data integrity issues if you don’t handle it carefully. Make sure to test your code thoroughly and re-enable the constraint as soon as possible to avoid any potential problems.

That’s it! With these simple steps, you can fix the «UPDATE statement conflicted with the FOREIGN KEY constraint» error in SQL Server.

Method 4: Modify the Referenced Data

To fix the SQL error on update related to the FOREIGN KEY constraint, we can modify the referenced data. Here are the steps to do this:

  1. Identify the FOREIGN KEY constraint that is causing the error. This can be done by looking at the error message or by checking the table schema.

  2. Find the table that is referenced by the FOREIGN KEY constraint. This is the table that needs to be modified.

  3. Update the referenced data in the table to match the new values in the referencing table. This can be done using an UPDATE statement.

  4. Once the referenced data has been updated, retry the UPDATE statement that was causing the error.

Here is an example of how to modify the referenced data to fix the SQL error on update:

-- Identify the FOREIGN KEY constraint causing the error
ALTER TABLE dbo.Orders
ADD CONSTRAINT FK_Orders_Customers
FOREIGN KEY (CustomerID) REFERENCES dbo.Customers(CustomerID);

-- Find the referenced table
SELECT *
FROM dbo.Customers;

-- Update the referenced data
UPDATE dbo.Customers
SET CustomerID = 'C002'
WHERE CustomerID = 'C001';

-- Retry the UPDATE statement
UPDATE dbo.Orders
SET CustomerID = 'C002'
WHERE OrderID = 1;

In this example, we first identify the FOREIGN KEY constraint FK_Orders_Customers that is causing the error. We then find the referenced table dbo.Customers and update the CustomerID value from C001 to C002. Finally, we retry the UPDATE statement on the dbo.Orders table and it should now execute successfully.

Note that modifying the referenced data can have implications for other parts of the database, so it is important to fully understand the impact of any changes before making them.

Method 5: Use a Transaction

If you’re encountering the «UPDATE statement conflicted with the FOREIGN KEY constraint» error in SQL Server, you can use a transaction to fix it. Here are the steps:

  1. Begin a transaction using the BEGIN TRANSACTION statement.
  2. Update the parent table first before updating the child table to avoid the foreign key constraint error.
  3. Use the TRY...CATCH block to handle any errors that may occur during the transaction.
  4. If an error occurs, use the ROLLBACK TRANSACTION statement to undo the changes made in the transaction.
  5. If no error occurs, use the COMMIT TRANSACTION statement to commit the changes made in the transaction.

Here’s an example code:

BEGIN TRANSACTION;

BEGIN TRY
    UPDATE ParentTable
    SET Column1 = 'NewValue'
    WHERE ParentID = 1;

    UPDATE ChildTable
    SET Column2 = 'NewValue'
    WHERE ChildID = 1;
END TRY
BEGIN CATCH
    PRINT 'Error occurred: ' + ERROR_MESSAGE();
    ROLLBACK TRANSACTION;
END CATCH;

COMMIT TRANSACTION;

In this example, we first update the ParentTable before updating the ChildTable to avoid the foreign key constraint error. We also use a TRY...CATCH block to handle any errors that may occur during the transaction. If an error occurs, we print the error message and rollback the transaction. If no error occurs, we commit the changes made in the transaction.

Note that using a transaction can help you avoid the foreign key constraint error, but it may not always be the best solution. You should also consider other options such as disabling the constraint temporarily or updating the child table first if it makes sense in your specific scenario.

When I am trying to save Updated data in table using Entity Framework in ASP.NET MVC, I am getting the below error

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_CustomerProfileV2_IndustryList". 
The conflict occurred in database "CRM", table "dbo.IndustryList", column 'IndustryName'.
The statement has been terminated.

How can i Resolve the above issue?

Here is my Current sample code

 [HttpPost]
        public ActionResult EditCustomer(long customerProfileID, CustomerProfile model)
        {
            try
            {
                //code removed 

                crmdb.Entry(model).State = System.Data.Entity.EntityState.Modified;
                crmdb.SaveChanges(); //error here

               //some code removed
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString().Replace("n", "<br>"));
                return PartialView();
            }
        }

Any help is appreciated, thanks

Asked by:- jon

0

: 8770
At:- 4/2/2018 9:33:50 AM


2 Answers

As per your error details «The UPDATE
statement conflicted with the FOREIGN KEY constraint «FK_CustomerProfileV2_IndustryList». The conflict occurred
in database
«CRM», table
«dbo.IndustryList», column ‘IndustryName’. The statement has been terminated.
«

When you are submitting forms or updating the data, You have a field related to Table dbo.IndustryList with Columns name IndustryName, which cannot be empty due to Foreign key constraint.

So to simply resolve this error provide some value for IndustryName in your form

2

At:- 4/2/2018 11:29:46 AM

Above answer works in some cases but, this error can also occur when you try to update «Primary Key» of a table row but it is referenced by a foreign key from another table and the UPDATE SPECIFIC of table Reference is set to «No action».

So to remove this error, in your SSMS database table, you can simply right-click your foreign key and select Modify.

In the Foreign key relationships dialog under the «INSERT and UPDATE Specific» set the UPDATE rule =  Cascade (Instead of «No Action»)

You can also perform above operation using SQL Query

ALTER TABLE YourTable
DROP Constraint Your_FK
GO

ALTER TABLE YourTable
ADD CONSTRAINT [New_FK_Constraint]
FOREIGN KEY (YourColumn) REFERENCES ReferencedTable(YourColumn)
ON DELETE CASCADE ON UPDATE CASCADE
GO 

0

At:- 8/3/2021 3:29:06 PM
Updated at:- 8/3/2021 3:30:38 PM

Scenario:

You are working as SQL Server developer, You wrote an update statement for one of the table and getting below error.



Msg 547, Level 16, State 0, Line 32
The UPDATE statement conflicted with the REFERENCE constraint «FK_». 
The conflict occurred in database «YourDatabaseName», table «SchemaName.YourTableName», column ‘ColumnName’.
The statement has been terminated.

How to resolve this issue?

Solution:

Let’s create this error first by using below script. We are going to create two tables dbo.Customer and dbo.Orders. The tables has Primary-Foreign Key Relationship.

USE YourDatabaseName
GO

CREATE TABLE dbo.Customer (
    Customerid INT PRIMARY KEY
    ,FName VARCHAR(100)
    ,LName VARCHAR(100)
    ,SSN VARCHAR(10)
    )


    CREATE TABLE dbo.Orders (
    OrderId INT Identity(1, 1)
    ,OrderitemName VARCHAR(50)
    ,OrderItemAmt INT
    ,Customer_id INT FOREIGN KEY REFERENCES Customer(CustomerId)
    )


    --insert sample data
     insert into dbo.Customer 
    (CustomerId,FName, LName,SSN)
     values
    (1,'Aamir','Shahzad','000-000-00')

    insert into dbo.Orders
    (OrderItemName,OrderItemAmt,Customer_Id)
    values ('TV',1,1)


How to update record when Column is referenced by Foreign Key Constraint in SQL Server

Now let’s say if you feel that CustomerId value is incorrect in dbo.Customer and need to be updated. You wrote below update statement to update CustomerId to 100.

    update dbo.Customer
    set Customerid=100

You will get below error.

Msg 547, Level 16, State 0, Line 33

The UPDATE statement conflicted with the REFERENCE constraint «FK__Orders__Customer__1ED998B2». 

The conflict occurred in database «YourDatabaseName», table «dbo.Orders», column ‘Customer_id’.

The statement has been terminated.

As there is no Customer_id value=100 in dbo.Orders table, You can’t update the record in reference table. Now you thought that let’s fix the Parent table first ( dbo.Orders) and then I can update the dbo.Customer table.

    update dbo.Orders
    set Customer_Id=100



Again you got the error as shown below, because we don’t have CustomerId=100 available in dbo.Customer table.

Msg 547, Level 16, State 0, Line 36

The UPDATE statement conflicted with the FOREIGN KEY constraint «FK__Orders__Customer__1ED998B2».

 The conflict occurred in database «YourDatabaseName», table «dbo.Customer», column ‘Customerid’.

The statement has been terminated.

From here we can come with with multiple solutions

1) Instead of updating the record, Insert the record in Reference Table ( Dbo.Customer), Then update the record in Parent table (Dbo.Orders) and finally delete the existing records from Reference Table.

    --Insert Record in Reference Table First
     insert into dbo.Customer 
    (CustomerId,FName, LName,SSN)
     values
    (100,'Aamir','Shahzad','000-000-00')

    --Update the Records in Parent Table 
        update dbo.Orders
    set Customer_Id=100

    --Delete the old record from Reference Table
    Delete from dbo.Customer
    where CustomerId=1



Check the records in table now.

How to update Column Value when referenced by Foreign Key Constraint in SQL Server 

2) Disable the Foreign Key Constraint and Update the Values Manually

Another solution can be, disable the Foreign Key constraint, update the records and finally enable the Foreign key again.

--Find the Foreign Key Constraint with Table Name
    USE YourDatabaseName
    GO
    Select 
    Schema_name(Schema_id) as SchemaName,
    object_name(Parent_object_id) as TableName,
    name as ForeignKeyConstraintName
    from sys.foreign_keys


Disable the Foreign Key Constraint by using below statement

Syntax

ALTER TABLE SchemaName.ParentTableName

NOCHECK CONSTRAINT Constraint_Name

I used below statement to disable Foreign Key constraint on dbo.Orders table.

--Disable Foregin Key by using NOCHECK
ALTER TABLE dbo.Orders
NOCHECK CONSTRAINT FK__Orders__Customer__2A4B4B5E

--Run Update Statements
    update dbo.Customer
    set Customerid=100

    update dbo.Orders
    set Customer_Id=100

Enable Foreign Key Constraint Syntax

ALTER TABLE SchemaName.ParentTableName

CHECK CONSTRAINT Constraint_Name

I execute below script to Enable Foreign Key Constraint on dbo.Orders table.

--Enable Foreign Key Constraint by using CHECK
ALTER TABLE dbo.Orders
CHECK CONSTRAINT FK__Orders__Customer__2A4B4B5E

Video Demo : The UPDATE statement conflicted with the REFERENCE Constraint

Это тоже интересно:

  • Конфликт инструкции delete с ограничением reference sql
  • Конфликт инструкции alter table с ограничением foreign key как исправить
  • Конфидор экстра вдг инструкция по применению
  • Конфитюр из красной смородины на зиму пошаговая инструкция
  • Конфидор порошок инструкция по применению

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии