.netentity-frameworkt-sqlasp.net-coreidentity-insert

Entity Framework update row while excluding IDENTITY column


I'm trying to update a row while ignoring the identity column that exists in the database.

On update I get the following error:

_context.Entry(existingEvent).Property(x => x.ReferenceNumber).IsModified = false;
_context.Events.Update(existingEvent);

Exception: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot update identity column 'ReferenceNumber'.

I also tried the following but that also results in an exception:

_context.Events.Update(existingEvent);
_context.Entry(existingEvent.ReferenceNumber).State = EntityState.Unchanged;

System.InvalidOperationException: The entity type 'int' was not found. Ensure that the entity type has been added to the model.

Table:

CREATE TABLE [DW].[Reporting]
(
    [ID] UNIQUEIDENTIFIER NOT NULL,
    [ReferenceNumber] INT NOT NULL IDENTITY(1,1) UNIQUE,
    [Date] DATETIME NOT NULL,
    [Address] VARCHAR(256) NOT NULL,
    [EventName] VARCHAR(256),
    [Subject] VARCHAR(512),
    [PhotographerID] UNIQUEIDENTIFIER,
    [CameraNumber] VARCHAR(24),
    [PictureAmount] INT,
    [NegativeID] UNIQUEIDENTIFIER,
    [CategoryID] UNIQUEIDENTIFIER,
    [People] VARCHAR(256),

    CONSTRAINT [PK_Reporting] PRIMARY KEY (ID),
    CONSTRAINT [UV_Reporting_Code] UNIQUE ([ReferenceNumber]),
    CONSTRAINT [FK_Reporting_Photographers_PhotographerID] 
        FOREIGN KEY ([PhotographerID]) REFERENCES [DW].[Photographers]([ID]),
    CONSTRAINT [FK_Reporting_Negatives_NegativeID] 
        FOREIGN KEY ([NegativeID]) REFERENCES [DW].[Negatives]([ID]),
    CONSTRAINT [FK_Reporting_Categories_CategoryID] 
        FOREIGN KEY ([CategoryID]) REFERENCES [DW].[Categories]([ID])
)

Solution

  • You've just got the code reversed. Update() marks all the properties as Modified. If you want to exclude one, do it after.

    _context.Events.Update(existingEvent);
    _context.Entry(existingEvent).Property(x => x.ReferenceNumber).IsModified = false;