EntityFramework 6 AddOrUpdate not working with com

2020-08-17 03:43发布

问题:

The issue has been my weekend nightmare... I have a table where AddOrUpdate is not working correctly, it keeps adding but never updating.

All I want to do is when I add a new entity to the table using AddOrUpdate I want it to check the AppointmentId and CompletionCodeId columns and if they match than update, otherwise add.

Table structure:

CREATE TABLE [dbo].[AppointmentCodes] (
    [Id]               INT IDENTITY (1, 1) NOT NULL,
    [AppointmentId]    INT NOT NULL,
    [Quantity]         INT NOT NULL,
    [CompletionCodeId] INT NOT NULL,
    CONSTRAINT [PK_AppointmentCodes] PRIMARY KEY CLUSTERED ([Id] ASC, [AppointmentId] ASC));

^^ Not sure if that is even correct.

public void AddOrUpdate(T entity)
{
    //uses DbContextExtensions to check value of primary key
    _context.AddOrUpdate(entity);
    Commit();
}

METHOD

public void AddAppointmentCodes(List<AppointmentCode> appointmentCodes)
{
    appointmentCodes.ForEach(x => _appointmentCodeRepository.AddOrUpdate(x));
}

回答1:

You missed this overload of AddOrUpdate:

_context.AppointmentCodes
        .AddOrUpdate(a => new { a.AppointmentId, a.CompletionCodeId },
                     appointmentCodes.ToArray());