Home > Software engineering >  Error when modifying a primary key as a foreign key
Error when modifying a primary key as a foreign key

Time:10-03

I have a primary key as a foreign key in Entity Framework.

public class RailcarTrip
{
    [Key, ForeignKey("WaybillRailcar")]
    public int WaybillRailcarId { get; set; }
    public WaybillRailcar WaybillRailcar { get; set; }

    // Etc.
}

This seems to work fine, and generates the following table.

CREATE TABLE [dbo].[RailcarTrips](
    [WaybillRailcarId] [int] NOT NULL,
    [StartDate] [datetime2](7) NOT NULL,
    [DeliveryDate] [datetime2](7) NULL,
    [ReleaseDate] [datetime2](7) NULL,
    [ReturnDate] [datetime2](7) NULL,
    [DeliveryEta] [datetime2](7) NULL,
    [ReleaseEta] [datetime2](7) NULL,
    [ReturnEta] [datetime2](7) NULL,
    [ReturnCity] [nvarchar](80) NULL,
    [ReturnState] [nvarchar](2) NULL,
    [TripType] [int] NOT NULL,
 CONSTRAINT [PK_RailcarTrips] PRIMARY KEY CLUSTERED 
(
    [WaybillRailcarId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[RailcarTrips]  WITH CHECK ADD  CONSTRAINT [FK_RailcarTrips_WaybillRailcars_WaybillRailcarId] FOREIGN KEY([WaybillRailcarId])
REFERENCES [dbo].[WaybillRailcars] ([Id])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[RailcarTrips] CHECK CONSTRAINT [FK_RailcarTrips_WaybillRailcars_WaybillRailcarId]
GO

But I get an error when I try to change this PK/FK so that it references a different record.

The property 'RailcarTrip.WaybillRailcarId' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key, first delete the dependent and invoke 'SaveChanges', and then associate the dependent with the new principal.

I don't understand why this is a problem? The primary key is not set as an entity/autoset. This code should be a simple update of a FK. I don't want to have to delete anything. Can anyone explain why it's an issue?

This appears to be an Entity Framework error and not a SQL Server error.

CodePudding user response:

EF doesn't support modifying primary keys. So you need to delete and insert (Remove SaveChanges Add SaveChanges) the RailCarTrip to move it to a different WaybillRailcar. Alternatively you can update the PK/FK directly in TSQL.

CodePudding user response:

If I understood You correctly, that is that you want to change the value of primary key of your entity (RailcarTrip), than You have answered Your own question - EF is informing you, that primary key is not a modifiable value, which is correct for SQL database. It does not matter if this key is also a foreign key. To modify a primary key value one has to delete corresponding entry and recreate it with new key value.

  • Related