EntityFramework 6 AddOrUpdate不使用复合或复合主键

时间:2014-03-09 20:38:59

标签: c# sql sql-server entity-framework foreign-keys

这个问题一直是我周末的噩梦......我有一张表AddOrUpdate无法正常工作,它一直在添加,但从不更新。

我想要做的就是当我使用AddOrUpdate向表中添加新实体时,我希望它检查AppointmentIdCompletionCodeId列以及它们是否匹配而不是更新,否则添加。

表格结构:

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));

^^不确定这是否正确。

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

方法

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

1 个答案:

答案 0 :(得分:17)

您错过了AddOrUpdate的{​​{3}}:

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