c# - EntityFramework 6 AddOrUpdate 不适用于复合或复合主键

标签 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));
}

最佳答案

您错过了 this overload AddOrUpdate 的:

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

关于c# - EntityFramework 6 AddOrUpdate 不适用于复合或复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22287852/

相关文章:

c# - 在 Delphi 2007 中使用 SDK BSOD 但在 C# 中工作的应用程序

sql - Postgresql - 查询问题

sql-server - 如何从 SQL Server Integration Services 目录导入包?

sql - 有人知道自动将一堆测试(虚拟)数据转储到 sql 数据库中的程序吗?

c# - PUT 时记录更改的最佳方法

c# - 检查 LINQ 查询是否返回行

mysql - 如何比较 SQL 中的 2 行并查看是否相同的 ID Like 彼此匹配?

sql-server - 新连接的 READPAST 锁问题

c# - 如何将调试文本从 C# 类发送到 ASP.NET 页面

sql - 有效识别差异