C# 实体框架核心原始SQL错误:System.ArgumentException已添加具有相同密钥的项。关键字:Id

C# 实体框架核心原始SQL错误:System.ArgumentException已添加具有相同密钥的项。关键字:Id,c#,asp.net-core,.net-core,entity-framework-core,asp.net-core-webapi,C#,Asp.net Core,.net Core,Entity Framework Core,Asp.net Core Webapi,我使用的是.NET v5.0.100-preview.8.20417.9、ASP.NET Core Web API 5、Microsoft SQL Server 2019、实体框架Core v5.0.0-preview.8.20414.8 数据库 创建表[dbo]。[AspNetUsers] [Id][nvarchar]450不为空, [用户名][nvarchar]256空, [NormalizedUserName][nvarchar]256空, [电子邮件][nvarchar]256空, [N

我使用的是.NET v5.0.100-preview.8.20417.9、ASP.NET Core Web API 5、Microsoft SQL Server 2019、实体框架Core v5.0.0-preview.8.20414.8

数据库

创建表[dbo]。[AspNetUsers] [Id][nvarchar]450不为空, [用户名][nvarchar]256空, [NormalizedUserName][nvarchar]256空, [电子邮件][nvarchar]256空, [NormalizedEmail][nvarchar]256空, [电子邮件确认][位]不为空, [PasswordHash][nvarchar]最大为空, [SecurityStamp][nvarchar]最大为空, [ConcurrencyStamp][nvarchar]最大空值, [PhoneNumber][nvarchar]最大为空, [phonenumberconfirm][bit]不为空, [TwoFactorEnabled][bit]不为空, [LockoutEnd][datetimeoffset]7空, [LockoutEnabled][bit]不为空, [AccessFailedCount][int]不为空, [Fullname][nvarchar]最大空值, [AliasName][nvarchar]最大为空, [SecondMobile][nvarchar]最大空值, [关于][nvarchar]最大空值, [Created][datetime2]7空, [Modified][datetime2]7空, 约束[PK_AspNetUsers] 主键群集[Id]ASC 当PAD_INDEX=OFF,STATISTICS_norecocomputer=OFF时, 忽略\u DUP\u KEY=OFF,允许\u ROW\u LOCKS=ON, 允许页面锁定=打开,优化顺序键=关闭打开[主] 在[PRIMARY]文本上图像在[PRIMARY]上 去 创建表[dbo].[trusted_person] [id][int]标识1,1不为空, [fullname][nvarchar]512空, [别名][nvarchar]512空, [电子邮件][nvarchar]512空, [电话号码1][nvarchar]50空, [电话号码2][nvarchar]50空, [电话号码3][nvarchar]50空, [relationship_id][int]NULL, [关于][nvarchar]最大值不为空, [avatar_id][int]NULL, [已创建][日期时间]空, [modified][datetime]空, 约束[PK\U受信任的人] 主键群集[id]ASC 当PAD_INDEX=OFF,STATISTICS_norecocomputer=OFF时, 忽略\u DUP\u KEY=OFF,允许\u ROW\u LOCKS=ON, 允许页面锁定=打开,优化顺序键=关闭打开[主] 在[PRIMARY]文本上图像在[PRIMARY]上 去 创建表[dbo]。[user\u trusted\u person] [user_id][nvarchar]450不为空, [trusted_person_id][int]不为空, 约束[PK\U用户\U受信任人] 主键群集[user\u id]ASC、[trusted\u person\u id]ASC 当PAD_INDEX=OFF,STATISTICS_norecocomputer=OFF时, 忽略\u DUP\u KEY=OFF,允许\u ROW\u LOCKS=ON, 允许页面锁定=打开,优化顺序键=关闭打开[主] 在[小学] 去 插入到[dbo].[AspNetUsers][Id],[UserName],[NormalizedUserName],[Email],[NormalizedMail],[EmailConfirmed],[PasswordHash],[SecurityStamp],[ConcurrencyStamp],[PhoneNumber],[PhoneNumberConfirmed],[TwoFactorEnabled],[LockoutEnd],[LockoutEnabled],[AccessFailedCount],[Fullname],[AliasName],[SecondMobile],[About],[Created],[修改] 数值N'4485e86d-3c2f-484f-a0b1-29e9c895bf9d',N'hanp2@example.io“,不”HANP2@example.io“,不”hanp2@example.io“,不”HANP2@EXAMPLE.IO“,1,N'AQAAAAAAAAACCAAAAAELJSFHHPWMLWHB6FWRW9F/6DXQntlZMMcBMLDeiq1Ekkwf7V0IE76Bm7HoHwXUGUNA==”,N'GTNEDRSWMSSTHAGZVL4N7HOEHECUX3KC5',N'49bc54f6-217a-43f2-872e-b39e0453b90b',N'090909878767',0,0,0,NULL,1,0,N'Nguyễn Phơng Há2',n'HaNP2',n'0123456765',n'PGĐkỹ 清华大学ật',卡斯特'2020-09-10T09:36:48.9768760'作为日期时间2,卡斯特'2020-09-10T09:36:48.9771728'作为日期时间2 去 插入到[dbo].[AspNetUsers][Id],[UserName],[NormalizedUserName],[Email],[NormalizedMail],[EmailConfirmed],[PasswordHash],[SecurityStamp],[ConcurrencyStamp],[PhoneNumber],[PhoneNumberConfirmed],[TwoFactorEnabled],[LockoutEnd],[LockoutEnabled],[AccessFailedCount],[Fullname],[AliasName],[SecondMobile],[About],[Created],[修改] 数值N'8ec8b490-bc7d-4468-af7f-9870ccd72981',N'tinlh@example.io“,不”TINLH@example.io“,不”tinlh@example.io“,不”TINLH@EXAMPLE.IO“,0,N'aqaaaaaaaaacqaaaemn05q50vk31c5v+GBm4JK9YdXXSDnugtplgn+o2u/eU2vJLNOyMl1t7EyENK5BGPQ==”,N'3iin7jkn5xckpe7pofwfnhlznhk7zkd',N'0559b9ec-9998-4183-84af-224aece1d12',NULL,0,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL,N'Fro新界终端开发商,卡斯特'2020-09-10T08:22:30.1337889'作为日期时间2,卡斯特'2020-09-10T08:22:30.1352528'作为日期时间2 去 插入到[dbo].[AspNetUsers][Id],[UserName],[NormalizedUserName],[Email],[NormalizedMail],[EmailConfirmed],[PasswordHash],[SecurityStamp],[ConcurrencyStamp],[PhoneNumber],[PhoneNumberConfirmed],[TwoFactorEnabled],[LockoutEnd],[LockoutEnabled],[AccessFailedCount],[Fullname],[AliasName],[SecondMobile],[About],[Created],[修改] 数值N'a9e23763-8285-4d4b-b466-e1d5d9287e43',N'hanp@example.io“,不”HANP@example.io“,不”hanp@example.io“,不”HANP@EXAMPLE.IO,1,N'AQAAAAACCAAAECIISI1XQ9KL+8/RIS+ztOU5sU+J2KFYODPOJPZFD9 xL6r3H10WNhi/VITbv2mtfA==',N'QDOW7EB5XF6CIQZ4H4JBRRLSANIGTHR',N'7eed1e98-ea18-4f4b-b017-c428adc2da73',N'0909878767',0,0,NULL,1,0,N'Nguyễn Phơng Hán'HaNP',n'0123456765',n'PGĐkỹ 清华大学ật',卡斯特'2020-09-09T16:38:37.7443193'作为日期时间2,卡斯特'2020-09-09T16:38:37.7444016'作为日期时间2 去 在上设置标识\u插入[dbo].[trusted\u person] 去 插入[dbo]。[trusted_person][id],[fullname],[alias_name],[email],[phone_number1],[phone_number2],[phone_number3],[relationship_id],[about],[avatar_id],[created],[modified] 价值观2,N'Nguyễn Thanh V–n',n'Thanh V–n',n'thanhvan@yahoo.com,N'0989873776',N'0989872777',N'0989876778',3,N'Nguyen Van',42,CASTN'2020-09-10T09:32:07.443'作为日期时间,空 去 插入[dbo]。[trusted_person][id],[fullname],[alias_name],[email],[phone_number1],[phone_number2],[phone_number3],[relationship_id],[about],[avatar_id],[created],[modified] 值3,N'Nguyen Van An',N'An',N'ductx@example.io,N'09876545',N'09876546',N'09876547',1,N'abc',1,CASTN'2020-09-10T14:38:15.130'作为日期时间,空 去 将标识插入[dbo].[trusted\u person]设置为关闭 去 插入[dbo].[user_trusted_person][user_id],[trusted_person_id]值N'4485e86d-3c2f-484f-a0b1-29e9c895bf9d',3 去 在SQLServerManagementStudio中,我可以查询它是否成功,返回1条记录

选择* 来自受信任的人t 左加入用户\u受信任的人\u ON u.trusted\u person\u id=t.id 左加入a.Id=u.user\u Id上的AspNetUsers a 式中a.Id='4485e86d-3c2f-484f-a0b1-29e9c895bf9d'; C代码:

使用制度; 可空禁用 命名空间shadow.Models { 公共部分类受托人 { 公共int Id{get;set;} 公共字符串全名{get;set;} 公共字符串别名{get;set;} 公共字符串电子邮件{get;set;} 公共字符串PhoneNumber1{get;set;} 公共字符串PhoneNumber2{get;set;} 公共字符串PhoneNumber3{get;set;} public int?RelationshipId{get;set;} 关于{get;set;}的公共字符串 公共int?AvatarId{get;set;} 公共日期时间?已创建{get;set;} 公共日期时间?已修改{get;set;} } } DbContext有TrustedPeople-TrustedPeople的复数形式

使用Microsoft.AspNetCore.Identity.EntityFrameworkCore; 使用Microsoft.EntityFrameworkCore; 使用阴影模型; 命名空间shadow.Data { 公共分部类ApplicationDbContext:IdentityDbContext


如何修复它?

由于查询返回许多名为“id”的列,因此出现此错误

尝试用select t.*替换select*


注意:如果a.Id={0},UserId,而不是a.Id='{0}',UserId

则会出现此错误,因为查询返回许多名为“Id”的列

尝试用select t.*替换select*


注意:其中a.Id={0},UserId,而不是其中a.Id='{0},UserId

什么是TrustedPerson?我只是在问题中添加了更多。什么是TrustedPerson?我添加了更多,TrustedPerson是Entity Framework Core数据库集中TrustedPerson的复数。您的数据上下文的生命周期是什么?TrustedPerson是什么?我只是在问题中添加了更多。什么是TrustedPerson?我添加了更多,TrustedPerson是复数f Entity Framework Core数据库集中的TrustedPerson。您的数据上下文的生存期是多少?没有错误,但返回0记录null。如果我在SQL Server Management Studio中查询,它将返回1记录。我认为您的理想是接近真正的解决方案。没有错误,但返回0记录null。如果我在SQL Server Management Studio中查询,它将返回1记录。我认为你的理想是接近真正的解决方案。
System.ArgumentException: An item with the same key has already been added. 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)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   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)
   at shadow.Controllers.UserTrustedPersonController.GetAllTrustedPersonsByUserId(String UserId) in D:\shadow_backend\Controllers\UserTrustedPersonController.cs:line 77
   at lambda_method9(Closure , Object )
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>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)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>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)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Cache-Control: no-cache
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate, br
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJFbWFpbCI6InRpbmxoQG1wc29sdXRpb25zLmlvIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZWlkZW50aWZpZXIiOiIyODI1MTVmZi00ODljLTRmOWMtODQ4Ny1hNzcyZDcyYzMxMDkiLCJleHAiOjE2MDIzMTQ5MzMsImlzcyI6Imh0dHA6Ly9tcHNvbHV0aW9ucy5pbyIsImF1ZCI6Imh0dHA6Ly9tcHNvbHV0aW9ucy5pbyJ9.l0_PH63k05RpjH6lEj7TJWHW0wP8VuhtfWugzs1jjhg
Host: localhost:5002
User-Agent: PostmanRuntime/7.26.5
Postman-Token: 3ecd1393-9865-4e80-93f9-d0f707ee2ad7

[HttpGet]
[Route("user")]
public async Task<ActionResult<IEnumerable<TrustedPerson>>> GetAllTrustedPersonsByUserId(string UserId)
{
    var items = _db.TrustedPeople
        .FromSqlRaw("" +
            " SELECT t.* FROM trusted_person t " +
            " LEFT JOIN user_trusted_person u ON u.trusted_person_id = t.id " +
            " LEFT JOIN AspNetUsers a ON a.Id = u.user_id " +
            " WHERE a.Id = {0}", UserId)
        .ToList();
    return Ok(items);
}