c# - 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
知道为什么我可能会收到此错误吗?
解决方案
这是因为你的Store Procedure's
两个字段是 L.Id
和U.Id
那些被视为Id
但是当涉及到与你的模型属性绑定时,Id
编译UserId
器在映射两个时遇到问题。所以最好的方法是使用 SQL Alias 来处理这个问题AS
。
U.Id AS UserId
会解决你的问题。
注意:如果选择查询中的主键相同,请记住通过
AS
uisng 将它们分开,而不是将它们映射为相同的键。
推荐阅读
- python - 多处理功能在 Raspberry pi 中不起作用:OSError: [Errno 16] Device or resource busy
- postgresql - raster2pgsql:“无法为 INSERT 语句分配内存”
- python - 在带有 GitHub 页面的 markdown 文件 (index.md) 中嵌入绘图交互式图表,而不是使用 Jekyll
- javascript - 在应用脚本中向历史日期添加天数
- python - 点击标签 Selenium 自动化
- javascript - 将枚举 JavaScript 转换为数组,并在数组中选择一个随机元素
- javascript - React - TypeError:无法设置未定义的属性'props'
- selenium - 如何自动化使用外部应用程序的网站?
- javascript - 为什么 firebase onAuthStateChanged 总是返回空值?
- excel - VBA 项目窗口中的文件夹已消失