EntityFramework 6 AddOrUpdate无法使用复合或复合主键 [英] EntityFramework 6 AddOrUpdate not working with compound or composite primary key

查看:375
本文介绍了EntityFramework 6 AddOrUpdate无法使用复合或复合主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是我的周末恶梦...我有一张表,其中 AddOrUpdate 无法正常工作,它不断添加,但永远不会更新。

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

所有我想做的是当我使用 AddOrUpdate 添加一个新的实体到表中时,我想要查看 AppointmentId CompletionCodeId 列,如果匹配比更新,否则添加。

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.

表格结构:

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

方法

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


推荐答案

你错过了 AddOrUpdate

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

这篇关于EntityFramework 6 AddOrUpdate无法使用复合或复合主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆