首页 > 解决方案 > GET 调用:已添加具有相同密钥的项目。键:ID

问题描述

我正在尝试使用 EF Core 调用 SQL Server 数据库中的存储过程。db 服务器使用 Docker 托管。问题是当我对控制器进行 GET 调用以访问服务时,它会停止一段时间,然后我收到此错误...

ArgumentException:已添加具有相同键的项目。键:ID

这是我的代码:

楷模

public interface IGiftList
{
   int Id { get; set; }
   string Occasion { get; set; }
   int UserId { get; set; }
   string Alias { get; set; }
   bool AnotherRecipient { get; set; }
   string RecipientName { get; set; }
   int RecipientAddressId { get; set; }
}

public class GiftList : IGiftList
{
   public int Id { get; set; }
   public string Occasion { get; set; }
   public int UserId { get; set; }
   public string Alias { get; set; }
   public bool AnotherRecipient { get; set; }
   public string RecipientName { get; set; }
   public int RecipientAddressId { get; set; }
   public List<Gift> Items { get; set;}
}

控制器

[HttpGet, Route("lists")]
public List<GiftList> GetUserLists([FromQuery] int userId)
{
   var lists = _giftService.GetUserLists(userId).Select(l => (GiftList)l).ToList();
   return lists;
}

服务

public List<IGiftList> GetUserLists(int userId)
{
   var items = this.giftContext.Lists.FromSqlRaw($"EXECUTE dbo.GetUserLists @UserId={userId}").ToList<IGiftList>(); <--Exception gets raised here.
   return items;
}

存储过程

CREATE PROCEDURE dbo.GetUserLists 
(
    @UserId INT
)
AS
DECLARE @ListId INT

SET @ListId = (SELECT TOP (1) Id FROM Lists WHERE UserId = @UserId);

SELECT 
    L.Id,
    O.Title,
    U.Id,
    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

知道为什么我可能会收到此错误吗?

标签: c#sql-server.net-coreasp.net-core-mvcasp.net-core-webapi

解决方案


这是因为你的Store Procedure's两个字段是 L.IdU.Id那些被视为Id但是当涉及到与你的模型属性绑定时,Id编译UserId器在映射两个时遇到问题。所以最好的方法是使用 SQL Alias 来处理这个问题AS

U.Id AS UserId会解决你的问题。

注意:如果选择查询中的主键相同,请记住通过ASuisng 将它们分开,而不是将它们映射为相同的键。


推荐阅读