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

这个问题一直是我周末的噩梦…我有一个表,其中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 appointmentCodes) { appointmentCodes.ForEach(x => _appointmentCodeRepository.AddOrUpdate(x)); } 

您错过了AddOrUpdate 重载 :

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