简体   繁体   English

C# 存储过程 FromSqlRaw 错误键已存在

[英]C# stored procedure FromSqlRaw error key already exist

I have a problem to run a stored procedure in EF.我在 EF 中运行存储过程时遇到问题。 If I execute the procedure from SSMS, it works fine, but from code I get this error:如果我从 SSMS 执行该过程,它工作正常,但从代码我得到这个错误:

System.ArgumentException: An item with the same key has already been added. System.ArgumentException:已添加具有相同键的项目。 Key: Id键:标识

at System.Collections.Generic.Dictionary 2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable 1 source, Func 2 keySelector, Func 2 elementSelector, IEqualityComparer 1 comparer) at Microsoft.EntityFrameworkCore.Query.Internal.FromSqlQueryingEnumerable 1.BuildIndexMap(IReadOnlyList 1 columnNames, DbDataReader dataReader) at Microsoft.EntityFrameworkCore.Query.Internal.FromSqlQueryingEnumerable 1.Enumerator.InitializeReader(DbContext _, Boolean result)在 System.Collections.Generic.Dictionary 2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable 2 keySelector, Func源 12,FuncSelect 元素1 comparer) at Microsoft.EntityFrameworkCore.Query.Internal.FromSqlQueryingEnumerable 1.BuildIndexMap(IReadOnlyList 1 columnNames, DbDataReader dataReader) at Microsoft.EntityFrameworkCore.Query.Internal.FromSqlQueryingEnumerable 1.Enumerator.InitializeReader(DbContext _, Boolean 结果)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func 3 operation, Func 3 verifySucceeded)在 Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state,Func 3 operation, Func 3 验证成功)
at Microsoft.EntityFrameworkCore.Query.Internal.FromSqlQueryingEnumerable 1.Enumerator.MoveNext() at System.Collections.Generic.List 1..ctor(IEnumerable 1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable 1 source)在 Microsoft.EntityFrameworkCore.Query.Internal.FromSqlQueryingEnumerable 1.Enumerator.MoveNext() at System.Collections.Generic.List 1..ctor(IEnumerable 1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable )
at MyseExchange.Controllers.UserController.GetMyTeamByUserId(Int32 userId)在 MyseExchange.Controllers.UserController.GetMyTeamByUserId(Int32 userId)
at lambda_method5(Closure, Object )在 lambda_method5(关闭,Object)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)在 Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper 映射器,ObjectMethodExecutor 执行器,Object controller,Object[] 参数)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker 调用程序,ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed 上下文)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(状态和下一个,范围和 scope,对象和 state,布尔值和已完成)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed 上下文)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(状态和下一个,范围和 scope,对象和 state,布尔值和已完成)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 调用程序,任务任务,IDisposable 范围)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端点端点,任务 requestTask,ILogger 记录器)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 上下文)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)在 Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)在 Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext,ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)

This is my code:这是我的代码:

var param = new SqlParameter[] {
                        new SqlParameter() {
                            ParameterName = "@userId",
                            SqlDbType =  System.Data.SqlDbType.Int,
                            Direction = System.Data.ParameterDirection.Input,
                            Value = 36
                        },
                        new SqlParameter() {
                            ParameterName = "@date",
                            SqlDbType =  System.Data.SqlDbType.VarChar,
                            Direction = System.Data.ParameterDirection.Input,
                            Value = testdate
                        }};

List<MyTeam> studentList = _context.MyTeam.FromSqlRaw("[dbo].[getMyTeamByUserId] @userId, @date", param).ToList();

I can not understand where the problem is, thanks in advance for the help我不明白问题出在哪里,在此先感谢您的帮助

Stored procedure:存储过程:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:      Stefano
-- Create Date: 
-- Description: 
-- =============================================
CREATE PROCEDURE getMyTeamByUserId
    (@userId bigint = 0,
     @date varchar(100) = '')
AS
BEGIN
    SET NOCOUNT ON

    SELECT
        [m].[Id], [m].[PlayerId], [m].[PurchaseDate], 
        [m].[PurchasePrice], [m].[UserId], 
        [p].[Id], [p].[Active], [p].[ActiveOnWallet], 
        [p].[CountryOfBirth], [p].[DateOfBirth], 
        [p].[FirstName], [p].[Foot], [p].[Heigth], [p].[IsLock], 
        [p].[LastName], [p].[MarketValue], [p].[MatchName], 
        [p].[Nationality], [p].[NationalityId], 
        [p].[PlaceOfBirth], [p].[PlayerId], [p].[Position], 
        [p].[ShirtNumber], [p].[SquadId], [p].[Status], 
        [p].[TransfertMarketId], [p].[Type], [p].[Value], 
        [p].[Weigth], 
        [s].[Id], [s].[CompetitionId], [s].[CompetitionName], 
        [s].[ContestantClubName], [s].[ContestantCode], 
        [s].[ContestantId], [s].[ContestantName], 
        [s].[ContestantShortName], 
        [s].[TournamentCalendarEndDate], 
        [s].[TournamentCalendarId], 
        [s].[TournamentCalendarStartDate], [s].[VenueId], 
        [s].[VenueName], 
        [u].[Id], [t0].[Id], [t0].[Date], [t0].[DevTurn], 
        [t0].[FullDate], [t0].[PlayerId], [t0].[Value]
    FROM
        [MyTeam] AS [m]
    LEFT JOIN 
        [User] AS [u] ON [m].[UserId] = [u].[Id]
    LEFT JOIN 
        [Player] AS [p] ON [m].[PlayerId] = [p].[Id]
    LEFT JOIN 
        [Squad] AS [s] ON [p].[SquadId] = [s].[Id]
    LEFT JOIN 
        (SELECT 
             [t].[Id], [t].[Date], [t].[DevTurn], [t].[FullDate], 
             [t].[PlayerId], [t].[Value]
         FROM 
             (SELECT 
                  [s0].[Id], [s0].[Date], [s0].[DevTurn], 
                  [s0].[FullDate], [s0].[PlayerId], [s0].[Value], 
                  ROW_NUMBER() OVER (PARTITION BY [s0].[PlayerId] ORDER BY [s0].[FullDate] DESC) AS [row]
              FROM 
                  [Stock] AS [s0]
              WHERE 
                  [s0].[Date] <= CONVERT(datetime, @date)) AS [t]
        WHERE 
            [t].[row] <= 1) AS [t0] ON [p].[Id] = [t0].[PlayerId]
    WHERE 
        [u].[Id] = @userId
    ORDER BY 
        [m].[Id], [u].[Id], [p].[Id], [s].[Id], 
        [t0].[PlayerId], [t0].[FullDate] DESC, [t0].[Id]
END

This may not be the only problem, but I do see one thing that's an issue.这可能不是唯一的问题,但我确实看到了一个问题。 You're returning a column called Id multiple times in your select statement.您在 select 语句中多次返回名为 Id 的列。 That works in SSMS but will fail when calling it from.FromSqlRaw().这在 SSMS 中有效,但在从.FromSqlRaw() 调用它时会失败。 I believe the我相信

"An item with the same key has already been added. Key: Id

at System.Collections.Generic.Dictionary2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)" 

error is referencing the attempt to insert these returned values into the List of class MyTeam.错误是指尝试将这些返回值插入到 class MyTeam 的列表中。 Your returned columns need to exactly match the class MyTeam you're returning them to.您返回的列需要与您将它们返回到的 class MyTeam 完全匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM