You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core调用SQL Server存储过程时GET请求报同键Id已添加错误

错误原因

你遇到的ArgumentException: An item with the same key has already been added. Key: Id错误,核心原因是存储过程返回的结果集中存在两个同名的Id列,EF Core在做结果到实体的映射时,会将列名作为映射的唯一键,重复的Id列触发了键冲突。

具体来看你的存储逻辑:SELECT语句中同时返回了Lists表的L.Id和Users表的U.Id,没有为重名列设置别名,最终返回的结果集里两个列的名称都是Id,EF Core无法区分这两个列,映射到GiftList实体时就抛出了重复键错误。另外你的O.Title列也没有对应别名,会导致映射到实体Occasion属性失败,值为空。

修复步骤

  1. 修改存储过程的SELECT语句,给重名列和需要匹配实体属性的列设置别名:
SELECT 
    L.Id,
    O.Title AS Occasion,
    U.Id AS UserId,
    L.Alias,
    L.AnotherRecipient,
    L.RecipientName,
    L.RecipientAddressId
FROM Lists AS L
JOIN Occasions AS O
    ON O.Id = L.OccasionId
JOIN Users AS U
    ON U.Id = L.UserId
WHERE
    L.UserId = @UserId
  1. 可选优化:你当前使用的字符串插值写法存在SQL注入风险,建议改成参数化查询:
// 需要先引用命名空间 Microsoft.Data.SqlClient
public List<IGiftList> GetUserLists(int userId)
{
    var userIdParam = new SqlParameter("@UserId", userId);
    var items = this.giftContext.Lists.FromSqlRaw("EXECUTE dbo.GetUserLists @UserId", userIdParam).ToList<IGiftList>();
    return items;
}

内容的提问来源于stack exchange,提问作者drethedevjs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:45:00